idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
143,300 | public static void withInstance ( String url , Closure c ) throws SQLException { Sql sql = null ; try { sql = newInstance ( url ) ; c . call ( sql ) ; } finally { if ( sql != null ) sql . close ( ) ; } } | Invokes a closure passing it a new Sql instance created from the given JDBC connection URL . The created connection will be closed if required . | 59 | 29 |
143,301 | public synchronized void withTransaction ( Closure closure ) throws SQLException { boolean savedCacheConnection = cacheConnection ; cacheConnection = true ; Connection connection = null ; boolean savedAutoCommit = true ; try { connection = createConnection ( ) ; savedAutoCommit = connection . getAutoCommit ( ) ; connection . setAutoCommit ( false ) ; callClosurePossiblyWithConnection ( closure , connection ) ; connection . commit ( ) ; } catch ( SQLException e ) { handleError ( connection , e ) ; throw e ; } catch ( RuntimeException e ) { handleError ( connection , e ) ; throw e ; } catch ( Error e ) { handleError ( connection , e ) ; throw e ; } catch ( Exception e ) { handleError ( connection , e ) ; throw new SQLException ( "Unexpected exception during transaction" , e ) ; } finally { if ( connection != null ) { try { connection . setAutoCommit ( savedAutoCommit ) ; } catch ( SQLException e ) { LOG . finest ( "Caught exception resetting auto commit: " + e . getMessage ( ) + " - continuing" ) ; } } cacheConnection = false ; closeResources ( connection , null ) ; cacheConnection = savedCacheConnection ; if ( dataSource != null && ! cacheConnection ) { useConnection = null ; } } } | Performs the closure within a transaction using a cached connection . If the closure takes a single argument it will be called with the connection otherwise it will be called with no arguments . | 289 | 35 |
143,302 | public static Object invoke ( Object object , String methodName , Object [ ] parameters ) { try { Class [ ] classTypes = new Class [ parameters . length ] ; for ( int i = 0 ; i < classTypes . length ; i ++ ) { classTypes [ i ] = parameters [ i ] . getClass ( ) ; } Method method = object . getClass ( ) . getMethod ( methodName , classTypes ) ; return method . invoke ( object , parameters ) ; } catch ( Throwable t ) { return InvokerHelper . invokeMethod ( object , methodName , parameters ) ; } } | Invoke a method through reflection . Falls through to using the Invoker to call the method in case the reflection call fails .. | 125 | 25 |
143,303 | public static String [ ] tokenizeUnquoted ( String s ) { List tokens = new LinkedList ( ) ; int first = 0 ; while ( first < s . length ( ) ) { first = skipWhitespace ( s , first ) ; int last = scanToken ( s , first ) ; if ( first < last ) { tokens . add ( s . substring ( first , last ) ) ; } first = last ; } return ( String [ ] ) tokens . toArray ( new String [ tokens . size ( ) ] ) ; } | This method tokenizes a string by space characters but ignores spaces in quoted parts that are parts in or . The method does allows the usage of in and in . The space character between tokens is not returned . | 115 | 41 |
143,304 | @ SuppressWarnings ( "unchecked" ) private void addPrivateFieldsAccessors ( ClassNode node ) { Set < ASTNode > accessedFields = ( Set < ASTNode > ) node . getNodeMetaData ( StaticTypesMarker . PV_FIELDS_ACCESS ) ; if ( accessedFields == null ) return ; Map < String , MethodNode > privateConstantAccessors = ( Map < String , MethodNode > ) node . getNodeMetaData ( PRIVATE_FIELDS_ACCESSORS ) ; if ( privateConstantAccessors != null ) { // already added return ; } int acc = - 1 ; privateConstantAccessors = new HashMap < String , MethodNode > ( ) ; final int access = Opcodes . ACC_STATIC | Opcodes . ACC_PUBLIC | Opcodes . ACC_SYNTHETIC ; for ( FieldNode fieldNode : node . getFields ( ) ) { if ( accessedFields . contains ( fieldNode ) ) { acc ++ ; Parameter param = new Parameter ( node . getPlainNodeReference ( ) , "$that" ) ; Expression receiver = fieldNode . isStatic ( ) ? new ClassExpression ( node ) : new VariableExpression ( param ) ; Statement stmt = new ExpressionStatement ( new PropertyExpression ( receiver , fieldNode . getName ( ) ) ) ; MethodNode accessor = node . addMethod ( "pfaccess$" + acc , access , fieldNode . getOriginType ( ) , new Parameter [ ] { param } , ClassNode . EMPTY_ARRAY , stmt ) ; privateConstantAccessors . put ( fieldNode . getName ( ) , accessor ) ; } } node . setNodeMetaData ( PRIVATE_FIELDS_ACCESSORS , privateConstantAccessors ) ; } | Adds special accessors for private constants so that inner classes can retrieve them . | 396 | 15 |
143,305 | public static boolean isPostJDK5 ( String bytecodeVersion ) { return JDK5 . equals ( bytecodeVersion ) || JDK6 . equals ( bytecodeVersion ) || JDK7 . equals ( bytecodeVersion ) || JDK8 . equals ( bytecodeVersion ) ; } | Checks if the specified bytecode version string represents a JDK 1 . 5 + compatible bytecode version . | 61 | 22 |
143,306 | public void setTargetDirectory ( String directory ) { if ( directory != null && directory . length ( ) > 0 ) { this . targetDirectory = new File ( directory ) ; } else { this . targetDirectory = null ; } } | Sets the target directory . | 48 | 6 |
143,307 | protected synchronized Class loadClass ( final String name , boolean resolve ) throws ClassNotFoundException { Class c = this . findLoadedClass ( name ) ; if ( c != null ) return c ; c = ( Class ) customClasses . get ( name ) ; if ( c != null ) return c ; try { c = oldFindClass ( name ) ; } catch ( ClassNotFoundException cnfe ) { // IGNORE } if ( c == null ) c = super . loadClass ( name , resolve ) ; if ( resolve ) resolveClass ( c ) ; return c ; } | loads a class using the name of the class | 123 | 9 |
143,308 | public NodeList getAt ( String name ) { NodeList answer = new NodeList ( ) ; for ( Object child : this ) { if ( child instanceof Node ) { Node childNode = ( Node ) child ; Object temp = childNode . get ( name ) ; if ( temp instanceof Collection ) { answer . addAll ( ( Collection ) temp ) ; } else { answer . add ( temp ) ; } } } return answer ; } | Provides lookup of elements by non - namespaced name . | 92 | 12 |
143,309 | public String text ( ) { String previousText = null ; StringBuilder buffer = null ; for ( Object child : this ) { String text = null ; if ( child instanceof String ) { text = ( String ) child ; } else if ( child instanceof Node ) { text = ( ( Node ) child ) . text ( ) ; } if ( text != null ) { if ( previousText == null ) { previousText = text ; } else { if ( buffer == null ) { buffer = new StringBuilder ( ) ; buffer . append ( previousText ) ; } buffer . append ( text ) ; } } } if ( buffer != null ) { return buffer . toString ( ) ; } if ( previousText != null ) { return previousText ; } return "" ; } | Returns the text value of all of the elements in the collection . | 160 | 13 |
143,310 | private boolean isAllNumeric ( TokenStream stream ) { List < Token > tokens = ( ( NattyTokenSource ) stream . getTokenSource ( ) ) . getTokens ( ) ; for ( Token token : tokens ) { try { Integer . parseInt ( token . getText ( ) ) ; } catch ( NumberFormatException e ) { return false ; } } return true ; } | Determines if a token stream contains only numeric tokens | 80 | 11 |
143,311 | private List < TokenStream > collectTokenStreams ( TokenStream stream ) { // walk through the token stream and build a collection // of sub token streams that represent possible date locations List < Token > currentGroup = null ; List < List < Token > > groups = new ArrayList < List < Token > > ( ) ; Token currentToken ; int currentTokenType ; StringBuilder tokenString = new StringBuilder ( ) ; while ( ( currentToken = stream . getTokenSource ( ) . nextToken ( ) ) . getType ( ) != DateLexer . EOF ) { currentTokenType = currentToken . getType ( ) ; tokenString . append ( DateParser . tokenNames [ currentTokenType ] ) . append ( " " ) ; // we're currently NOT collecting for a possible date group if ( currentGroup == null ) { // skip over white space and known tokens that cannot be the start of a date if ( currentTokenType != DateLexer . WHITE_SPACE && DateParser . FOLLOW_empty_in_parse186 . member ( currentTokenType ) ) { currentGroup = new ArrayList < Token > ( ) ; currentGroup . add ( currentToken ) ; } } // we're currently collecting else { // preserve white space if ( currentTokenType == DateLexer . WHITE_SPACE ) { currentGroup . add ( currentToken ) ; } else { // if this is an unknown token, we'll close out the current group if ( currentTokenType == DateLexer . UNKNOWN ) { addGroup ( currentGroup , groups ) ; currentGroup = null ; } // otherwise, the token is known and we're currently collecting for // a group, so we'll add it to the current group else { currentGroup . add ( currentToken ) ; } } } } if ( currentGroup != null ) { addGroup ( currentGroup , groups ) ; } _logger . info ( "STREAM: " + tokenString . toString ( ) ) ; List < TokenStream > streams = new ArrayList < TokenStream > ( ) ; for ( List < Token > group : groups ) { if ( ! group . isEmpty ( ) ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "GROUP: " ) ; for ( Token token : group ) { builder . append ( DateParser . tokenNames [ token . getType ( ) ] ) . append ( " " ) ; } _logger . info ( builder . toString ( ) ) ; streams . add ( new CommonTokenStream ( new NattyTokenSource ( group ) ) ) ; } } return streams ; } | Scans the given token global token stream for a list of sub - token streams representing those portions of the global stream that may contain date time information | 544 | 29 |
143,312 | private void addGroup ( List < Token > group , List < List < Token > > groups ) { if ( group . isEmpty ( ) ) return ; // remove trailing tokens that should be ignored while ( ! group . isEmpty ( ) && IGNORED_TRAILING_TOKENS . contains ( group . get ( group . size ( ) - 1 ) . getType ( ) ) ) { group . remove ( group . size ( ) - 1 ) ; } // if the group still has some tokens left, we'll add it to our list of groups if ( ! group . isEmpty ( ) ) { groups . add ( group ) ; } } | Cleans up the given group and adds it to the list of groups if still valid | 137 | 17 |
143,313 | public void seekToDayOfWeek ( String direction , String seekType , String seekAmount , String dayOfWeek ) { int dayOfWeekInt = Integer . parseInt ( dayOfWeek ) ; int seekAmountInt = Integer . parseInt ( seekAmount ) ; assert ( direction . equals ( DIR_LEFT ) || direction . equals ( DIR_RIGHT ) ) ; assert ( seekType . equals ( SEEK_BY_DAY ) || seekType . equals ( SEEK_BY_WEEK ) ) ; assert ( dayOfWeekInt >= 1 && dayOfWeekInt <= 7 ) ; markDateInvocation ( ) ; int sign = direction . equals ( DIR_RIGHT ) ? 1 : - 1 ; if ( seekType . equals ( SEEK_BY_WEEK ) ) { // set our calendar to this weeks requested day of the week, // then add or subtract the week(s) _calendar . set ( Calendar . DAY_OF_WEEK , dayOfWeekInt ) ; _calendar . add ( Calendar . DAY_OF_YEAR , seekAmountInt * 7 * sign ) ; } else if ( seekType . equals ( SEEK_BY_DAY ) ) { // find the closest day do { _calendar . add ( Calendar . DAY_OF_YEAR , sign ) ; } while ( _calendar . get ( Calendar . DAY_OF_WEEK ) != dayOfWeekInt ) ; // now add/subtract any additional days if ( seekAmountInt > 0 ) { _calendar . add ( Calendar . WEEK_OF_YEAR , ( seekAmountInt - 1 ) * sign ) ; } } } | seeks to a specified day of the week in the past or future . | 354 | 15 |
143,314 | public void seekToDayOfMonth ( String dayOfMonth ) { int dayOfMonthInt = Integer . parseInt ( dayOfMonth ) ; assert ( dayOfMonthInt >= 1 && dayOfMonthInt <= 31 ) ; markDateInvocation ( ) ; dayOfMonthInt = Math . min ( dayOfMonthInt , _calendar . getActualMaximum ( Calendar . DAY_OF_MONTH ) ) ; _calendar . set ( Calendar . DAY_OF_MONTH , dayOfMonthInt ) ; } | Seeks to the given day within the current month | 110 | 10 |
143,315 | public void seekToDayOfYear ( String dayOfYear ) { int dayOfYearInt = Integer . parseInt ( dayOfYear ) ; assert ( dayOfYearInt >= 1 && dayOfYearInt <= 366 ) ; markDateInvocation ( ) ; dayOfYearInt = Math . min ( dayOfYearInt , _calendar . getActualMaximum ( Calendar . DAY_OF_YEAR ) ) ; _calendar . set ( Calendar . DAY_OF_YEAR , dayOfYearInt ) ; } | Seeks to the given day within the current year | 110 | 10 |
143,316 | public void seekToMonth ( String direction , String seekAmount , String month ) { int seekAmountInt = Integer . parseInt ( seekAmount ) ; int monthInt = Integer . parseInt ( month ) ; assert ( direction . equals ( DIR_LEFT ) || direction . equals ( DIR_RIGHT ) ) ; assert ( monthInt >= 1 && monthInt <= 12 ) ; markDateInvocation ( ) ; // set the day to the first of month. This step is necessary because if we seek to the // current day of a month whose number of days is less than the current day, we will // pushed into the next month. _calendar . set ( Calendar . DAY_OF_MONTH , 1 ) ; // seek to the appropriate year if ( seekAmountInt > 0 ) { int currentMonth = _calendar . get ( Calendar . MONTH ) + 1 ; int sign = direction . equals ( DIR_RIGHT ) ? 1 : - 1 ; int numYearsToShift = seekAmountInt + ( currentMonth == monthInt ? 0 : ( currentMonth < monthInt ? sign > 0 ? - 1 : 0 : sign > 0 ? 0 : - 1 ) ) ; _calendar . add ( Calendar . YEAR , ( numYearsToShift * sign ) ) ; } // now set the month _calendar . set ( Calendar . MONTH , monthInt - 1 ) ; } | seeks to a particular month | 294 | 6 |
143,317 | public void setExplicitTime ( String hours , String minutes , String seconds , String amPm , String zoneString ) { int hoursInt = Integer . parseInt ( hours ) ; int minutesInt = minutes != null ? Integer . parseInt ( minutes ) : 0 ; assert ( amPm == null || amPm . equals ( AM ) || amPm . equals ( PM ) ) ; assert ( hoursInt >= 0 ) ; assert ( minutesInt >= 0 && minutesInt < 60 ) ; markTimeInvocation ( amPm ) ; // reset milliseconds to 0 _calendar . set ( Calendar . MILLISECOND , 0 ) ; // if no explicit zone is given, we use our own TimeZone zone = null ; if ( zoneString != null ) { if ( zoneString . startsWith ( PLUS ) || zoneString . startsWith ( MINUS ) ) { zoneString = GMT + zoneString ; } zone = TimeZone . getTimeZone ( zoneString ) ; } _calendar . setTimeZone ( zone != null ? zone : _defaultTimeZone ) ; _calendar . set ( Calendar . HOUR_OF_DAY , hoursInt ) ; // hours greater than 12 are in 24-hour time if ( hoursInt <= 12 ) { int amPmInt = amPm == null ? ( hoursInt >= 12 ? Calendar . PM : Calendar . AM ) : amPm . equals ( PM ) ? Calendar . PM : Calendar . AM ; _calendar . set ( Calendar . AM_PM , amPmInt ) ; // calendar is whacky at 12 o'clock (must use 0) if ( hoursInt == 12 ) hoursInt = 0 ; _calendar . set ( Calendar . HOUR , hoursInt ) ; } if ( seconds != null ) { int secondsInt = Integer . parseInt ( seconds ) ; assert ( secondsInt >= 0 && secondsInt < 60 ) ; _calendar . set ( Calendar . SECOND , secondsInt ) ; } else { _calendar . set ( Calendar . SECOND , 0 ) ; } _calendar . set ( Calendar . MINUTE , minutesInt ) ; } | Sets the the time of day | 450 | 7 |
143,318 | public void seekToHoliday ( String holidayString , String direction , String seekAmount ) { Holiday holiday = Holiday . valueOf ( holidayString ) ; assert ( holiday != null ) ; seekToIcsEvent ( HOLIDAY_ICS_FILE , holiday . getSummary ( ) , direction , seekAmount ) ; } | Seeks forward or backwards to a particular holiday based on the current date | 66 | 14 |
143,319 | public void seekToHolidayYear ( String holidayString , String yearString ) { Holiday holiday = Holiday . valueOf ( holidayString ) ; assert ( holiday != null ) ; seekToIcsEventYear ( HOLIDAY_ICS_FILE , yearString , holiday . getSummary ( ) ) ; } | Seeks to the given holiday within the given year | 63 | 10 |
143,320 | public void seekToSeason ( String seasonString , String direction , String seekAmount ) { Season season = Season . valueOf ( seasonString ) ; assert ( season != null ) ; seekToIcsEvent ( SEASON_ICS_FILE , season . getSummary ( ) , direction , seekAmount ) ; } | Seeks forward or backwards to a particular season based on the current date | 64 | 14 |
143,321 | public void seekToSeasonYear ( String seasonString , String yearString ) { Season season = Season . valueOf ( seasonString ) ; assert ( season != null ) ; seekToIcsEventYear ( SEASON_ICS_FILE , yearString , season . getSummary ( ) ) ; } | Seeks to the given season within the given year | 61 | 10 |
143,322 | private void resetCalendar ( ) { _calendar = getCalendar ( ) ; if ( _defaultTimeZone != null ) { _calendar . setTimeZone ( _defaultTimeZone ) ; } _currentYear = _calendar . get ( Calendar . YEAR ) ; } | Resets the calendar | 59 | 4 |
143,323 | private Date seasonalDateFromIcs ( String icsFileName , String eventSummary , int year ) { Map < Integer , Date > dates = getDatesFromIcs ( icsFileName , eventSummary , year , year ) ; return dates . get ( year - ( eventSummary . equals ( Holiday . NEW_YEARS_EVE . getSummary ( ) ) ? 1 : 0 ) ) ; } | Finds and returns the date for the given event summary and year within the given ics file or null if not present . | 87 | 25 |
143,324 | private void markDateInvocation ( ) { _updatePreviousDates = ! _dateGivenInGroup ; _dateGivenInGroup = true ; _dateGroup . setDateInferred ( false ) ; if ( _firstDateInvocationInGroup ) { // if a time has been given within the current date group, // we capture the current time before resetting the calendar if ( _timeGivenInGroup ) { int hours = _calendar . get ( Calendar . HOUR_OF_DAY ) ; int minutes = _calendar . get ( Calendar . MINUTE ) ; int seconds = _calendar . get ( Calendar . SECOND ) ; resetCalendar ( ) ; _calendar . set ( Calendar . HOUR_OF_DAY , hours ) ; _calendar . set ( Calendar . MINUTE , minutes ) ; _calendar . set ( Calendar . SECOND , seconds ) ; } else { resetCalendar ( ) ; } _firstDateInvocationInGroup = false ; } } | ensures that the first invocation of a date seeking rule is captured | 209 | 13 |
143,325 | private Calendar cleanHistCalendar ( Calendar cal ) { cal . set ( Calendar . MILLISECOND , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . MINUTE , 0 ) ; cal . set ( Calendar . HOUR , 0 ) ; return cal ; } | Put everything smaller than days at 0 | 65 | 7 |
143,326 | public static Calendar parseDividendDate ( String date ) { if ( ! Utils . isParseable ( date ) ) { return null ; } date = date . trim ( ) ; SimpleDateFormat format = new SimpleDateFormat ( Utils . getDividendDateFormat ( date ) , Locale . US ) ; format . setTimeZone ( TimeZone . getTimeZone ( YahooFinance . TIMEZONE ) ) ; try { Calendar today = Calendar . getInstance ( TimeZone . getTimeZone ( YahooFinance . TIMEZONE ) ) ; Calendar parsedDate = Calendar . getInstance ( TimeZone . getTimeZone ( YahooFinance . TIMEZONE ) ) ; parsedDate . setTime ( format . parse ( date ) ) ; if ( parsedDate . get ( Calendar . YEAR ) == 1970 ) { // Not really clear which year the dividend date is... making a reasonable guess. int monthDiff = parsedDate . get ( Calendar . MONTH ) - today . get ( Calendar . MONTH ) ; int year = today . get ( Calendar . YEAR ) ; if ( monthDiff > 6 ) { year -= 1 ; } else if ( monthDiff < - 6 ) { year += 1 ; } parsedDate . set ( Calendar . YEAR , year ) ; } return parsedDate ; } catch ( ParseException ex ) { log . warn ( "Failed to parse dividend date: " + date ) ; log . debug ( "Failed to parse dividend date: " + date , ex ) ; return null ; } } | Used to parse the dividend dates . Returns null if the date cannot be parsed . | 322 | 16 |
143,327 | public static TimeZone get ( String suffix ) { if ( SUFFIX_TIMEZONES . containsKey ( suffix ) ) { return SUFFIX_TIMEZONES . get ( suffix ) ; } log . warn ( "Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York" , suffix ) ; return SUFFIX_TIMEZONES . get ( "" ) ; } | Get the time zone for a specific exchange suffix | 88 | 9 |
143,328 | public static TimeZone getStockTimeZone ( String symbol ) { // First check if it's a known stock index if ( INDEX_TIMEZONES . containsKey ( symbol ) ) { return INDEX_TIMEZONES . get ( symbol ) ; } if ( ! symbol . contains ( "." ) ) { return ExchangeTimeZone . get ( "" ) ; } String [ ] split = symbol . split ( "\\." ) ; return ExchangeTimeZone . get ( split [ split . length - 1 ] ) ; } | Get the time zone for a specific stock or index . For stocks the exchange suffix is extracted from the stock symbol to retrieve the time zone . | 108 | 28 |
143,329 | @ Override protected Class getPrototypeClass ( Video content ) { Class prototypeClass ; if ( content . isFavorite ( ) ) { prototypeClass = FavoriteVideoRenderer . class ; } else if ( content . isLive ( ) ) { prototypeClass = LiveVideoRenderer . class ; } else { prototypeClass = LikeVideoRenderer . class ; } return prototypeClass ; } | Method to declare Video - VideoRenderer mapping . Favorite videos will be rendered using FavoriteVideoRenderer . Live videos will be rendered using LiveVideoRenderer . Liked videos will be rendered using LikeVideoRenderer . | 82 | 48 |
143,330 | @ Override public int getItemViewType ( int position ) { T content = getItem ( position ) ; return rendererBuilder . getItemViewType ( content ) ; } | Indicate to the RecyclerView the type of Renderer used to one position using a numeric value . | 37 | 22 |
143,331 | @ Override public RendererViewHolder onCreateViewHolder ( ViewGroup viewGroup , int viewType ) { rendererBuilder . withParent ( viewGroup ) ; rendererBuilder . withLayoutInflater ( LayoutInflater . from ( viewGroup . getContext ( ) ) ) ; rendererBuilder . withViewType ( viewType ) ; RendererViewHolder viewHolder = rendererBuilder . buildRendererViewHolder ( ) ; if ( viewHolder == null ) { throw new NullRendererBuiltException ( "RendererBuilder have to return a not null viewHolder" ) ; } return viewHolder ; } | One of the two main methods in this class . Creates a RendererViewHolder instance with a Renderer inside ready to be used . The RendererBuilder to create a RendererViewHolder using the information given as parameter . | 140 | 48 |
143,332 | @ Override public void onBindViewHolder ( RendererViewHolder viewHolder , int position ) { T content = getItem ( position ) ; Renderer < T > renderer = viewHolder . getRenderer ( ) ; if ( renderer == null ) { throw new NullRendererBuiltException ( "RendererBuilder have to return a not null renderer" ) ; } renderer . setContent ( content ) ; updateRendererExtraValues ( content , renderer , position ) ; renderer . render ( ) ; } | Given a RendererViewHolder passed as argument and a position renders the view using the Renderer previously stored into the RendererViewHolder . | 118 | 30 |
143,333 | public void diffUpdate ( List < T > newList ) { if ( getCollection ( ) . size ( ) == 0 ) { addAll ( newList ) ; notifyDataSetChanged ( ) ; } else { DiffCallback diffCallback = new DiffCallback ( collection , newList ) ; DiffUtil . DiffResult diffResult = DiffUtil . calculateDiff ( diffCallback ) ; clear ( ) ; addAll ( newList ) ; diffResult . dispatchUpdatesTo ( this ) ; } } | Provides a ready to use diff update for our adapter based on the implementation of the standard equals method from Object . | 103 | 23 |
143,334 | public RendererBuilder < T > withPrototype ( Renderer < ? extends T > renderer ) { if ( renderer == null ) { throw new NeedsPrototypesException ( "RendererBuilder can't use a null Renderer<T> instance as prototype" ) ; } this . prototypes . add ( renderer ) ; return this ; } | Add a Renderer instance as prototype . | 73 | 8 |
143,335 | public < G extends T > RendererBuilder < T > bind ( Class < G > clazz , Renderer < ? extends G > prototype ) { if ( clazz == null || prototype == null ) { throw new IllegalArgumentException ( "The binding RecyclerView binding can't be configured using null instances" ) ; } prototypes . add ( prototype ) ; binding . put ( clazz , prototype . getClass ( ) ) ; return this ; } | Given a class configures the binding between a class and a Renderer class . | 95 | 16 |
143,336 | int getItemViewType ( T content ) { Class prototypeClass = getPrototypeClass ( content ) ; validatePrototypeClass ( prototypeClass ) ; return getItemViewType ( prototypeClass ) ; } | Return the item view type used by the adapter to implement recycle mechanism . | 42 | 14 |
143,337 | protected Renderer build ( ) { validateAttributes ( ) ; Renderer renderer ; if ( isRecyclable ( convertView , content ) ) { renderer = recycle ( convertView , content ) ; } else { renderer = createRenderer ( content , parent ) ; } return renderer ; } | Main method of this class related to ListView widget . This method is the responsible of recycle or create a new Renderer instance with all the needed information to implement the rendering . This method will validate all the attributes passed in the builder constructor and will check if can recycle or has to create a new Renderer instance . | 65 | 63 |
143,338 | protected RendererViewHolder buildRendererViewHolder ( ) { validateAttributesToCreateANewRendererViewHolder ( ) ; Renderer renderer = getPrototypeByIndex ( viewType ) . copy ( ) ; renderer . onCreate ( null , layoutInflater , parent ) ; return new RendererViewHolder ( renderer ) ; } | Main method of this class related to RecyclerView widget . This method is the responsible of create a new Renderer instance with all the needed information to implement the rendering . This method will validate all the attributes passed in the builder constructor and will create a RendererViewHolder instance . | 79 | 58 |
143,339 | private Renderer recycle ( View convertView , T content ) { Renderer renderer = ( Renderer ) convertView . getTag ( ) ; renderer . onRecycle ( content ) ; return renderer ; } | Recycles the Renderer getting it from the tag associated to the renderer root view . This view is not used with RecyclerView widget . | 45 | 31 |
143,340 | private Renderer createRenderer ( T content , ViewGroup parent ) { int prototypeIndex = getPrototypeIndex ( content ) ; Renderer renderer = getPrototypeByIndex ( prototypeIndex ) . copy ( ) ; renderer . onCreate ( content , layoutInflater , parent ) ; return renderer ; } | Create a Renderer getting a copy from the prototypes collection . | 68 | 12 |
143,341 | private Renderer getPrototypeByIndex ( final int prototypeIndex ) { Renderer prototypeSelected = null ; int i = 0 ; for ( Renderer prototype : prototypes ) { if ( i == prototypeIndex ) { prototypeSelected = prototype ; } i ++ ; } return prototypeSelected ; } | Search one prototype using the prototype index which is equals to the view type . This method has to be implemented because prototypes member is declared with Collection and that interface doesn t allow the client code to get one element by index . | 62 | 44 |
143,342 | private boolean isRecyclable ( View convertView , T content ) { boolean isRecyclable = false ; if ( convertView != null && convertView . getTag ( ) != null ) { Class prototypeClass = getPrototypeClass ( content ) ; validatePrototypeClass ( prototypeClass ) ; isRecyclable = prototypeClass . equals ( convertView . getTag ( ) . getClass ( ) ) ; } return isRecyclable ; } | Check if one Renderer is recyclable getting it from the convertView s tag and checking the class used . | 98 | 23 |
143,343 | private int getItemViewType ( Class prototypeClass ) { int itemViewType = - 1 ; for ( Renderer renderer : prototypes ) { if ( renderer . getClass ( ) . equals ( prototypeClass ) ) { itemViewType = getPrototypeIndex ( renderer ) ; break ; } } if ( itemViewType == - 1 ) { throw new PrototypeNotFoundException ( "Review your RendererBuilder implementation, you are returning one" + " prototype class not found in prototypes collection" ) ; } return itemViewType ; } | Return the Renderer class associated to the prototype . | 113 | 10 |
143,344 | private int getPrototypeIndex ( Renderer renderer ) { int index = 0 ; for ( Renderer prototype : prototypes ) { if ( prototype . getClass ( ) . equals ( renderer . getClass ( ) ) ) { break ; } index ++ ; } return index ; } | Return the index associated to the Renderer . | 59 | 9 |
143,345 | private void validateAttributes ( ) { if ( content == null ) { throw new NullContentException ( "RendererBuilder needs content to create Renderer instances" ) ; } if ( parent == null ) { throw new NullParentException ( "RendererBuilder needs a parent to inflate Renderer instances" ) ; } if ( layoutInflater == null ) { throw new NullLayoutInflaterException ( "RendererBuilder needs a LayoutInflater to inflate Renderer instances" ) ; } } | Throws one RendererException if the content parent or layoutInflater are null . | 108 | 18 |
143,346 | private void validateAttributesToCreateANewRendererViewHolder ( ) { if ( viewType == null ) { throw new NullContentException ( "RendererBuilder needs a view type to create a RendererViewHolder" ) ; } if ( layoutInflater == null ) { throw new NullLayoutInflaterException ( "RendererBuilder needs a LayoutInflater to create a RendererViewHolder" ) ; } if ( parent == null ) { throw new NullParentException ( "RendererBuilder needs a parent to create a RendererViewHolder" ) ; } } | Throws one RendererException if the viewType layoutInflater or parent are null . | 128 | 19 |
143,347 | protected Class getPrototypeClass ( T content ) { if ( prototypes . size ( ) == 1 ) { return prototypes . get ( 0 ) . getClass ( ) ; } else { return binding . get ( content . getClass ( ) ) ; } } | Method to be implemented by the RendererBuilder subtypes . In this method the library user will define the mapping between content and renderer class . | 53 | 29 |
143,348 | @ Override protected View inflate ( LayoutInflater inflater , ViewGroup parent ) { View inflatedView = inflater . inflate ( R . layout . video_renderer , parent , false ) ; /* * You don't have to use ButterKnife library to implement the mapping between your layout * and your widgets you can implement setUpView and hookListener methods declared in * Renderer<T> class. */ ButterKnife . bind ( this , inflatedView ) ; return inflatedView ; } | Inflate the main layout used to render videos in the list view . | 105 | 15 |
143,349 | @ Override public void render ( ) { Video video = getContent ( ) ; renderThumbnail ( video ) ; renderTitle ( video ) ; renderMarker ( video ) ; renderLabel ( ) ; } | Main render algorithm based on render the video thumbnail render the title render the marker and the label . | 42 | 19 |
143,350 | private void renderThumbnail ( Video video ) { Picasso . with ( getContext ( ) ) . cancelRequest ( thumbnail ) ; Picasso . with ( getContext ( ) ) . load ( video . getThumbnail ( ) ) . placeholder ( R . drawable . placeholder ) . into ( thumbnail ) ; } | Use picasso to render the video thumbnail into the thumbnail widget using a temporal placeholder . | 63 | 17 |
143,351 | public void onCreate ( T content , LayoutInflater layoutInflater , ViewGroup parent ) { this . content = content ; this . rootView = inflate ( layoutInflater , parent ) ; if ( rootView == null ) { throw new NotInflateViewException ( "Renderer instances have to return a not null view in inflateView method" ) ; } this . rootView . setTag ( this ) ; setUpView ( rootView ) ; hookListeners ( rootView ) ; } | Method called when the renderer is going to be created . This method has the responsibility of inflate the xml layout using the layoutInflater and the parent ViewGroup set itself to the tag and call setUpView and hookListeners methods . | 110 | 50 |
143,352 | Renderer copy ( ) { Renderer copy = null ; try { copy = ( Renderer ) this . clone ( ) ; } catch ( CloneNotSupportedException e ) { Log . e ( "Renderer" , "All your renderers should be clonables." ) ; } return copy ; } | Create a clone of the Renderer . This method is the base of the prototype mechanism implemented to avoid create new objects from RendererBuilder . Pay an special attention implementing clone method in Renderer subtypes . | 65 | 41 |
143,353 | @ Override public View getView ( int position , View convertView , ViewGroup parent ) { T content = getItem ( position ) ; rendererBuilder . withContent ( content ) ; rendererBuilder . withConvertView ( convertView ) ; rendererBuilder . withParent ( parent ) ; rendererBuilder . withLayoutInflater ( LayoutInflater . from ( parent . getContext ( ) ) ) ; Renderer < T > renderer = rendererBuilder . build ( ) ; if ( renderer == null ) { throw new NullRendererBuiltException ( "RendererBuilder have to return a not null Renderer" ) ; } updateRendererExtraValues ( content , renderer , position ) ; renderer . render ( ) ; return renderer . getRootView ( ) ; } | Main method of RendererAdapter . This method has the responsibility of update the RendererBuilder values and create or recycle a new Renderer . Once the renderer has been obtained the RendereBuilder will call the render method in the renderer and will return the Renderer root view to the ListView . | 171 | 61 |
143,354 | @ Override public Object instantiateItem ( ViewGroup parent , int position ) { T content = getItem ( position ) ; rendererBuilder . withContent ( content ) ; rendererBuilder . withParent ( parent ) ; rendererBuilder . withLayoutInflater ( LayoutInflater . from ( parent . getContext ( ) ) ) ; Renderer < T > renderer = rendererBuilder . build ( ) ; if ( renderer == null ) { throw new NullRendererBuiltException ( "RendererBuilder have to return a not null Renderer" ) ; } updateRendererExtraValues ( content , renderer , position ) ; renderer . render ( ) ; View view = renderer . getRootView ( ) ; parent . addView ( view ) ; return view ; } | Main method of VPRendererAdapter . This method has the responsibility of update the RendererBuilder values and create or recycle a new Renderer . Once the renderer has been obtained the RendereBuilder will call the render method in the renderer and will return the Renderer root view to the ViewPager . | 168 | 64 |
143,355 | public VideoCollection generate ( final int videoCount ) { List < Video > videos = new LinkedList < Video > ( ) ; for ( int i = 0 ; i < videoCount ; i ++ ) { Video video = generateRandomVideo ( ) ; videos . add ( video ) ; } return new VideoCollection ( videos ) ; } | Generate a VideoCollection with random data obtained form VIDEO_INFO map . You don t need o create your own AdapteeCollections . Review ListAdapteeCollection if needed . | 69 | 36 |
143,356 | private void initializeVideoInfo ( ) { VIDEO_INFO . put ( "The Big Bang Theory" , "http://thetvdb.com/banners/_cache/posters/80379-9.jpg" ) ; VIDEO_INFO . put ( "Breaking Bad" , "http://thetvdb.com/banners/_cache/posters/81189-22.jpg" ) ; VIDEO_INFO . put ( "Arrow" , "http://thetvdb.com/banners/_cache/posters/257655-15.jpg" ) ; VIDEO_INFO . put ( "Game of Thrones" , "http://thetvdb.com/banners/_cache/posters/121361-26.jpg" ) ; VIDEO_INFO . put ( "Lost" , "http://thetvdb.com/banners/_cache/posters/73739-2.jpg" ) ; VIDEO_INFO . put ( "How I met your mother" , "http://thetvdb.com/banners/_cache/posters/75760-29.jpg" ) ; VIDEO_INFO . put ( "Dexter" , "http://thetvdb.com/banners/_cache/posters/79349-24.jpg" ) ; VIDEO_INFO . put ( "Sleepy Hollow" , "http://thetvdb.com/banners/_cache/posters/269578-5.jpg" ) ; VIDEO_INFO . put ( "The Vampire Diaries" , "http://thetvdb.com/banners/_cache/posters/95491-27.jpg" ) ; VIDEO_INFO . put ( "Friends" , "http://thetvdb.com/banners/_cache/posters/79168-4.jpg" ) ; VIDEO_INFO . put ( "New Girl" , "http://thetvdb.com/banners/_cache/posters/248682-9.jpg" ) ; VIDEO_INFO . put ( "The Mentalist" , "http://thetvdb.com/banners/_cache/posters/82459-1.jpg" ) ; VIDEO_INFO . put ( "Sons of Anarchy" , "http://thetvdb.com/banners/_cache/posters/82696-1.jpg" ) ; } | Initialize VIDEO_INFO data . | 506 | 7 |
143,357 | private Video generateRandomVideo ( ) { Video video = new Video ( ) ; configureFavoriteStatus ( video ) ; configureLikeStatus ( video ) ; configureLiveStatus ( video ) ; configureTitleAndThumbnail ( video ) ; return video ; } | Create a random video . | 49 | 5 |
143,358 | protected final ByteBuffer parseContent ( ByteBuffer in ) throws BaseExceptions . ParserException { if ( contentComplete ( ) ) { throw new BaseExceptions . InvalidState ( "content already complete: " + _endOfContent ) ; } else { switch ( _endOfContent ) { case UNKNOWN_CONTENT : // This makes sense only for response parsing. Requests must always have // either Content-Length or Transfer-Encoding _endOfContent = EndOfContent . EOF_CONTENT ; _contentLength = Long . MAX_VALUE ; // Its up to the user to limit a body size return parseContent ( in ) ; case CONTENT_LENGTH : case EOF_CONTENT : return nonChunkedContent ( in ) ; case CHUNKED_CONTENT : return chunkedContent ( in ) ; default : throw new BaseExceptions . InvalidState ( "not implemented: " + _endOfContent ) ; } } } | Parses the buffer into body content | 202 | 8 |
143,359 | final protected void putChar ( char c ) { final int clen = _internalBuffer . length ; if ( clen == _bufferPosition ) { final char [ ] next = new char [ 2 * clen + 1 ] ; System . arraycopy ( _internalBuffer , 0 , next , 0 , _bufferPosition ) ; _internalBuffer = next ; } _internalBuffer [ _bufferPosition ++ ] = c ; } | Store the char in the internal buffer | 85 | 7 |
143,360 | final protected String getTrimmedString ( ) throws BadMessage { if ( _bufferPosition == 0 ) return "" ; int start = 0 ; boolean quoted = false ; // Look for start while ( start < _bufferPosition ) { final char ch = _internalBuffer [ start ] ; if ( ch == ' ' ) { quoted = true ; break ; } else if ( ch != HttpTokens . SPACE && ch != HttpTokens . TAB ) { break ; } start ++ ; } int end = _bufferPosition ; // Position is of next write // Look for end while ( end > start ) { final char ch = _internalBuffer [ end - 1 ] ; if ( quoted ) { if ( ch == ' ' ) break ; else if ( ch != HttpTokens . SPACE && ch != HttpTokens . TAB ) { throw new BadMessage ( "String might not quoted correctly: '" + getString ( ) + "'" ) ; } } else if ( ch != HttpTokens . SPACE && ch != HttpTokens . TAB ) break ; end -- ; } String str = new String ( _internalBuffer , start , end - start ) ; return str ; } | Returns the string in the buffer minus an leading or trailing whitespace or quotes | 247 | 15 |
143,361 | final protected char next ( final ByteBuffer buffer , boolean allow8859 ) throws BaseExceptions . BadMessage { if ( ! buffer . hasRemaining ( ) ) return HttpTokens . EMPTY_BUFF ; if ( _segmentByteLimit <= _segmentBytePosition ) { shutdownParser ( ) ; throw new BaseExceptions . BadMessage ( "Request length limit exceeded: " + _segmentByteLimit ) ; } final byte b = buffer . get ( ) ; _segmentBytePosition ++ ; // If we ended on a CR, make sure we are if ( _cr ) { if ( b != HttpTokens . LF ) { throw new BadCharacter ( "Invalid sequence: LF didn't follow CR: " + b ) ; } _cr = false ; return ( char ) b ; // must be LF } // Make sure its a valid character if ( b < HttpTokens . SPACE ) { if ( b == HttpTokens . CR ) { // Set the flag to check for _cr and just run again _cr = true ; return next ( buffer , allow8859 ) ; } else if ( b == HttpTokens . TAB || allow8859 && b < 0 ) { return ( char ) ( b & 0xff ) ; } else if ( b == HttpTokens . LF ) { return ( char ) b ; // A backend should accept a bare linefeed. http://tools.ietf.org/html/rfc2616#section-19.3 } else if ( isLenient ( ) ) { return HttpTokens . REPLACEMENT ; } else { shutdownParser ( ) ; throw new BadCharacter ( "Invalid char: '" + ( char ) ( b & 0xff ) + "', 0x" + Integer . toHexString ( b ) ) ; } } // valid ascii char return ( char ) b ; } | Removes CRs but returns LFs | 395 | 8 |
143,362 | protected int mapGanttBarHeight ( int height ) { switch ( height ) { case 0 : { height = 6 ; break ; } case 1 : { height = 8 ; break ; } case 2 : { height = 10 ; break ; } case 3 : { height = 12 ; break ; } case 4 : { height = 14 ; break ; } case 5 : { height = 18 ; break ; } case 6 : { height = 24 ; break ; } } return ( height ) ; } | This method maps the encoded height of a Gantt bar to the height in pixels . | 102 | 18 |
143,363 | protected TableFontStyle getColumnFontStyle ( byte [ ] data , int offset , Map < Integer , FontBase > fontBases ) { int uniqueID = MPPUtility . getInt ( data , offset ) ; FieldType fieldType = MPPTaskField . getInstance ( MPPUtility . getShort ( data , offset + 4 ) ) ; Integer index = Integer . valueOf ( MPPUtility . getByte ( data , offset + 8 ) ) ; int style = MPPUtility . getByte ( data , offset + 9 ) ; ColorType color = ColorType . getInstance ( MPPUtility . getByte ( data , offset + 10 ) ) ; int change = MPPUtility . getByte ( data , offset + 12 ) ; FontBase fontBase = fontBases . get ( index ) ; boolean bold = ( ( style & 0x01 ) != 0 ) ; boolean italic = ( ( style & 0x02 ) != 0 ) ; boolean underline = ( ( style & 0x04 ) != 0 ) ; boolean boldChanged = ( ( change & 0x01 ) != 0 ) ; boolean underlineChanged = ( ( change & 0x02 ) != 0 ) ; boolean italicChanged = ( ( change & 0x04 ) != 0 ) ; boolean colorChanged = ( ( change & 0x08 ) != 0 ) ; boolean fontChanged = ( ( change & 0x10 ) != 0 ) ; boolean backgroundColorChanged = ( uniqueID == - 1 ) ; boolean backgroundPatternChanged = ( uniqueID == - 1 ) ; return ( new TableFontStyle ( uniqueID , fieldType , fontBase , italic , bold , underline , false , color . getColor ( ) , Color . BLACK , BackgroundPattern . TRANSPARENT , italicChanged , boldChanged , underlineChanged , false , colorChanged , fontChanged , backgroundColorChanged , backgroundPatternChanged ) ) ; } | Retrieve column font details from a block of property data . | 405 | 12 |
143,364 | private InputStream prepareInputStream ( InputStream stream ) throws IOException { InputStream result ; BufferedInputStream bis = new BufferedInputStream ( stream ) ; readHeaderProperties ( bis ) ; if ( isCompressed ( ) ) { result = new InflaterInputStream ( bis ) ; } else { result = bis ; } return result ; } | If the file is compressed handle this so that the stream is ready to read . | 75 | 16 |
143,365 | private String readHeaderString ( BufferedInputStream stream ) throws IOException { int bufferSize = 100 ; stream . mark ( bufferSize ) ; byte [ ] buffer = new byte [ bufferSize ] ; stream . read ( buffer ) ; Charset charset = CharsetHelper . UTF8 ; String header = new String ( buffer , charset ) ; int prefixIndex = header . indexOf ( "PPX!!!!|" ) ; int suffixIndex = header . indexOf ( "|!!!!XPP" ) ; if ( prefixIndex != 0 || suffixIndex == - 1 ) { throw new IOException ( "File format not recognised" ) ; } int skip = suffixIndex + 9 ; stream . reset ( ) ; stream . skip ( skip ) ; return header . substring ( prefixIndex + 8 , suffixIndex ) ; } | Read the header from the Phoenix file . | 174 | 8 |
143,366 | private void readHeaderProperties ( BufferedInputStream stream ) throws IOException { String header = readHeaderString ( stream ) ; for ( String property : header . split ( "\\|" ) ) { String [ ] expression = property . split ( "=" ) ; m_properties . put ( expression [ 0 ] , expression [ 1 ] ) ; } } | Read properties from the raw header data . | 75 | 8 |
143,367 | @ Override public void process ( MPPReader reader , ProjectFile file , DirectoryEntry root ) throws MPXJException , IOException { try { populateMemberData ( reader , file , root ) ; processProjectProperties ( ) ; if ( ! reader . getReadPropertiesOnly ( ) ) { processCalendarData ( ) ; processResourceData ( ) ; processTaskData ( ) ; processConstraintData ( ) ; processAssignmentData ( ) ; if ( reader . getReadPresentationData ( ) ) { processViewPropertyData ( ) ; processViewData ( ) ; processTableData ( ) ; } } } finally { clearMemberData ( ) ; } } | This method is used to process an MPP8 file . This is the file format used by Project 98 . | 143 | 22 |
143,368 | private void updateBaseCalendarNames ( List < Pair < ProjectCalendar , Integer > > baseCalendars ) { for ( Pair < ProjectCalendar , Integer > pair : baseCalendars ) { ProjectCalendar cal = pair . getFirst ( ) ; Integer baseCalendarID = pair . getSecond ( ) ; ProjectCalendar baseCal = m_calendarMap . get ( baseCalendarID ) ; if ( baseCal != null ) { cal . setParent ( baseCal ) ; } } } | The way calendars are stored in an MPP8 file means that there can be forward references between the base calendar unique ID for a derived calendar and the base calendar itself . To get around this we initially populate the base calendar name attribute with the base calendar unique ID and now in this method we can convert those ID values into the correct names . | 106 | 68 |
143,369 | private void setTaskNotes ( Task task , byte [ ] data , ExtendedData taskExtData , FixDeferFix taskVarData ) { String notes = taskExtData . getString ( TASK_NOTES ) ; if ( notes == null && data . length == 366 ) { byte [ ] offsetData = taskVarData . getByteArray ( getOffset ( data , 362 ) ) ; if ( offsetData != null && offsetData . length >= 12 ) { notes = taskVarData . getString ( getOffset ( offsetData , 8 ) ) ; // We do pick up some random stuff with this approach, and // we don't know enough about the file format to know when to ignore it // so we'll use a heuristic here to ignore anything that // doesn't look like RTF. if ( notes != null && notes . indexOf ( ' ' ) == - 1 ) { notes = null ; } } } if ( notes != null ) { if ( m_reader . getPreserveNoteFormatting ( ) == false ) { notes = RtfHelper . strip ( notes ) ; } task . setNotes ( notes ) ; } } | There appear to be two ways of representing task notes in an MPP8 file . This method tries to determine which has been used . | 241 | 27 |
143,370 | private void processHyperlinkData ( Task task , byte [ ] data ) { if ( data != null ) { int offset = 12 ; String hyperlink ; String address ; String subaddress ; offset += 12 ; hyperlink = MPPUtility . getUnicodeString ( data , offset ) ; offset += ( ( hyperlink . length ( ) + 1 ) * 2 ) ; offset += 12 ; address = MPPUtility . getUnicodeString ( data , offset ) ; offset += ( ( address . length ( ) + 1 ) * 2 ) ; offset += 12 ; subaddress = MPPUtility . getUnicodeString ( data , offset ) ; task . setHyperlink ( hyperlink ) ; task . setHyperlinkAddress ( address ) ; task . setHyperlinkSubAddress ( subaddress ) ; } } | This method is used to extract the task hyperlink attributes from a block of data and call the appropriate modifier methods to configure the specified task object . | 174 | 29 |
143,371 | public void process ( String driverClass , String connectionString , String projectID , String outputFile ) throws Exception { System . out . println ( "Reading Primavera database started." ) ; Class . forName ( driverClass ) ; Properties props = new Properties ( ) ; // // This is not a very robust way to detect that we're working with SQLlite... // If you are trying to grab data from // a standalone P6 using SQLite, the SQLite JDBC driver needs this property // in order to correctly parse timestamps. // if ( driverClass . equals ( "org.sqlite.JDBC" ) ) { props . setProperty ( "date_string_format" , "yyyy-MM-dd HH:mm:ss" ) ; } Connection c = DriverManager . getConnection ( connectionString , props ) ; PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader ( ) ; reader . setConnection ( c ) ; processProject ( reader , Integer . parseInt ( projectID ) , outputFile ) ; } | Extract Primavera project data and export in another format . | 222 | 14 |
143,372 | private void processProject ( PrimaveraDatabaseReader reader , int projectID , String outputFile ) throws Exception { long start = System . currentTimeMillis ( ) ; reader . setProjectID ( projectID ) ; ProjectFile projectFile = reader . read ( ) ; long elapsed = System . currentTimeMillis ( ) - start ; System . out . println ( "Reading database completed in " + elapsed + "ms." ) ; System . out . println ( "Writing output file started." ) ; start = System . currentTimeMillis ( ) ; ProjectWriter writer = ProjectWriterUtility . getProjectWriter ( outputFile ) ; writer . write ( projectFile , outputFile ) ; elapsed = System . currentTimeMillis ( ) - start ; System . out . println ( "Writing output completed in " + elapsed + "ms." ) ; } | Process a single project . | 178 | 5 |
143,373 | public static ResourceField getInstance ( int value ) { ResourceField result = null ; if ( value >= 0 && value < FIELD_ARRAY . length ) { result = FIELD_ARRAY [ value ] ; } else { if ( ( value & 0x8000 ) != 0 ) { int baseValue = ResourceField . ENTERPRISE_CUSTOM_FIELD1 . getValue ( ) ; int id = baseValue + ( value & 0xFFF ) ; result = ResourceField . getInstance ( id ) ; } } return ( result ) ; } | Retrieve an instance of the ResourceField class based on the data read from an MS Project file . | 118 | 20 |
143,374 | public void update ( Record record , boolean isText ) throws MPXJException { int length = record . getLength ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( isText == true ) { add ( getTaskCode ( record . getString ( i ) ) ) ; } else { add ( record . getInteger ( i ) . intValue ( ) ) ; } } } | This method populates the task model from data read from an MPX file . | 88 | 16 |
143,375 | private void add ( int field ) { if ( field < m_flags . length ) { if ( m_flags [ field ] == false ) { m_flags [ field ] = true ; m_fields [ m_count ] = field ; ++ m_count ; } } } | This method is called from the task class each time an attribute is added ensuring that all of the attributes present in each task record are present in the resource model . | 59 | 32 |
143,376 | @ SuppressWarnings ( "unchecked" ) private boolean isFieldPopulated ( Task task , TaskField field ) { boolean result = false ; if ( field != null ) { Object value = task . getCachedValue ( field ) ; switch ( field ) { case PREDECESSORS : case SUCCESSORS : { result = value != null && ! ( ( List < Relation > ) value ) . isEmpty ( ) ; break ; } default : { result = value != null ; break ; } } } return result ; } | Determine if a task field contains data . | 115 | 10 |
143,377 | private String getTaskField ( int key ) { String result = null ; if ( ( key > 0 ) && ( key < m_taskNames . length ) ) { result = m_taskNames [ key ] ; } return ( result ) ; } | Returns Task field name of supplied code no . | 52 | 9 |
143,378 | private int getTaskCode ( String field ) throws MPXJException { Integer result = m_taskNumbers . get ( field . trim ( ) ) ; if ( result == null ) { throw new MPXJException ( MPXJException . INVALID_TASK_FIELD_NAME + " " + field ) ; } return ( result . intValue ( ) ) ; } | Returns code number of Task field supplied . | 81 | 8 |
143,379 | public static String parseString ( String value ) { if ( value != null ) { // Strip angle brackets if present if ( ! value . isEmpty ( ) && value . charAt ( 0 ) == ' ' ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } // Strip quotes if present if ( ! value . isEmpty ( ) && value . charAt ( 0 ) == ' ' ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } } return value ; } | Parse a string . | 115 | 5 |
143,380 | public static Number parseDouble ( String value ) throws ParseException { Number result = null ; value = parseString ( value ) ; // If we still have a value if ( value != null && ! value . isEmpty ( ) && ! value . equals ( "-1 -1" ) ) { int index = value . indexOf ( "E+" ) ; if ( index != - 1 ) { value = value . substring ( 0 , index ) + ' ' + value . substring ( index + 2 , value . length ( ) ) ; } if ( value . indexOf ( ' ' ) != - 1 ) { result = DOUBLE_FORMAT . get ( ) . parse ( value ) ; } else { result = Double . valueOf ( value ) ; } } return result ; } | Parse the string representation of a double . | 167 | 9 |
143,381 | public static Boolean parseBoolean ( String value ) throws ParseException { Boolean result = null ; Integer number = parseInteger ( value ) ; if ( number != null ) { result = number . intValue ( ) == 0 ? Boolean . FALSE : Boolean . TRUE ; } return result ; } | Parse a string representation of a Boolean value . | 60 | 10 |
143,382 | public static Integer parseInteger ( String value ) throws ParseException { Integer result = null ; if ( value . length ( ) > 0 && value . indexOf ( ' ' ) == - 1 ) { if ( value . indexOf ( ' ' ) == - 1 ) { result = Integer . valueOf ( value ) ; } else { Number n = DatatypeConverter . parseDouble ( value ) ; result = Integer . valueOf ( n . intValue ( ) ) ; } } return result ; } | Parse a string representation of an Integer value . | 107 | 10 |
143,383 | public static Date parseEpochTimestamp ( String value ) { Date result = null ; if ( value . length ( ) > 0 ) { if ( ! value . equals ( "-1 -1" ) ) { Calendar cal = DateHelper . popCalendar ( JAVA_EPOCH ) ; int index = value . indexOf ( ' ' ) ; if ( index == - 1 ) { if ( value . length ( ) < 6 ) { value = "000000" + value ; value = value . substring ( value . length ( ) - 6 ) ; } int hours = Integer . parseInt ( value . substring ( 0 , 2 ) ) ; int minutes = Integer . parseInt ( value . substring ( 2 , 4 ) ) ; int seconds = Integer . parseInt ( value . substring ( 4 ) ) ; cal . set ( Calendar . HOUR , hours ) ; cal . set ( Calendar . MINUTE , minutes ) ; cal . set ( Calendar . SECOND , seconds ) ; } else { long astaDays = Long . parseLong ( value . substring ( 0 , index ) ) ; int astaSeconds = Integer . parseInt ( value . substring ( index + 1 ) ) ; cal . add ( Calendar . DAY_OF_YEAR , ( int ) ( astaDays - ASTA_EPOCH ) ) ; cal . set ( Calendar . MILLISECOND , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . HOUR , 0 ) ; cal . add ( Calendar . SECOND , astaSeconds ) ; } result = cal . getTime ( ) ; DateHelper . pushCalendar ( cal ) ; } } return result ; } | Parse the string representation of a timestamp . | 365 | 9 |
143,384 | protected void processProjectListItem ( Map < Integer , String > result , Row row ) { Integer id = row . getInteger ( "PROJ_ID" ) ; String name = row . getString ( "PROJ_NAME" ) ; result . put ( id , name ) ; } | Retrieve the details of a single project from the database . | 61 | 12 |
143,385 | protected void processCalendarData ( ProjectCalendar calendar , Row row ) { int dayIndex = row . getInt ( "CD_DAY_OR_EXCEPTION" ) ; if ( dayIndex == 0 ) { processCalendarException ( calendar , row ) ; } else { processCalendarHours ( calendar , row , dayIndex ) ; } } | Read calendar hours and exception data . | 74 | 7 |
143,386 | private void processCalendarException ( ProjectCalendar calendar , Row row ) { Date fromDate = row . getDate ( "CD_FROM_DATE" ) ; Date toDate = row . getDate ( "CD_TO_DATE" ) ; boolean working = row . getInt ( "CD_WORKING" ) != 0 ; ProjectCalendarException exception = calendar . addCalendarException ( fromDate , toDate ) ; if ( working ) { exception . addRange ( new DateRange ( row . getDate ( "CD_FROM_TIME1" ) , row . getDate ( "CD_TO_TIME1" ) ) ) ; exception . addRange ( new DateRange ( row . getDate ( "CD_FROM_TIME2" ) , row . getDate ( "CD_TO_TIME2" ) ) ) ; exception . addRange ( new DateRange ( row . getDate ( "CD_FROM_TIME3" ) , row . getDate ( "CD_TO_TIME3" ) ) ) ; exception . addRange ( new DateRange ( row . getDate ( "CD_FROM_TIME4" ) , row . getDate ( "CD_TO_TIME4" ) ) ) ; exception . addRange ( new DateRange ( row . getDate ( "CD_FROM_TIME5" ) , row . getDate ( "CD_TO_TIME5" ) ) ) ; } } | Process a calendar exception . | 310 | 5 |
143,387 | private void processCalendarHours ( ProjectCalendar calendar , Row row , int dayIndex ) { Day day = Day . getInstance ( dayIndex ) ; boolean working = row . getInt ( "CD_WORKING" ) != 0 ; calendar . setWorkingDay ( day , working ) ; if ( working == true ) { ProjectCalendarHours hours = calendar . addCalendarHours ( day ) ; Date start = row . getDate ( "CD_FROM_TIME1" ) ; Date end = row . getDate ( "CD_TO_TIME1" ) ; if ( start != null && end != null ) { hours . addRange ( new DateRange ( start , end ) ) ; } start = row . getDate ( "CD_FROM_TIME2" ) ; end = row . getDate ( "CD_TO_TIME2" ) ; if ( start != null && end != null ) { hours . addRange ( new DateRange ( start , end ) ) ; } start = row . getDate ( "CD_FROM_TIME3" ) ; end = row . getDate ( "CD_TO_TIME3" ) ; if ( start != null && end != null ) { hours . addRange ( new DateRange ( start , end ) ) ; } start = row . getDate ( "CD_FROM_TIME4" ) ; end = row . getDate ( "CD_TO_TIME4" ) ; if ( start != null && end != null ) { hours . addRange ( new DateRange ( start , end ) ) ; } start = row . getDate ( "CD_FROM_TIME5" ) ; end = row . getDate ( "CD_TO_TIME5" ) ; if ( start != null && end != null ) { hours . addRange ( new DateRange ( start , end ) ) ; } } } | Process calendar hours . | 398 | 4 |
143,388 | protected void processResourceBaseline ( Row row ) { Integer id = row . getInteger ( "RES_UID" ) ; Resource resource = m_project . getResourceByUniqueID ( id ) ; if ( resource != null ) { int index = row . getInt ( "RB_BASE_NUM" ) ; resource . setBaselineWork ( index , row . getDuration ( "RB_BASE_WORK" ) ) ; resource . setBaselineCost ( index , row . getCurrency ( "RB_BASE_COST" ) ) ; } } | Read resource baseline values . | 121 | 5 |
143,389 | protected void processDurationField ( Row row ) { processField ( row , "DUR_FIELD_ID" , "DUR_REF_UID" , MPDUtility . getAdjustedDuration ( m_project , row . getInt ( "DUR_VALUE" ) , MPDUtility . getDurationTimeUnits ( row . getInt ( "DUR_FMT" ) ) ) ) ; } | Read a single duration field extended attribute . | 89 | 8 |
143,390 | protected void processOutlineCodeField ( Integer entityID , Row row ) { processField ( row , "OC_FIELD_ID" , entityID , row . getString ( "OC_NAME" ) ) ; } | Read a single outline code field extended attribute . | 46 | 9 |
143,391 | protected void processTaskBaseline ( Row row ) { Integer id = row . getInteger ( "TASK_UID" ) ; Task task = m_project . getTaskByUniqueID ( id ) ; if ( task != null ) { int index = row . getInt ( "TB_BASE_NUM" ) ; task . setBaselineDuration ( index , MPDUtility . getAdjustedDuration ( m_project , row . getInt ( "TB_BASE_DUR" ) , MPDUtility . getDurationTimeUnits ( row . getInt ( "TB_BASE_DUR_FMT" ) ) ) ) ; task . setBaselineStart ( index , row . getDate ( "TB_BASE_START" ) ) ; task . setBaselineFinish ( index , row . getDate ( "TB_BASE_FINISH" ) ) ; task . setBaselineWork ( index , row . getDuration ( "TB_BASE_WORK" ) ) ; task . setBaselineCost ( index , row . getCurrency ( "TB_BASE_COST" ) ) ; } } | Read task baseline values . | 247 | 5 |
143,392 | protected void processLink ( Row row ) { Task predecessorTask = m_project . getTaskByUniqueID ( row . getInteger ( "LINK_PRED_UID" ) ) ; Task successorTask = m_project . getTaskByUniqueID ( row . getInteger ( "LINK_SUCC_UID" ) ) ; if ( predecessorTask != null && successorTask != null ) { RelationType type = RelationType . getInstance ( row . getInt ( "LINK_TYPE" ) ) ; TimeUnit durationUnits = MPDUtility . getDurationTimeUnits ( row . getInt ( "LINK_LAG_FMT" ) ) ; Duration duration = MPDUtility . getDuration ( row . getDouble ( "LINK_LAG" ) . doubleValue ( ) , durationUnits ) ; Relation relation = successorTask . addPredecessor ( predecessorTask , type , duration ) ; relation . setUniqueID ( row . getInteger ( "LINK_UID" ) ) ; m_eventManager . fireRelationReadEvent ( relation ) ; } } | Process a relationship between two tasks . | 236 | 7 |
143,393 | protected void processAssignmentBaseline ( Row row ) { Integer id = row . getInteger ( "ASSN_UID" ) ; ResourceAssignment assignment = m_assignmentMap . get ( id ) ; if ( assignment != null ) { int index = row . getInt ( "AB_BASE_NUM" ) ; assignment . setBaselineStart ( index , row . getDate ( "AB_BASE_START" ) ) ; assignment . setBaselineFinish ( index , row . getDate ( "AB_BASE_FINISH" ) ) ; assignment . setBaselineWork ( index , row . getDuration ( "AB_BASE_WORK" ) ) ; assignment . setBaselineCost ( index , row . getCurrency ( "AB_BASE_COST" ) ) ; } } | Read resource assignment baseline values . | 175 | 6 |
143,394 | protected void postProcessing ( ) { // // Update the internal structure. We'll take this opportunity to // generate outline numbers for the tasks as they don't appear to // be present in the MPP file. // ProjectConfig config = m_project . getProjectConfig ( ) ; config . setAutoWBS ( m_autoWBS ) ; config . setAutoOutlineNumber ( true ) ; m_project . updateStructure ( ) ; config . setAutoOutlineNumber ( false ) ; // // Perform post-processing to set the summary flag // for ( Task task : m_project . getTasks ( ) ) { task . setSummary ( task . hasChildTasks ( ) ) ; } // // Ensure that the unique ID counters are correct // config . updateUniqueCounters ( ) ; } | Carry out any post - processing required to tidy up the data read from the database . | 169 | 18 |
143,395 | private Integer getNullOnValue ( Integer value , int nullValue ) { return ( NumberHelper . getInt ( value ) == nullValue ? null : value ) ; } | This method returns the value it is passed or null if the value matches the nullValue argument . | 35 | 19 |
143,396 | public void process ( DirectoryEntry projectDir , ProjectFile file , DocumentInputStreamFactory inputStreamFactory ) throws IOException { DirectoryEntry consDir ; try { consDir = ( DirectoryEntry ) projectDir . getEntry ( "TBkndCons" ) ; } catch ( FileNotFoundException ex ) { consDir = null ; } if ( consDir != null ) { FixedMeta consFixedMeta = new FixedMeta ( new DocumentInputStream ( ( ( DocumentEntry ) consDir . getEntry ( "FixedMeta" ) ) ) , 10 ) ; FixedData consFixedData = new FixedData ( consFixedMeta , 20 , inputStreamFactory . getInstance ( consDir , "FixedData" ) ) ; // FixedMeta consFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry("Fixed2Meta"))), 9); // FixedData consFixed2Data = new FixedData(consFixed2Meta, 48, getEncryptableInputStream(consDir, "Fixed2Data")); int count = consFixedMeta . getAdjustedItemCount ( ) ; int lastConstraintID = - 1 ; ProjectProperties properties = file . getProjectProperties ( ) ; EventManager eventManager = file . getEventManager ( ) ; boolean project15 = NumberHelper . getInt ( properties . getMppFileType ( ) ) == 14 && NumberHelper . getInt ( properties . getApplicationVersion ( ) ) > ApplicationVersion . PROJECT_2010 ; int durationUnitsOffset = project15 ? 18 : 14 ; int durationOffset = project15 ? 14 : 16 ; for ( int loop = 0 ; loop < count ; loop ++ ) { byte [ ] metaData = consFixedMeta . getByteArrayValue ( loop ) ; // // SourceForge bug 2209477: we were reading an int here, but // it looks like the deleted flag is just a short. // if ( MPPUtility . getShort ( metaData , 0 ) != 0 ) { continue ; } int index = consFixedData . getIndexFromOffset ( MPPUtility . getInt ( metaData , 4 ) ) ; if ( index == - 1 ) { continue ; } // // Do we have enough data? // byte [ ] data = consFixedData . getByteArrayValue ( index ) ; if ( data . length < 14 ) { continue ; } int constraintID = MPPUtility . getInt ( data , 0 ) ; if ( constraintID <= lastConstraintID ) { continue ; } lastConstraintID = constraintID ; int taskID1 = MPPUtility . getInt ( data , 4 ) ; int taskID2 = MPPUtility . getInt ( data , 8 ) ; if ( taskID1 == taskID2 ) { continue ; } // byte[] metaData2 = consFixed2Meta.getByteArrayValue(loop); // int index2 = consFixed2Data.getIndexFromOffset(MPPUtility.getInt(metaData2, 4)); // byte[] data2 = consFixed2Data.getByteArrayValue(index2); Task task1 = file . getTaskByUniqueID ( Integer . valueOf ( taskID1 ) ) ; Task task2 = file . getTaskByUniqueID ( Integer . valueOf ( taskID2 ) ) ; if ( task1 != null && task2 != null ) { RelationType type = RelationType . getInstance ( MPPUtility . getShort ( data , 12 ) ) ; TimeUnit durationUnits = MPPUtility . getDurationTimeUnits ( MPPUtility . getShort ( data , durationUnitsOffset ) ) ; Duration lag = MPPUtility . getAdjustedDuration ( properties , MPPUtility . getInt ( data , durationOffset ) , durationUnits ) ; Relation relation = task2 . addPredecessor ( task1 , type , lag ) ; relation . setUniqueID ( Integer . valueOf ( constraintID ) ) ; eventManager . fireRelationReadEvent ( relation ) ; } } } } | Main entry point when called to process constraint data . | 862 | 10 |
143,397 | private Object getColumnValue ( String table , String column , String data , int type , boolean epochDateFormat ) throws MPXJException { try { Object value = null ; switch ( type ) { case Types . BIT : { value = DatatypeConverter . parseBoolean ( data ) ; break ; } case Types . VARCHAR : case Types . LONGVARCHAR : { value = DatatypeConverter . parseString ( data ) ; break ; } case Types . TIME : { value = DatatypeConverter . parseBasicTime ( data ) ; break ; } case Types . TIMESTAMP : { if ( epochDateFormat ) { value = DatatypeConverter . parseEpochTimestamp ( data ) ; } else { value = DatatypeConverter . parseBasicTimestamp ( data ) ; } break ; } case Types . DOUBLE : { value = DatatypeConverter . parseDouble ( data ) ; break ; } case Types . INTEGER : { value = DatatypeConverter . parseInteger ( data ) ; break ; } default : { throw new IllegalArgumentException ( "Unsupported SQL type: " + type ) ; } } return value ; } catch ( Exception ex ) { throw new MPXJException ( "Failed to parse " + table + "." + column + " (data=" + data + ", type=" + type + ")" , ex ) ; } } | Maps the text representation of column data to Java types . | 309 | 11 |
143,398 | public List < Callouts . Callout > getCallout ( ) { if ( callout == null ) { callout = new ArrayList < Callouts . Callout > ( ) ; } return this . callout ; } | Gets the value of the callout property . | 47 | 10 |
143,399 | public static final Integer parseMinutesFromHours ( String value ) { Integer result = null ; if ( value != null ) { result = Integer . valueOf ( Integer . parseInt ( value ) * 60 ) ; } return result ; } | Parse a duration in minutes form a number of hours . | 49 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.