idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
35,500
public org . grails . datastore . mapping . query . api . Criteria sizeEq ( String propertyName , int size ) { if ( ! validateSimpleExpression ( ) ) { throwRuntimeException ( new IllegalArgumentException ( "Call to [sizeEq] with propertyName [" + propertyName + "] and size [" + size + "] not allowed here." ) ) ; } propertyName = calculatePropertyName ( propertyName ) ; addToCriteria ( Restrictions . sizeEq ( propertyName , size ) ) ; return this ; }
Creates a Criterion that contrains a collection property by size
35,501
public org . grails . datastore . mapping . query . api . Criteria between ( String propertyName , Object lo , Object hi ) { if ( ! validateSimpleExpression ( ) ) { throwRuntimeException ( new IllegalArgumentException ( "Call to [between] with propertyName [" + propertyName + "] not allowed here." ) ) ; } propertyName = calculatePropertyName ( propertyName ) ; addToCriteria ( Restrictions . between ( propertyName , lo , hi ) ) ; return this ; }
Creates a between Criterion based on the property name and specified lo and hi values
35,502
protected Criterion addToCriteria ( Criterion c ) { if ( ! logicalExpressionStack . isEmpty ( ) ) { logicalExpressionStack . get ( logicalExpressionStack . size ( ) - 1 ) . args . add ( c ) ; } else { criteria . add ( c ) ; } return c ; }
adds and returns the given criterion to the currently active criteria set . this might be either the root criteria or a currently open LogicalExpression .
35,503
protected Session createSessionProxy ( Session session ) { Class < ? > [ ] sessionIfcs ; Class < ? > mainIfc = Session . class ; if ( session instanceof EventSource ) { sessionIfcs = new Class [ ] { mainIfc , EventSource . class } ; } else if ( session instanceof SessionImplementor ) { sessionIfcs = new Class [ ] { mainIfc , SessionImplementor . class } ; } else { sessionIfcs = new Class [ ] { mainIfc } ; } return ( Session ) Proxy . newProxyInstance ( session . getClass ( ) . getClassLoader ( ) , sessionIfcs , new CloseSuppressingInvocationHandler ( session ) ) ; }
Create a close - suppressing proxy for the given Hibernate Session . The proxy also prepares returned Query and Criteria objects .
35,504
protected FlushMode applyFlushMode ( Session session , boolean existingTransaction ) { if ( isApplyFlushModeOnlyToNonExistingTransactions ( ) && existingTransaction ) { return null ; } if ( getFlushMode ( ) == FLUSH_NEVER ) { if ( existingTransaction ) { FlushMode previousFlushMode = session . getHibernateFlushMode ( ) ; if ( ! previousFlushMode . lessThan ( FlushMode . COMMIT ) ) { session . setHibernateFlushMode ( FlushMode . MANUAL ) ; return previousFlushMode ; } } else { session . setHibernateFlushMode ( FlushMode . MANUAL ) ; } } else if ( getFlushMode ( ) == FLUSH_EAGER ) { if ( existingTransaction ) { FlushMode previousFlushMode = session . getHibernateFlushMode ( ) ; if ( ! previousFlushMode . equals ( FlushMode . AUTO ) ) { session . setHibernateFlushMode ( FlushMode . AUTO ) ; return previousFlushMode ; } } else { } } else if ( getFlushMode ( ) == FLUSH_COMMIT ) { if ( existingTransaction ) { FlushMode previousFlushMode = session . getHibernateFlushMode ( ) ; if ( previousFlushMode . equals ( FlushMode . AUTO ) || previousFlushMode . equals ( FlushMode . ALWAYS ) ) { session . setHibernateFlushMode ( FlushMode . COMMIT ) ; return previousFlushMode ; } } else { session . setHibernateFlushMode ( FlushMode . COMMIT ) ; } } else if ( getFlushMode ( ) == FLUSH_ALWAYS ) { if ( existingTransaction ) { FlushMode previousFlushMode = session . getHibernateFlushMode ( ) ; if ( ! previousFlushMode . equals ( FlushMode . ALWAYS ) ) { session . setHibernateFlushMode ( FlushMode . ALWAYS ) ; return previousFlushMode ; } } else { session . setHibernateFlushMode ( FlushMode . ALWAYS ) ; } } return null ; }
Apply the flush mode that s been specified for this accessor to the given Session .
35,505
public static JSONCompareResult compareJSON ( String expectedStr , String actualStr , JSONComparator comparator ) throws JSONException { Object expected = JSONParser . parseJSON ( expectedStr ) ; Object actual = JSONParser . parseJSON ( actualStr ) ; if ( ( expected instanceof JSONObject ) && ( actual instanceof JSONObject ) ) { return compareJSON ( ( JSONObject ) expected , ( JSONObject ) actual , comparator ) ; } else if ( ( expected instanceof JSONArray ) && ( actual instanceof JSONArray ) ) { return compareJSON ( ( JSONArray ) expected , ( JSONArray ) actual , comparator ) ; } else if ( expected instanceof JSONString && actual instanceof JSONString ) { return compareJson ( ( JSONString ) expected , ( JSONString ) actual ) ; } else if ( expected instanceof JSONObject ) { return new JSONCompareResult ( ) . fail ( "" , expected , actual ) ; } else { return new JSONCompareResult ( ) . fail ( "" , expected , actual ) ; } }
Compares JSON string provided to the expected JSON string using provided comparator and returns the results of the comparison .
35,506
public static JSONCompareResult compareJSON ( String expectedStr , String actualStr , JSONCompareMode mode ) throws JSONException { return compareJSON ( expectedStr , actualStr , getComparatorForMode ( mode ) ) ; }
Compares JSON string provided to the expected JSON string and returns the results of the comparison .
35,507
public boolean matches ( String prefix , Object actual , Object expected , JSONCompareResult result ) throws ValueMatcherException { if ( comparator instanceof LocationAwareValueMatcher ) { return ( ( LocationAwareValueMatcher < Object > ) comparator ) . equal ( prefix , actual , expected , result ) ; } return comparator . equal ( actual , expected ) ; }
Return true if actual value matches expected value using this Customization s comparator . The equal method used for comparison depends on type of comparator .
35,508
public void compareJSONArray ( String prefix , JSONArray expected , JSONArray actual , JSONCompareResult result ) throws JSONException { String arrayPrefix = prefix + "[]" ; if ( expected . length ( ) < 1 || expected . length ( ) > 2 ) { result . fail ( MessageFormat . format ( "{0}: invalid expectation: expected array should contain either 1 or 2 elements but contains {1} elements" , arrayPrefix , expected . length ( ) ) ) ; return ; } if ( ! ( expected . get ( 0 ) instanceof Number ) ) { result . fail ( MessageFormat . format ( "{0}: invalid expectation: {1}expected array size ''{2}'' not a number" , arrayPrefix , ( expected . length ( ) == 1 ? "" : "minimum " ) , expected . get ( 0 ) ) ) ; return ; } if ( ( expected . length ( ) == 2 && ! ( expected . get ( 1 ) instanceof Number ) ) ) { result . fail ( MessageFormat . format ( "{0}: invalid expectation: maximum expected array size ''{1}'' not a number" , arrayPrefix , expected . get ( 1 ) ) ) ; return ; } int minExpectedLength = expected . getInt ( 0 ) ; if ( minExpectedLength < 0 ) { result . fail ( MessageFormat . format ( "{0}: invalid expectation: minimum expected array size ''{1}'' negative" , arrayPrefix , minExpectedLength ) ) ; return ; } int maxExpectedLength = expected . length ( ) == 2 ? expected . getInt ( 1 ) : minExpectedLength ; if ( maxExpectedLength < minExpectedLength ) { result . fail ( MessageFormat . format ( "{0}: invalid expectation: maximum expected array size ''{1}'' less than minimum expected array size ''{2}''" , arrayPrefix , maxExpectedLength , minExpectedLength ) ) ; return ; } if ( actual . length ( ) < minExpectedLength || actual . length ( ) > maxExpectedLength ) { result . fail ( arrayPrefix , MessageFormat . format ( "array size of {0}{1} elements" , minExpectedLength , ( expected . length ( ) == 2 ? ( " to " + maxExpectedLength ) : "" ) ) , MessageFormat . format ( "{0} elements" , actual . length ( ) ) ) ; } }
Expected array should consist of either 1 or 2 integer values that define maximum and minimum valid lengths of the actual array . If expected array contains a single integer value then the actual array must contain exactly that number of elements .
35,509
public final JSONCompareResult compareJSON ( JSONArray expected , JSONArray actual ) throws JSONException { JSONCompareResult result = new JSONCompareResult ( ) ; compareJSONArray ( "" , expected , actual , result ) ; return result ; }
Compares JSONArray provided to the expected JSONArray and returns the results of the comparison .
35,510
protected void recursivelyCompareJSONArray ( String key , JSONArray expected , JSONArray actual , JSONCompareResult result ) throws JSONException { Set < Integer > matched = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < expected . length ( ) ; ++ i ) { Object expectedElement = expected . get ( i ) ; boolean matchFound = false ; for ( int j = 0 ; j < actual . length ( ) ; ++ j ) { Object actualElement = actual . get ( j ) ; if ( matched . contains ( j ) || ! actualElement . getClass ( ) . equals ( expectedElement . getClass ( ) ) ) { continue ; } if ( expectedElement instanceof JSONObject ) { if ( compareJSON ( ( JSONObject ) expectedElement , ( JSONObject ) actualElement ) . passed ( ) ) { matched . add ( j ) ; matchFound = true ; break ; } } else if ( expectedElement instanceof JSONArray ) { if ( compareJSON ( ( JSONArray ) expectedElement , ( JSONArray ) actualElement ) . passed ( ) ) { matched . add ( j ) ; matchFound = true ; break ; } } else if ( expectedElement . equals ( actualElement ) ) { matched . add ( j ) ; matchFound = true ; break ; } } if ( ! matchFound ) { result . fail ( key + "[" + i + "] Could not find match for element " + expectedElement ) ; return ; } } }
easy way to uniquely identify each element .
35,511
public JSONCompareResult missing ( String field , Object expected ) { _fieldMissing . add ( new FieldComparisonFailure ( field , expected , null ) ) ; fail ( formatMissing ( field , expected ) ) ; return this ; }
Identify the missing field
35,512
public JSONCompareResult unexpected ( String field , Object actual ) { _fieldUnexpected . add ( new FieldComparisonFailure ( field , null , actual ) ) ; fail ( formatUnexpected ( field , actual ) ) ; return this ; }
Identify unexpected field
35,513
public static boolean allSimpleValues ( JSONArray array ) throws JSONException { for ( int i = 0 ; i < array . length ( ) ; ++ i ) { if ( ! isSimpleValue ( array . get ( i ) ) ) { return false ; } } return true ; }
Returns whether all of the elements in the given array are simple values .
35,514
private int getPressedColor ( int color ) { float [ ] hsv = new float [ 3 ] ; Color . colorToHSV ( color , hsv ) ; hsv [ 2 ] = hsv [ 2 ] * PRESSED_STATE_MULTIPLIER ; return Color . HSVToColor ( hsv ) ; }
Given a particular color adjusts its value by a multiplier .
35,515
public void drawPalette ( int [ ] colors , int selectedColor ) { if ( colors == null ) { return ; } this . removeAllViews ( ) ; int tableElements = 0 ; int rowElements = 0 ; int rowNumber = 0 ; TableRow row = createTableRow ( ) ; for ( int color : colors ) { tableElements ++ ; View colorSwatch = createColorSwatch ( color , selectedColor ) ; setSwatchDescription ( rowNumber , tableElements , rowElements , color == selectedColor , colorSwatch ) ; addSwatchToRow ( row , colorSwatch , rowNumber ) ; rowElements ++ ; if ( rowElements == mNumColumns ) { addView ( row ) ; row = createTableRow ( ) ; rowElements = 0 ; rowNumber ++ ; } } if ( rowElements > 0 ) { while ( rowElements != mNumColumns ) { addSwatchToRow ( row , createBlankSpace ( ) , rowNumber ) ; rowElements ++ ; } addView ( row ) ; } }
Adds swatches to table in a serpentine format .
35,516
private ImageView createBlankSpace ( ) { ImageView view = new ImageView ( getContext ( ) ) ; TableRow . LayoutParams params = new TableRow . LayoutParams ( mSwatchLength , mSwatchLength ) ; params . setMargins ( mMarginSize , mMarginSize , mMarginSize , mMarginSize ) ; view . setLayoutParams ( params ) ; return view ; }
Creates a blank space to fill the row .
35,517
private ColorPickerSwatch createColorSwatch ( int color , int selectedColor ) { ColorPickerSwatch view = new ColorPickerSwatch ( getContext ( ) , color , color == selectedColor , mOnColorSelectedListener ) ; TableRow . LayoutParams params = new TableRow . LayoutParams ( mSwatchLength , mSwatchLength ) ; params . setMargins ( mMarginSize , mMarginSize , mMarginSize , mMarginSize ) ; view . setLayoutParams ( params ) ; return view ; }
Creates a color swatch .
35,518
public CucumberITGenerator create ( final ParallelScheme parallelScheme ) throws MojoExecutionException { if ( ParallelScheme . FEATURE . equals ( parallelScheme ) ) { return createFileGeneratorByFeature ( ) ; } else { return createFileGeneratorByScenario ( ) ; } }
Create a CucumberITGenerator based on the given parallel scheme .
35,519
private List < String > createPluginStrings ( ) { final List < String > formatList = new ArrayList < String > ( ) ; for ( final Plugin plugin : overriddenParameters . getPlugins ( ) ) { formatList . add ( plugin . asPluginString ( fileCounter ) ) ; } return formatList ; }
Create the format string used for the output .
35,520
public void generateCucumberITFiles ( final File outputDirectory , final Collection < File > featureFiles ) throws MojoExecutionException { Parser < GherkinDocument > parser = new Parser < GherkinDocument > ( new AstBuilder ( ) ) ; TagPredicate tagPredicate = new TagPredicate ( overriddenParameters . getTags ( ) ) ; TokenMatcher matcher = new TokenMatcher ( ) ; for ( final File file : featureFiles ) { GherkinDocument gherkinDocument = null ; final List < Pickle > acceptedPickles = new ArrayList < Pickle > ( ) ; try { String source = FileUtils . readFileToString ( file ) ; gherkinDocument = parser . parse ( source , matcher ) ; Compiler compiler = new Compiler ( ) ; List < Pickle > pickles = compiler . compile ( gherkinDocument ) ; for ( Pickle pickle : pickles ) { if ( tagPredicate . apply ( pickle . getTags ( ) ) ) { acceptedPickles . add ( pickle ) ; } } } catch ( final IOException e ) { System . out . println ( format ( "WARNING: Failed to parse '%s'...IGNORING" , file . getName ( ) ) ) ; } for ( Pickle pickle : acceptedPickles ) { int locationIndex = pickle . getLocations ( ) . size ( ) ; final Location location = findLocationByIndex ( pickle , 0 ) ; final Location locationToCompare = findLocationByIndex ( pickle , locationIndex - 1 ) ; outputFileName = classNamingScheme . generate ( file . getName ( ) ) ; setFeatureFileLocation ( file , location ) ; setParsedFeature ( gherkinDocument . getFeature ( ) ) ; setParsedScenario ( findScenarioDefinitionViaLocation ( locationToCompare , gherkinDocument ) ) ; writeFile ( outputDirectory ) ; } } }
Generates a Cucumber runner for each scenario or example in a scenario outline .
35,521
public String generate ( final String featureFileName ) { String fileNameWithNoExtension = FilenameUtils . removeExtension ( featureFileName ) ; fileNameWithNoExtension = fileNameWithNoExtension . replaceAll ( "_" , "-" ) ; fileNameWithNoExtension = fileNameWithNoExtension . replaceAll ( " " , "" ) ; fileNameWithNoExtension = fileNameWithNoExtension . replaceAll ( "\\." , "-" ) ; String className = CaseFormat . LOWER_HYPHEN . to ( CaseFormat . UPPER_CAMEL , fileNameWithNoExtension ) ; final Matcher startsWithDigitCheck = startsWithDigit . matcher ( className ) ; if ( startsWithDigitCheck . matches ( ) ) { className = "_" + className ; } return className ; }
Generate a class name based on the supplied feature file .
35,522
public String generate ( final String featureFileName ) { String className = pattern . replace ( "{f}" , featureFileNamingScheme . generate ( featureFileName ) ) ; int number = counter . next ( ) ; className = replaceAll ( COUNTER_PATTERN , className , number ) ; className = replaceAll ( MODULO_COUNTER_PATTERN , className , number ) ; return className ; }
Generate a class name using the required pattern and feature file .
35,523
public void execute ( ) throws MojoExecutionException { if ( ! featuresDirectory . exists ( ) ) { throw new MojoExecutionException ( "Features directory does not exist" ) ; } final Collection < File > featureFiles = listFiles ( featuresDirectory , new String [ ] { "feature" } , true ) ; final List < File > sortedFeatureFiles = new NameFileComparator ( ) . sort ( new ArrayList < File > ( featureFiles ) ) ; createOutputDirIfRequired ( ) ; File packageDirectory = packageName == null ? outputDirectory : new File ( outputDirectory , packageName . replace ( '.' , '/' ) ) ; if ( ! packageDirectory . exists ( ) ) { packageDirectory . mkdirs ( ) ; } final CucumberITGenerator fileGenerator = createFileGenerator ( ) ; fileGenerator . generateCucumberITFiles ( packageDirectory , sortedFeatureFiles ) ; getLog ( ) . info ( "Adding " + outputDirectory . getAbsolutePath ( ) + " to test-compile source root" ) ; project . addTestCompileSourceRoot ( outputDirectory . getAbsolutePath ( ) ) ; }
Called by Maven to run this mojo after parameters have been injected .
35,524
private OverriddenCucumberOptionsParameters overrideParametersWithCucumberOptions ( ) throws MojoExecutionException { try { final OverriddenCucumberOptionsParameters overriddenParameters = new OverriddenCucumberOptionsParameters ( ) . setTags ( tags ) . setGlue ( glue ) . setStrict ( strict ) . setPlugins ( parseFormatAndPlugins ( format , plugins == null ? new ArrayList < Plugin > ( ) : plugins ) ) . setMonochrome ( monochrome ) ; if ( cucumberOptions != null && cucumberOptions . length ( ) > 0 ) { final RuntimeOptions options = new RuntimeOptions ( cucumberOptions ) ; overriddenParameters . overrideTags ( options . getFilters ( ) ) . overrideGlue ( options . getGlue ( ) ) . overridePlugins ( parsePlugins ( options . getPluginNames ( ) ) ) . overrideStrict ( options . isStrict ( ) ) . overrideMonochrome ( options . isMonochrome ( ) ) ; } return overriddenParameters ; } catch ( IllegalArgumentException e ) { throw new MojoExecutionException ( this , "Invalid parameter. " , e . getMessage ( ) ) ; } }
Overrides the parameters with cucumber . options if they have been specified . Plugins have somewhat limited support .
35,525
public void startSetup ( final OnIabSetupFinishedListener listener ) { if ( options != null ) { Logger . d ( "startSetup() options = " , options ) ; } if ( listener == null ) { throw new IllegalArgumentException ( "Setup listener must be not null!" ) ; } if ( setupState != SETUP_RESULT_NOT_STARTED && setupState != SETUP_RESULT_FAILED ) { throw new IllegalStateException ( "Couldn't be set up. Current state: " + setupStateToString ( setupState ) ) ; } setupState = SETUP_IN_PROGRESS ; setupExecutorService = Executors . newSingleThreadExecutor ( ) ; availableAppstores . clear ( ) ; availableAppstores . addAll ( options . getAvailableStores ( ) ) ; final List < String > storeNames = new ArrayList < String > ( options . getAvailableStoreNames ( ) ) ; for ( final Appstore appstore : availableAppstores ) { storeNames . remove ( appstore . getAppstoreName ( ) ) ; } final List < Appstore > instantiatedAppstores = new ArrayList < Appstore > ( ) ; for ( final String storeName : options . getAvailableStoreNames ( ) ) { if ( appStoreFactoryMap . containsKey ( storeName ) ) { final Appstore appstore = appStoreFactoryMap . get ( storeName ) . get ( ) ; instantiatedAppstores . add ( appstore ) ; availableAppstores . add ( appstore ) ; storeNames . remove ( storeName ) ; } } if ( ! storeNames . isEmpty ( ) ) { discoverOpenStores ( new OpenStoresDiscoveredListener ( ) { public void openStoresDiscovered ( final List < Appstore > appStores ) { for ( final Appstore appstore : appStores ) { final String name = appstore . getAppstoreName ( ) ; if ( storeNames . contains ( name ) ) { availableAppstores . add ( appstore ) ; } else { final AppstoreInAppBillingService billingService ; if ( ( billingService = appstore . getInAppBillingService ( ) ) != null ) { billingService . dispose ( ) ; Logger . d ( "startSetup() billing service disposed for " , appstore . getAppstoreName ( ) ) ; } } } final Runnable cleanup = new Runnable ( ) { public void run ( ) { for ( final Appstore appstore : instantiatedAppstores ) { final AppstoreInAppBillingService billingService ; if ( ( billingService = appstore . getInAppBillingService ( ) ) != null ) { billingService . dispose ( ) ; Logger . d ( "startSetup() billing service disposed for " , appstore . getAppstoreName ( ) ) ; } } } } ; if ( setupState != SETUP_IN_PROGRESS ) { cleanup . run ( ) ; return ; } setupWithStrategy ( new OnIabSetupFinishedListener ( ) { public void onIabSetupFinished ( final IabResult result ) { listener . onIabSetupFinished ( result ) ; instantiatedAppstores . remove ( OpenIabHelper . this . appstore ) ; cleanup . run ( ) ; } } ) ; } } ) ; } else { setupWithStrategy ( listener ) ; } }
Discovers all available stores and selects the best billing service . Should be called from the UI thread
35,526
public List < Appstore > discoverOpenStores ( ) { if ( Utils . uiThread ( ) ) { throw new IllegalStateException ( "Must not be called from UI thread" ) ; } final List < Appstore > openAppstores = new ArrayList < Appstore > ( ) ; final CountDownLatch countDownLatch = new CountDownLatch ( 1 ) ; discoverOpenStores ( new OpenStoresDiscoveredListener ( ) { public void openStoresDiscovered ( final List < Appstore > appstores ) { openAppstores . addAll ( appstores ) ; countDownLatch . countDown ( ) ; } } ) ; try { countDownLatch . await ( ) ; } catch ( InterruptedException e ) { return null ; } return openAppstores ; }
Discovers a list of all available Open Stores .
35,527
public void discoverOpenStores ( final OpenStoresDiscoveredListener listener ) { final List < ServiceInfo > serviceInfos = queryOpenStoreServices ( ) ; final Queue < Intent > bindServiceIntents = new LinkedList < Intent > ( ) ; for ( final ServiceInfo serviceInfo : serviceInfos ) { bindServiceIntents . add ( getBindServiceIntent ( serviceInfo ) ) ; } discoverOpenStores ( listener , bindServiceIntents , new ArrayList < Appstore > ( ) ) ; }
Discovers Open Stores .
35,528
public void queryInventoryAsync ( final boolean querySkuDetails , final List < String > moreItemSkus , final List < String > moreSubsSkus , final IabHelper . QueryInventoryFinishedListener listener ) { checkSetupDone ( "queryInventory" ) ; if ( listener == null ) { throw new IllegalArgumentException ( "Inventory listener must be not null" ) ; } new Thread ( new Runnable ( ) { public void run ( ) { IabResult result ; Inventory inv = null ; try { inv = queryInventory ( querySkuDetails , moreItemSkus , moreSubsSkus ) ; result = new IabResult ( BILLING_RESPONSE_RESULT_OK , "Inventory refresh successful." ) ; } catch ( IabException exception ) { result = exception . getResult ( ) ; Logger . e ( "queryInventoryAsync() Error : " , exception ) ; } final IabResult result_f = result ; final Inventory inv_f = inv ; handler . post ( new Runnable ( ) { public void run ( ) { if ( setupState == SETUP_RESULT_SUCCESSFUL ) { listener . onQueryInventoryFinished ( result_f , inv_f ) ; } } } ) ; } } ) . start ( ) ; }
Queries the inventory . This will query all owned items from the server as well as information on additional skus if specified . This method may block or take long to execute .
35,529
void checkSetupDone ( String operation ) { if ( ! setupSuccessful ( ) ) { String stateToString = setupStateToString ( setupState ) ; Logger . e ( "Illegal state for operation (" , operation , "): " , stateToString ) ; throw new IllegalStateException ( stateToString + " Can't perform operation: " + operation ) ; } }
Checks that setup was done ; if not throws an exception .
35,530
public List < String > getAllStoreSkus ( final String appstoreName ) { if ( TextUtils . isEmpty ( appstoreName ) ) { throw SkuMappingException . newInstance ( SkuMappingException . REASON_STORE_NAME ) ; } Map < String , String > skuMap = sku2storeSkuMappings . get ( appstoreName ) ; return skuMap == null ? null : Collections . unmodifiableList ( new ArrayList < String > ( skuMap . values ( ) ) ) ; }
Returns a list of SKU for a store .
35,531
public void onBuyGasButtonClicked ( View arg0 ) { Log . d ( TAG , "Buy gas button clicked." ) ; if ( mSubscribedToInfiniteGas ) { complain ( "No need! You're subscribed to infinite gas. Isn't that awesome?" ) ; return ; } if ( mTank >= TANK_MAX ) { complain ( "Your tank is full. Drive around a bit!" ) ; return ; } if ( setupDone == null ) { complain ( "Billing Setup is not completed yet" ) ; return ; } if ( ! setupDone ) { complain ( "Billing Setup failed" ) ; return ; } setWaitScreen ( true ) ; Log . d ( TAG , "Launching purchase flow for gas." ) ; String payload = "" ; mHelper . launchPurchaseFlow ( this , InAppConfig . SKU_GAS , RC_REQUEST , mPurchaseFinishedListener , payload ) ; }
User clicked the Buy Gas button
35,532
public void onUpgradeAppButtonClicked ( View arg0 ) { Log . d ( TAG , "Upgrade button clicked; launching purchase flow for upgrade." ) ; if ( setupDone == null ) { complain ( "Billing Setup is not completed yet" ) ; return ; } if ( ! setupDone ) { complain ( "Billing Setup failed" ) ; return ; } setWaitScreen ( true ) ; String payload = "" ; mHelper . launchPurchaseFlow ( this , InAppConfig . SKU_PREMIUM , RC_REQUEST , mPurchaseFinishedListener , payload ) ; }
User clicked the Upgrade to Premium button .
35,533
public void onInfiniteGasButtonClicked ( View arg0 ) { if ( setupDone == null ) { complain ( "Billing Setup is not completed yet" ) ; return ; } if ( ! setupDone ) { complain ( "Billing Setup failed" ) ; return ; } if ( ! mHelper . subscriptionsSupported ( ) ) { complain ( "Subscriptions not supported on your device yet. Sorry!" ) ; return ; } String payload = "" ; setWaitScreen ( true ) ; Log . d ( TAG , "Launching purchase flow for infinite gas subscription." ) ; mHelper . launchPurchaseFlow ( this , InAppConfig . SKU_INFINITE_GAS , IabHelper . ITEM_TYPE_SUBS , RC_REQUEST , mPurchaseFinishedListener , payload ) ; }
flow for subscription .
35,534
public void onDriveButtonClicked ( View arg0 ) { Log . d ( TAG , "Drive button clicked." ) ; if ( ! mSubscribedToInfiniteGas && mTank <= 0 ) alert ( R . string . out_of_gas_msg ) ; else { if ( ! mSubscribedToInfiniteGas ) -- mTank ; saveData ( ) ; alert ( R . string . spent_gas_msg ) ; updateUi ( ) ; Log . d ( TAG , "Vrooom. Tank is now " + mTank ) ; } }
Drive button clicked . Burn gas!
35,535
public void onDestroy ( ) { super . onDestroy ( ) ; Log . d ( TAG , "Destroying helper." ) ; if ( mHelper != null ) mHelper . dispose ( ) ; mHelper = null ; }
We re being destroyed . It s important to dispose of the helper here!
35,536
public void updateUi ( ) { ( ( ImageView ) findViewById ( R . id . free_or_premium ) ) . setImageResource ( mIsPremium ? R . drawable . premium : R . drawable . free ) ; findViewById ( R . id . upgrade_button ) . setVisibility ( mIsPremium ? View . GONE : View . VISIBLE ) ; findViewById ( R . id . infinite_gas_button ) . setVisibility ( mSubscribedToInfiniteGas ? View . GONE : View . VISIBLE ) ; if ( mSubscribedToInfiniteGas ) { ( ( ImageView ) findViewById ( R . id . gas_gauge ) ) . setImageResource ( R . drawable . gas_inf ) ; } else { int index = mTank >= TANK_RES_IDS . length ? TANK_RES_IDS . length - 1 : mTank ; ( ( ImageView ) findViewById ( R . id . gas_gauge ) ) . setImageResource ( TANK_RES_IDS [ index ] ) ; } }
updates UI to reflect model
35,537
void setWaitScreen ( boolean set ) { findViewById ( R . id . screen_main ) . setVisibility ( set ? View . GONE : View . VISIBLE ) ; findViewById ( R . id . screen_wait ) . setVisibility ( set ? View . VISIBLE : View . GONE ) ; }
Enables or disables the please wait screen .
35,538
public List < String > getAllOwnedSkus ( String itemType ) { List < String > result = new ArrayList < String > ( ) ; for ( Purchase p : mPurchaseMap . values ( ) ) { if ( p . getItemType ( ) . equals ( itemType ) ) result . add ( p . getSku ( ) ) ; } return result ; }
Returns a list of all owned product IDs of a given type
35,539
public static boolean packageInstalled ( final Context context , final String packageName ) { final PackageManager packageManager = context . getPackageManager ( ) ; boolean result = false ; try { packageManager . getPackageInfo ( packageName , PackageManager . GET_ACTIVITIES ) ; result = true ; } catch ( PackageManager . NameNotFoundException ignore ) { } Logger . d ( "packageInstalled() is " , result , " for " , packageName ) ; return result ; }
Checks if an application is installed .
35,540
public static boolean isPackageInstaller ( final Context context , final String packageName ) { final PackageManager packageManager = context . getPackageManager ( ) ; final String installerPackageName = packageManager . getInstallerPackageName ( context . getPackageName ( ) ) ; boolean isPackageInstaller = TextUtils . equals ( installerPackageName , packageName ) ; Logger . d ( "isPackageInstaller() is " , isPackageInstaller , " for " , packageName ) ; return isPackageInstaller ; }
Checks if an application with the passed name is the installer of the calling app .
35,541
private static boolean isNookDevice ( ) { String brand = Build . BRAND ; String manufacturer = System . getProperty ( "ro.nook.manufacturer" ) ; return ( ( brand != null && brand . equalsIgnoreCase ( "nook" ) ) || manufacturer != null && manufacturer . equalsIgnoreCase ( "nook" ) ) ; }
todo check for different devices
35,542
public boolean isPackageInstaller ( final String packageName ) { Logger . d ( "sPackageInstaller: packageName = " , packageName ) ; final PackageManager packageManager = context . getPackageManager ( ) ; final String installerPackageName = packageManager . getInstallerPackageName ( packageName ) ; Logger . d ( "installerPackageName = " , installerPackageName ) ; return NOKIA_INSTALLER . equals ( installerPackageName ) ; }
Returns true only if actual installer for specified app
35,543
private boolean verifyFingreprint ( ) { try { PackageInfo info = context . getPackageManager ( ) . getPackageInfo ( NOKIA_INSTALLER , PackageManager . GET_SIGNATURES ) ; if ( info . signatures . length == 1 ) { byte [ ] cert = info . signatures [ 0 ] . toByteArray ( ) ; MessageDigest digest ; digest = MessageDigest . getInstance ( "SHA1" ) ; byte [ ] ENABLER_FINGERPRINT = digest . digest ( cert ) ; byte [ ] EXPECTED_FINGERPRINT = hexStringToByteArray ( EXPECTED_SHA1_FINGERPRINT ) ; if ( Arrays . equals ( ENABLER_FINGERPRINT , EXPECTED_FINGERPRINT ) ) { Logger . i ( "isBillingAvailable" , "NIAP signature verified" ) ; return true ; } } } catch ( NoSuchAlgorithmException e ) { e . printStackTrace ( ) ; } catch ( PackageManager . NameNotFoundException e ) { e . printStackTrace ( ) ; } return false ; }
Checks SHA1 fingerprint of the enabler
35,544
public static void setLogTag ( final String logTag ) { Logger . logTag = TextUtils . isEmpty ( logTag ) ? LOG_TAG : logTag ; }
Sets the log tag .
35,545
private void startSetupIabAsync ( final String packageName , final OnIabSetupFinishedListener listener ) { new Thread ( new Runnable ( ) { public void run ( ) { try { Logger . d ( "Checking for in-app billing 3 support." ) ; int response = mService . isBillingSupported ( 3 , packageName , ITEM_TYPE_INAPP ) ; if ( response != BILLING_RESPONSE_RESULT_OK ) { if ( listener != null ) listener . onIabSetupFinished ( new IabResult ( response , "Error checking for billing v3 support." ) ) ; mSubscriptionsSupported = false ; return ; } Logger . d ( "In-app billing version 3 supported for " , packageName ) ; response = mService . isBillingSupported ( 3 , packageName , ITEM_TYPE_SUBS ) ; if ( response == BILLING_RESPONSE_RESULT_OK ) { Logger . d ( "Subscriptions AVAILABLE." ) ; mSubscriptionsSupported = true ; } else { Logger . d ( "Subscriptions NOT AVAILABLE. Response: " , response ) ; } mSetupDone = true ; } catch ( RemoteException e ) { if ( listener != null ) { listener . onIabSetupFinished ( new IabResult ( IABHELPER_REMOTE_EXCEPTION , "RemoteException while setting up in-app billing." ) ) ; } Logger . e ( "RemoteException while setting up in-app billing" , e ) ; return ; } if ( listener != null ) { listener . onIabSetupFinished ( new IabResult ( BILLING_RESPONSE_RESULT_OK , "Setup successful." ) ) ; Logger . d ( "Setup successful." ) ; } } } ) . start ( ) ; }
Performs Iab setup with the mService object which must be properly connected before calling this method .
35,546
protected Intent getServiceIntent ( ) { final Intent intent = new Intent ( GooglePlay . VENDING_ACTION ) ; intent . setPackage ( GooglePlay . ANDROID_INSTALLER ) ; return intent ; }
IabHelper code is shared between OpenStore and Google Play but services has different names
35,547
public static String getResponseDesc ( int code ) { String [ ] iab_msgs = ( "0:OK/1:User Canceled/2:Unknown/" + "3:Billing Unavailable/4:Item unavailable/" + "5:Developer Error/6:Error/7:Item Already Owned/" + "8:Item not owned" ) . split ( "/" ) ; String [ ] iabhelper_msgs = ( "0:OK/-1001:Remote exception during initialization/" + "-1002:Bad response received/" + "-1003:Purchase signature verification failed/" + "-1004:Send intent failed/" + "-1005:User cancelled/" + "-1006:Unknown purchase response/" + "-1007:Missing token/" + "-1008:Unknown error/" + "-1009:Subscriptions not available/" + "-1010:Invalid consumption attempt" ) . split ( "/" ) ; if ( code <= IABHELPER_ERROR_BASE ) { int index = IABHELPER_ERROR_BASE - code ; if ( index >= 0 && index < iabhelper_msgs . length ) return iabhelper_msgs [ index ] ; else return String . valueOf ( code ) + ":Unknown IAB Helper Error" ; } else if ( code < 0 || code >= iab_msgs . length ) { return String . valueOf ( code ) + ":Unknown" ; } else { return iab_msgs [ code ] ; } }
Returns a human - readable description for the given response code .
35,548
private void processPurchaseSuccess ( final String purchaseData ) { Logger . i ( "NokiaStoreHelper.processPurchaseSuccess" ) ; Logger . d ( "purchaseData = " , purchaseData ) ; Purchase purchase ; try { final JSONObject obj = new JSONObject ( purchaseData ) ; final String sku = SkuManager . getInstance ( ) . getSku ( OpenIabHelper . NAME_NOKIA , obj . getString ( "productId" ) ) ; Logger . d ( "sku = " , sku ) ; purchase = new Purchase ( OpenIabHelper . NAME_NOKIA ) ; purchase . setItemType ( IabHelper . ITEM_TYPE_INAPP ) ; purchase . setOrderId ( obj . getString ( "orderId" ) ) ; purchase . setPackageName ( obj . getString ( "packageName" ) ) ; purchase . setSku ( sku ) ; purchase . setToken ( obj . getString ( "purchaseToken" ) ) ; purchase . setDeveloperPayload ( obj . getString ( "developerPayload" ) ) ; } catch ( JSONException e ) { Logger . e ( e , "JSONException: " , e ) ; final IabResult result = new NokiaResult ( IabHelper . IABHELPER_BAD_RESPONSE , "Failed to parse purchase data." ) ; if ( mPurchaseListener != null ) { mPurchaseListener . onIabPurchaseFinished ( result , null ) ; } return ; } if ( mPurchaseListener != null ) { mPurchaseListener . onIabPurchaseFinished ( new NokiaResult ( RESULT_OK , "Success" ) , purchase ) ; } }
Called if purchase has been successful
35,549
public static void convertCygwinFilenames ( final String [ ] names ) { if ( names == null ) { throw new NullPointerException ( "names" ) ; } final File gccDir = CUtil . getExecutableLocation ( GccCCompiler . CMD_PREFIX + "gcc.exe" ) ; if ( gccDir != null ) { final String prefix = gccDir . getAbsolutePath ( ) + "/.." ; final StringBuffer buf = new StringBuffer ( ) ; for ( int i = 0 ; i < names . length ; i ++ ) { final String name = names [ i ] ; if ( name != null && name . length ( ) > 1 && name . charAt ( 0 ) == '/' ) { buf . setLength ( 0 ) ; buf . append ( prefix ) ; buf . append ( name ) ; names [ i ] = buf . toString ( ) ; } } } }
Converts absolute Cygwin file or directory names to the corresponding Win32 name .
35,550
public static String [ ] getSpecs ( ) { if ( specs == null ) { final File gccParent = CUtil . getExecutableLocation ( GccCCompiler . CMD_PREFIX + "gcc.exe" ) ; if ( gccParent != null ) { final String relativePath = "../lib/gcc-lib/" + getMachine ( ) + '/' + getVersion ( ) + "/specs" ; final File specsFile = new File ( gccParent , relativePath ) ; try { final BufferedReader reader = new BufferedReader ( new FileReader ( specsFile ) ) ; final Vector < String > lines = new Vector < > ( 100 ) ; String line = reader . readLine ( ) ; while ( line != null ) { lines . addElement ( line ) ; line = reader . readLine ( ) ; } specs = new String [ lines . size ( ) ] ; lines . copyInto ( specs ) ; } catch ( final IOException ex ) { } } } if ( specs == null ) { specs = new String [ 0 ] ; } return specs ; }
Returns the contents of the gcc specs file .
35,551
public static void addAll ( final Vector dest , final Object [ ] src ) { if ( src == null ) { return ; } for ( final Object element : src ) { dest . addElement ( element ) ; } }
Adds the elements of the array to the given vector
35,552
public static int checkDirectoryArray ( final String [ ] names ) { int count = 0 ; for ( int i = 0 ; i < names . length ; i ++ ) { if ( names [ i ] != null ) { final File dir = new File ( names [ i ] ) ; if ( dir . exists ( ) && dir . isDirectory ( ) ) { count ++ ; } else { names [ i ] = null ; } } } return count ; }
Checks a array of names for non existent or non directory entries and nulls them out .
35,553
public static String getBasename ( final File file ) { final String path = file . getPath ( ) ; String basename = file . getName ( ) ; final int pos = basename . lastIndexOf ( '.' ) ; if ( pos != - 1 ) { basename = basename . substring ( 0 , pos ) ; } return basename ; }
Extracts the basename of a file removing the extension if present
35,554
public static File getExecutableLocation ( final String exeName ) { final File currentDir = new File ( System . getProperty ( "user.dir" ) ) ; if ( new File ( currentDir , exeName ) . exists ( ) ) { return currentDir ; } final File [ ] envPath = CUtil . getPathFromEnvironment ( "PATH" , File . pathSeparator ) ; for ( final File element : envPath ) { if ( new File ( element , exeName ) . exists ( ) ) { return element ; } } return null ; }
Gets the parent directory for the executable file name using the current directory and system executable path
35,555
public static String getParentPath ( final String path ) { final int pos = path . lastIndexOf ( File . separator ) ; if ( pos <= 0 ) { return null ; } return path . substring ( 0 , pos ) ; }
Extracts the parent of a file
35,556
public static File [ ] getPathFromEnvironment ( final String envVariable , final String delim ) { if ( System . getProperty ( "os.name" ) . equals ( "OS/400" ) ) { return new File [ ] { } ; } final Vector osEnv = Execute . getProcEnvironment ( ) ; final String match = envVariable . concat ( "=" ) ; for ( final Enumeration e = osEnv . elements ( ) ; e . hasMoreElements ( ) ; ) { final String entry = ( ( String ) e . nextElement ( ) ) . trim ( ) ; if ( entry . length ( ) > match . length ( ) ) { final String entryFrag = entry . substring ( 0 , match . length ( ) ) ; if ( entryFrag . equalsIgnoreCase ( match ) ) { final String path = entry . substring ( match . length ( ) ) ; return parsePath ( path , delim ) ; } } } final File [ ] noPath = new File [ 0 ] ; return noPath ; }
Returns an array of File for each existing directory in the specified environment variable
35,557
public static boolean isSystemPath ( final File source ) { final String lcPath = source . getAbsolutePath ( ) . toLowerCase ( java . util . Locale . US ) ; return lcPath . contains ( "platformsdk" ) || lcPath . contains ( "windows kits" ) || lcPath . contains ( "microsoft" ) || Objects . equals ( lcPath , "/usr/include" ) || Objects . equals ( lcPath , "/usr/lib" ) || Objects . equals ( lcPath , "/usr/local/include" ) || Objects . equals ( lcPath , "/usr/local/lib" ) ; }
Determines if source file has a system path that is part of the compiler or platform .
35,558
public static boolean sameList ( final Object [ ] a , final Object [ ] b ) { if ( a == null || b == null || a . length != b . length ) { return false ; } for ( int i = 0 ; i < a . length ; i ++ ) { if ( ! a [ i ] . equals ( b [ i ] ) ) { return false ; } } return true ; }
Compares the contents of 2 arrays for equaliy .
35,559
public static boolean sameList ( final Vector v , final Object [ ] a ) { if ( v == null || a == null || v . size ( ) != a . length ) { return false ; } for ( int i = 0 ; i < a . length ; i ++ ) { final Object o = a [ i ] ; if ( ! o . equals ( v . elementAt ( i ) ) ) { return false ; } } return true ; }
Compares the contents of an array and a Vector for equality .
35,560
public static String [ ] toArray ( final Vector src ) { final String [ ] retval = new String [ src . size ( ) ] ; src . copyInto ( retval ) ; return retval ; }
Converts a vector to a string array .
35,561
public static String xmlAttribEncode ( final String attrValue ) { final StringBuffer buf = new StringBuffer ( attrValue ) ; int quotePos ; for ( quotePos = - 1 ; ( quotePos = buf . indexOf ( "\"" , quotePos + 1 ) ) >= 0 ; ) { buf . deleteCharAt ( quotePos ) ; buf . insert ( quotePos , "&quot;" ) ; quotePos += 5 ; } for ( quotePos = - 1 ; ( quotePos = buf . indexOf ( "<" , quotePos + 1 ) ) >= 0 ; ) { buf . deleteCharAt ( quotePos ) ; buf . insert ( quotePos , "&lt;" ) ; quotePos += 3 ; } for ( quotePos = - 1 ; ( quotePos = buf . indexOf ( ">" , quotePos + 1 ) ) >= 0 ; ) { buf . deleteCharAt ( quotePos ) ; buf . insert ( quotePos , "&gt;" ) ; quotePos += 3 ; } return buf . toString ( ) ; }
Replaces any embedded quotes in the string so that the value can be placed in an attribute in an XML file
35,562
public static void serialize ( final Map propertyList , final List comments , final File file ) throws IOException , SAXException , TransformerConfigurationException { final SAXTransformerFactory sf = ( SAXTransformerFactory ) TransformerFactory . newInstance ( ) ; final TransformerHandler handler = sf . newTransformerHandler ( ) ; final FileOutputStream os = new FileOutputStream ( file ) ; final StreamResult result = new StreamResult ( os ) ; handler . setResult ( result ) ; handler . startDocument ( ) ; for ( final Object comment1 : comments ) { final char [ ] comment = String . valueOf ( comment1 ) . toCharArray ( ) ; handler . comment ( comment , 0 , comment . length ) ; } final AttributesImpl attributes = new AttributesImpl ( ) ; handler . startElement ( null , "plist" , "plist" , attributes ) ; serializeMap ( propertyList , handler ) ; handler . endElement ( null , "plist" , "plist" ) ; handler . endDocument ( ) ; }
Serializes a property list into a Cocoa XML Property List document .
35,563
private static void serializeBoolean ( final Boolean val , final ContentHandler handler ) throws SAXException { String tag = "false" ; if ( val . booleanValue ( ) ) { tag = "true" ; } final AttributesImpl attributes = new AttributesImpl ( ) ; handler . startElement ( null , tag , tag , attributes ) ; handler . endElement ( null , tag , tag ) ; }
Serialize a Boolean as a true or false element .
35,564
private static void serializeElement ( final String tag , final String content , final ContentHandler handler ) throws SAXException { final AttributesImpl attributes = new AttributesImpl ( ) ; handler . startElement ( null , tag , tag , attributes ) ; handler . characters ( content . toCharArray ( ) , 0 , content . length ( ) ) ; handler . endElement ( null , tag , tag ) ; }
Creates an element with the specified tag name and character content .
35,565
private static void serializeInteger ( final Number integer , final ContentHandler handler ) throws SAXException { serializeElement ( "integer" , String . valueOf ( integer . longValue ( ) ) , handler ) ; }
Serialize a Number as an integer element .
35,566
private static void serializeList ( final List list , final ContentHandler handler ) throws SAXException { final AttributesImpl attributes = new AttributesImpl ( ) ; handler . startElement ( null , "array" , "array" , attributes ) ; for ( final Object aList : list ) { serializeObject ( aList , handler ) ; } handler . endElement ( null , "array" , "array" ) ; }
Serialize a list as an array element .
35,567
private static void serializeMap ( final Map map , final ContentHandler handler ) throws SAXException { final AttributesImpl attributes = new AttributesImpl ( ) ; handler . startElement ( null , "dict" , "dict" , attributes ) ; if ( map . size ( ) > 0 ) { final Object [ ] keys = map . keySet ( ) . toArray ( ) ; Arrays . sort ( keys ) ; for ( final Object key2 : keys ) { final String key = String . valueOf ( key2 ) ; handler . startElement ( null , "key" , "key" , attributes ) ; handler . characters ( key . toCharArray ( ) , 0 , key . length ( ) ) ; handler . endElement ( null , "key" , "key" ) ; serializeObject ( map . get ( key2 ) , handler ) ; } } handler . endElement ( null , "dict" , "dict" ) ; }
Serialize a map as a dict element .
35,568
private static void serializeObject ( final Object obj , final ContentHandler handler ) throws SAXException { if ( obj instanceof Map ) { serializeMap ( ( Map ) obj , handler ) ; } else if ( obj instanceof List ) { serializeList ( ( List ) obj , handler ) ; } else if ( obj instanceof Number ) { if ( obj instanceof Double || obj instanceof Float ) { serializeReal ( ( Number ) obj , handler ) ; } else { serializeInteger ( ( Number ) obj , handler ) ; } } else if ( obj instanceof Boolean ) { serializeBoolean ( ( Boolean ) obj , handler ) ; } else { serializeString ( String . valueOf ( obj ) , handler ) ; } }
Serialize an object using the best available element .
35,569
private static void serializeReal ( final Number real , final ContentHandler handler ) throws SAXException { serializeElement ( "real" , String . valueOf ( real . doubleValue ( ) ) , handler ) ; }
Serialize a Number as a real element .
35,570
protected boolean canParse ( final File sourceFile ) { final String sourceName = sourceFile . toString ( ) ; final int lastPeriod = sourceName . lastIndexOf ( '.' ) ; if ( lastPeriod >= 0 && lastPeriod == sourceName . length ( ) - 4 ) { final String ext = sourceName . substring ( lastPeriod ) . toUpperCase ( ) ; if ( ext . equals ( ".DLL" ) || ext . equals ( ".TLB" ) || ext . equals ( ".RES" ) ) { return false ; } } return true ; }
Checks file name to see if parse should be attempted
35,571
public final DependencyInfo parseIncludes ( final CCTask task , final File source , final File [ ] includePath , final File [ ] sysIncludePath , final File [ ] envIncludePath , final File baseDir , final String includePathIdentifier ) { long sourceLastModified = source . lastModified ( ) ; final File [ ] sourcePath = new File [ 1 ] ; sourcePath [ 0 ] = new File ( source . getParent ( ) ) ; final Vector onIncludePath = new Vector ( ) ; final Vector onSysIncludePath = new Vector ( ) ; String baseDirPath ; try { baseDirPath = baseDir . getCanonicalPath ( ) ; } catch ( final IOException ex ) { baseDirPath = baseDir . toString ( ) ; } final String relativeSource = CUtil . getRelativePath ( baseDirPath , source ) ; String [ ] includes = emptyIncludeArray ; if ( canParse ( source ) ) { final Parser parser = createParser ( source ) ; try { final Reader reader = new BufferedReader ( new FileReader ( source ) ) ; parser . parse ( reader ) ; includes = parser . getIncludes ( ) ; } catch ( final IOException ex ) { task . log ( "Error parsing " + source . toString ( ) + ":" + ex . toString ( ) ) ; includes = new String [ 0 ] ; } } for ( final String include : includes ) { if ( ! resolveInclude ( include , sourcePath , onIncludePath ) ) { if ( ! resolveInclude ( include , includePath , onIncludePath ) ) { if ( ! resolveInclude ( include , sysIncludePath , onSysIncludePath ) ) { if ( ! resolveInclude ( include , envIncludePath , onSysIncludePath ) ) { sourceLastModified += 2 * CUtil . FILETIME_EPSILON ; } } } } } for ( int i = 0 ; i < onIncludePath . size ( ) ; i ++ ) { final String relativeInclude = CUtil . getRelativePath ( baseDirPath , ( File ) onIncludePath . elementAt ( i ) ) ; onIncludePath . setElementAt ( relativeInclude , i ) ; } for ( int i = 0 ; i < onSysIncludePath . size ( ) ; i ++ ) { final String relativeInclude = CUtil . getRelativePath ( baseDirPath , ( File ) onSysIncludePath . elementAt ( i ) ) ; onSysIncludePath . setElementAt ( relativeInclude , i ) ; } return new DependencyInfo ( includePathIdentifier , relativeSource , sourceLastModified , onIncludePath , onSysIncludePath ) ; }
Returns dependency info for the specified source file
35,572
private static void addAttribute ( final AttributesImpl attributes , final String attrName , final String attrValue ) { if ( attrName == null ) { throw new IllegalArgumentException ( "attrName" ) ; } if ( attrValue != null ) { attributes . addAttribute ( null , attrName , attrName , "#PCDATA" , attrValue ) ; } }
Adds an non - namespace - qualified attribute to attribute list .
35,573
private String getAdditionalDependencies ( final TargetInfo linkTarget , final List < DependencyDef > projectDependencies , final Map < String , TargetInfo > targets , final String basePath ) { String dependencies = null ; final File [ ] linkSources = linkTarget . getAllSources ( ) ; final StringBuffer buf = new StringBuffer ( ) ; for ( final File linkSource : linkSources ) { if ( targets . get ( linkSource . getName ( ) ) == null ) { String relPath = linkSource . getName ( ) ; boolean fromDependency = false ; if ( relPath . indexOf ( "." ) > 0 ) { final String baseName = relPath . substring ( 0 , relPath . indexOf ( "." ) ) ; for ( DependencyDef depend : projectDependencies ) { if ( baseName . compareToIgnoreCase ( depend . getName ( ) ) == 0 ) { fromDependency = true ; } } } if ( ! fromDependency ) { if ( ! CUtil . isSystemPath ( linkSource ) ) { relPath = CUtil . getRelativePath ( basePath , linkSource ) ; } if ( relPath . indexOf ( ' ' ) > 0 ) { buf . append ( '\"' ) ; buf . append ( CUtil . toWindowsPath ( relPath ) ) ; buf . append ( '\"' ) ; } else { buf . append ( relPath ) ; } buf . append ( ' ' ) ; } } } if ( buf . length ( ) > 0 ) { buf . setLength ( buf . length ( ) - 1 ) ; dependencies = buf . toString ( ) ; } return dependencies ; }
Get value of AdditionalDependencies property .
35,574
private String getAdditionalIncludeDirectories ( final String baseDir , final CommandLineCompilerConfiguration compilerConfig ) { final File [ ] includePath = compilerConfig . getIncludePath ( ) ; final StringBuffer includeDirs = new StringBuffer ( ) ; final String [ ] args = compilerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( arg . startsWith ( "/I" ) ) { includeDirs . append ( arg . substring ( 2 ) ) ; includeDirs . append ( ';' ) ; } } if ( includeDirs . length ( ) > 0 ) { includeDirs . setLength ( includeDirs . length ( ) - 1 ) ; } return includeDirs . toString ( ) ; }
Get value of AdditionalIncludeDirectories property .
35,575
private String getBasicRuntimeChecks ( final CommandLineCompilerConfiguration compilerConfig ) { String checks = "0" ; final String [ ] args = compilerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( "/RTCs" . equals ( arg ) ) { checks = "1" ; } if ( "/RTCu" . equals ( arg ) ) { checks = "2" ; } if ( "/RTC1" . equals ( arg ) || "/GZ" . equals ( arg ) ) { checks = "3" ; } } return checks ; }
Get value of BasicRuntimeChecks property .
35,576
private String getCharacterSet ( final CommandLineCompilerConfiguration compilerConfig ) { final String [ ] args = compilerConfig . getPreArguments ( ) ; String charset = "0" ; for ( final String arg : args ) { if ( "/D_UNICODE" . equals ( arg ) || "/DUNICODE" . equals ( arg ) ) { charset = "1" ; } if ( "/D_MBCS" . equals ( arg ) ) { charset = "2" ; } } return charset ; }
Get character set for Windows API .
35,577
private String getConfigurationType ( final CCTask task ) { final String outputType = task . getOuttype ( ) ; String targtype = "2" ; if ( "executable" . equals ( outputType ) ) { targtype = "1" ; } else if ( "static" . equals ( outputType ) ) { targtype = "4" ; } return targtype ; }
Gets the configuration type .
35,578
private String getDebugInformationFormat ( final CommandLineCompilerConfiguration compilerConfig ) { String format = "0" ; final String [ ] args = compilerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( "/Z7" . equals ( arg ) ) { format = "1" ; } if ( "/Zd" . equals ( arg ) ) { format = "2" ; } if ( "/Zi" . equals ( arg ) ) { format = "3" ; } if ( "/ZI" . equals ( arg ) ) { format = "4" ; } } return format ; }
Get value of DebugInformationFormat property .
35,579
private String getDetect64BitPortabilityProblems ( final CommandLineCompilerConfiguration compilerConfig ) { String warn64 = null ; final String [ ] args = compilerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( "/Wp64" . equals ( arg ) ) { warn64 = this . trueLiteral ; } } return warn64 ; }
Get value of Detect64BitPortabilityProblems property .
35,580
private String getLinkIncremental ( final CommandLineLinkerConfiguration linkerConfig ) { String incremental = "0" ; final String [ ] args = linkerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( "/INCREMENTAL:NO" . equals ( arg ) ) { incremental = "1" ; } if ( "/INCREMENTAL:YES" . equals ( arg ) ) { incremental = "2" ; } } return incremental ; }
Get value of LinkIncremental property .
35,581
private String getOptimization ( final CommandLineCompilerConfiguration compilerConfig ) { final String [ ] args = compilerConfig . getPreArguments ( ) ; String opt = "0" ; for ( final String arg : args ) { if ( "/Od" . equals ( arg ) ) { opt = "0" ; } if ( "/O1" . equals ( arg ) ) { opt = "1" ; } if ( "/O2" . equals ( arg ) ) { opt = "2" ; } if ( "/Ox" . equals ( arg ) ) { opt = "3" ; } } return opt ; }
Get value of Optimization property .
35,582
private String getPrecompiledHeaderFile ( final CommandLineCompilerConfiguration compilerConfig ) { String pch = null ; final String [ ] args = compilerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( arg . startsWith ( "/Fp" ) ) { pch = arg . substring ( 3 ) ; } } return pch ; }
Get value of PrecompiledHeaderFile property .
35,583
private String getPreprocessorDefinitions ( final CommandLineCompilerConfiguration compilerConfig , final boolean isDebug ) { final StringBuffer defines = new StringBuffer ( ) ; final String [ ] args = compilerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( arg . startsWith ( "/D" ) ) { String macro = arg . substring ( 2 ) ; if ( isDebug ) { if ( macro . equals ( "NDEBUG" ) ) { macro = "_DEBUG" ; } } else { if ( macro . equals ( "_DEBUG" ) ) { macro = "NDEBUG" ; } } defines . append ( macro ) ; defines . append ( ";" ) ; } } if ( defines . length ( ) > 0 ) { defines . setLength ( defines . length ( ) - 1 ) ; } return defines . toString ( ) ; }
Get value of PreprocessorDefinitions property .
35,584
private String getRuntimeLibrary ( final CommandLineCompilerConfiguration compilerConfig , final boolean isDebug ) { String rtl = null ; final String [ ] args = compilerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( arg . startsWith ( "/MT" ) ) { if ( isDebug ) { rtl = "1" ; } else { rtl = "0" ; } } else if ( arg . startsWith ( "/MD" ) ) { if ( isDebug ) { rtl = "3" ; } else { rtl = "2" ; } } } return rtl ; }
Get value of RuntimeLibrary property .
35,585
private String getSubsystem ( final CommandLineLinkerConfiguration linkerConfig ) { String subsystem = "0" ; final String [ ] args = linkerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( "/SUBSYSTEM:CONSOLE" . equals ( arg ) ) { subsystem = "1" ; } if ( "/SUBSYSTEM:WINDOWS" . equals ( arg ) ) { subsystem = "2" ; } if ( "/SUBSYSTEM:WINDOWSCE" . equals ( arg ) ) { subsystem = "9" ; } } return subsystem ; }
Get value of Subsystem property .
35,586
private String getTargetMachine ( final CommandLineLinkerConfiguration linkerConfig ) { String subsystem = "0" ; final String [ ] args = linkerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( "/MACHINE:X86" . equals ( arg ) ) { subsystem = "1" ; } } return subsystem ; }
Get value of TargetMachine property .
35,587
private String getUsePrecompiledHeader ( final CommandLineCompilerConfiguration compilerConfig ) { String usePCH = "0" ; final String [ ] args = compilerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( "/Yc" . equals ( arg ) ) { usePCH = "1" ; } if ( "/Yu" . equals ( arg ) ) { usePCH = "2" ; } } return usePCH ; }
Get value of UsePrecompiledHeader property .
35,588
private String getWarningLevel ( final CommandLineCompilerConfiguration compilerConfig ) { String warn = null ; final String [ ] args = compilerConfig . getPreArguments ( ) ; for ( final String arg : args ) { if ( "/W0" . equals ( arg ) ) { warn = "0" ; } if ( "/W1" . equals ( arg ) ) { warn = "1" ; } if ( "/W2" . equals ( arg ) ) { warn = "2" ; } if ( "/W3" . equals ( arg ) ) { warn = "3" ; } if ( "/W4" . equals ( arg ) ) { warn = "4" ; } } return warn ; }
Get value of WarningLevel property .
35,589
private boolean isGroupMember ( final String filter , final File candidate ) { final String fileName = candidate . getName ( ) ; final int lastDot = fileName . lastIndexOf ( '.' ) ; if ( lastDot >= 0 && lastDot < fileName . length ( ) - 1 ) { final String extension = ";" + fileName . substring ( lastDot + 1 ) . toLowerCase ( ) + ";" ; final String semiFilter = ";" + filter + ";" ; return semiFilter . contains ( extension ) ; } return false ; }
Returns true if the file has an extension that appears in the group filter .
35,590
private void writeCompilerElement ( final ContentHandler content , final boolean isDebug , final String basePath , final CommandLineCompilerConfiguration compilerConfig ) throws SAXException { final AttributesImpl attributes = new AttributesImpl ( ) ; addAttribute ( attributes , "Name" , "VCCLCompilerTool" ) ; String optimization = getOptimization ( compilerConfig ) ; String debugFormat = getDebugInformationFormat ( compilerConfig ) ; if ( isDebug ) { optimization = "0" ; if ( "0" . equals ( debugFormat ) ) { debugFormat = "4" ; } } else { if ( "0" . equals ( optimization ) ) { optimization = "2" ; } debugFormat = "0" ; } addAttribute ( attributes , "Optimization" , optimization ) ; addAttribute ( attributes , "AdditionalIncludeDirectories" , getAdditionalIncludeDirectories ( basePath , compilerConfig ) ) ; addAttribute ( attributes , "PreprocessorDefinitions" , getPreprocessorDefinitions ( compilerConfig , isDebug ) ) ; addAttribute ( attributes , "MinimalRebuild" , this . trueLiteral ) ; addAttribute ( attributes , "BasicRuntimeChecks" , getBasicRuntimeChecks ( compilerConfig ) ) ; addAttribute ( attributes , "RuntimeLibrary" , getRuntimeLibrary ( compilerConfig , isDebug ) ) ; addAttribute ( attributes , "UsePrecompiledHeader" , getUsePrecompiledHeader ( compilerConfig ) ) ; addAttribute ( attributes , "PrecompiledHeaderFile" , getPrecompiledHeaderFile ( compilerConfig ) ) ; addAttribute ( attributes , "WarningLevel" , getWarningLevel ( compilerConfig ) ) ; addAttribute ( attributes , "Detect64BitPortabilityProblems" , getDetect64BitPortabilityProblems ( compilerConfig ) ) ; addAttribute ( attributes , "DebugInformationFormat" , debugFormat ) ; content . startElement ( null , "Tool" , "Tool" , attributes ) ; content . endElement ( null , "Tool" , "Tool" ) ; }
write the Compiler element .
35,591
private void writeConfigurationStartTag ( final ContentHandler content , final boolean isDebug , final CCTask task , final CommandLineCompilerConfiguration compilerConfig ) throws SAXException { final AttributesImpl attributes = new AttributesImpl ( ) ; if ( isDebug ) { addAttribute ( attributes , "Name" , "Debug|Win32" ) ; addAttribute ( attributes , "OutputDirectory" , "Debug" ) ; addAttribute ( attributes , "IntermediateDirectory" , "Debug" ) ; } else { addAttribute ( attributes , "Name" , "Release|Win32" ) ; addAttribute ( attributes , "OutputDirectory" , "Release" ) ; addAttribute ( attributes , "IntermediateDirectory" , "Release" ) ; } addAttribute ( attributes , "ConfigurationType" , getConfigurationType ( task ) ) ; addAttribute ( attributes , "CharacterSet" , getCharacterSet ( compilerConfig ) ) ; content . startElement ( null , "Configuration" , "Configuration" , attributes ) ; }
Write the start tag of the Configuration element .
35,592
private void writeFilteredSources ( final String name , final String filter , final String basePath , final File [ ] sortedSources , final ContentHandler content ) throws SAXException { final AttributesImpl filterAttrs = new AttributesImpl ( ) ; filterAttrs . addAttribute ( null , "Name" , "Name" , "#PCDATA" , name ) ; filterAttrs . addAttribute ( null , "Filter" , "Filter" , "#PCDATA" , filter ) ; content . startElement ( null , "Filter" , "Filter" , filterAttrs ) ; final AttributesImpl fileAttrs = new AttributesImpl ( ) ; fileAttrs . addAttribute ( null , "RelativePath" , "RelativePath" , "#PCDATA" , "" ) ; for ( final File sortedSource : sortedSources ) { if ( isGroupMember ( filter , sortedSource ) ) { final String relativePath = CUtil . getRelativePath ( basePath , sortedSource ) ; fileAttrs . setValue ( 0 , relativePath ) ; content . startElement ( null , "File" , "File" , fileAttrs ) ; content . endElement ( null , "File" , "File" ) ; } } content . endElement ( null , "Filter" , "Filter" ) ; }
Writes a cluster of source files to the project .
35,593
private void writeLinkerElement ( final ContentHandler content , final boolean isDebug , final List < DependencyDef > dependencies , final String basePath , final TargetInfo linkTarget , final Map < String , TargetInfo > targets ) throws SAXException { final AttributesImpl attributes = new AttributesImpl ( ) ; addAttribute ( attributes , "Name" , "VCLinkerTool" ) ; final ProcessorConfiguration config = linkTarget . getConfiguration ( ) ; if ( config instanceof CommandLineLinkerConfiguration ) { final CommandLineLinkerConfiguration linkerConfig = ( CommandLineLinkerConfiguration ) config ; if ( linkerConfig . getLinker ( ) instanceof MsvcCompatibleLinker ) { addAttribute ( attributes , "LinkIncremental" , getLinkIncremental ( linkerConfig ) ) ; if ( isDebug ) { addAttribute ( attributes , "GenerateDebugInformation" , this . trueLiteral ) ; } else { addAttribute ( attributes , "GenerateDebugInformation" , this . falseLiteral ) ; } addAttribute ( attributes , "SubSystem" , getSubsystem ( linkerConfig ) ) ; addAttribute ( attributes , "TargetMachine" , getTargetMachine ( linkerConfig ) ) ; } } addAttribute ( attributes , "AdditionalDependencies" , getAdditionalDependencies ( linkTarget , dependencies , targets , basePath ) ) ; content . startElement ( null , "Tool" , "Tool" , attributes ) ; content . endElement ( null , "Tool" , "Tool" ) ; }
Write Tool element for linker .
35,594
protected String getIncludeDirSwitch ( final String source ) { final StringBuffer buf = new StringBuffer ( "-I" ) ; quoteFile ( buf , source ) ; return buf . toString ( ) ; }
Returns command line option to specify include directory
35,595
public static JavaClass getBcelClass ( final String filename ) throws IOException { final ClassParser parser = new ClassParser ( filename ) ; return parser . parse ( ) ; }
Returns the Bcel Class corresponding to the given class filename
35,596
public static String replace ( final CharSequence target , final CharSequence replacement , final String string ) { return Pattern . compile ( quote ( target . toString ( ) ) ) . matcher ( string ) . replaceAll ( quoteReplacement ( replacement . toString ( ) ) ) ; }
Replaces target with replacement in string . For jdk 1 . 4 compatiblity .
35,597
protected Parser createParser ( final File source ) { if ( source != null ) { final String sourceName = source . getName ( ) ; final int lastDot = sourceName . lastIndexOf ( '.' ) ; if ( lastDot >= 0 && lastDot + 1 < sourceName . length ( ) ) { final char afterDot = sourceName . charAt ( lastDot + 1 ) ; if ( afterDot == 'f' || afterDot == 'F' ) { return new FortranParser ( ) ; } } } return new CParser ( ) ; }
Create parser to determine dependencies .
35,598
private static String arraysToString ( final Object [ ] a ) { if ( a == null ) { return "null" ; } final int iMax = a . length - 1 ; if ( iMax == - 1 ) { return "[]" ; } final StringBuilder b = new StringBuilder ( ) ; b . append ( '[' ) ; for ( int i = 0 ; ; i ++ ) { b . append ( String . valueOf ( a [ i ] ) ) ; if ( i == iMax ) { return b . append ( ']' ) . toString ( ) ; } b . append ( ", " ) ; } }
JDK 1 . 4 compatibility
35,599
protected String quoteFilename ( final StringBuffer buf , final String filename ) { buf . setLength ( 0 ) ; BorlandProcessor . quoteFile ( buf , filename ) ; return buf . toString ( ) ; }
Encloses problematic file names within quotes .