idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
35,900 | static BlockCanaryInternals getInstance ( ) { if ( sInstance == null ) { synchronized ( BlockCanaryInternals . class ) { if ( sInstance == null ) { sInstance = new BlockCanaryInternals ( ) ; } } } return sInstance ; } | Get BlockCanaryInternals singleton |
35,901 | public static String save ( String str ) { String path ; synchronized ( SAVE_DELETE_LOCK ) { path = save ( "looper" , str ) ; } return path ; } | Save log to file |
35,902 | public static void cleanObsolete ( ) { HandlerThreadFactory . getWriteLogThreadHandler ( ) . post ( new Runnable ( ) { public void run ( ) { long now = System . currentTimeMillis ( ) ; File [ ] f = BlockCanaryInternals . getLogFiles ( ) ; if ( f != null && f . length > 0 ) { synchronized ( SAVE_DELETE_LOCK ) { for ( File aF : f ) { if ( now - aF . lastModified ( ) > OBSOLETE_DURATION ) { aF . delete ( ) ; } } } } } } ) ; } | Delete obsolete log files which is by default 2 days . |
35,903 | public String getCpuRateInfo ( ) { StringBuilder sb = new StringBuilder ( ) ; synchronized ( mCpuInfoEntries ) { for ( Map . Entry < Long , String > entry : mCpuInfoEntries . entrySet ( ) ) { long time = entry . getKey ( ) ; sb . append ( BlockInfo . TIME_FORMATTER . format ( time ) ) . append ( ' ' ) . append ( entry . getValue ( ) ) . append ( BlockInfo . SEPARATOR ) ; } } return sb . toString ( ) ; } | Get cpu rate information |
35,904 | public void stop ( ) { if ( mMonitorStarted ) { mMonitorStarted = false ; Looper . getMainLooper ( ) . setMessageLogging ( null ) ; mBlockCanaryCore . stackSampler . stop ( ) ; mBlockCanaryCore . cpuSampler . stop ( ) ; } } | Stop monitoring . |
35,905 | public void recordStartTime ( ) { PreferenceManager . getDefaultSharedPreferences ( BlockCanaryContext . get ( ) . provideContext ( ) ) . edit ( ) . putLong ( "BlockCanary_StartTime" , System . currentTimeMillis ( ) ) . commit ( ) ; } | Record monitor start time to preference you may use it when after push which tells start BlockCanary . |
35,906 | public boolean isMonitorDurationEnd ( ) { long startTime = PreferenceManager . getDefaultSharedPreferences ( BlockCanaryContext . get ( ) . provideContext ( ) ) . getLong ( "BlockCanary_StartTime" , 0 ) ; return startTime != 0 && System . currentTimeMillis ( ) - startTime > BlockCanaryContext . get ( ) . provideMonitorDuration ( ) * 3600 * 1000 ; } | Is monitor duration end compute from recordStartTime end provideMonitorDuration . |
35,907 | private HttpResponse directUpload ( GenericUrl initiationRequestUrl ) throws IOException { updateStateAndNotifyListener ( UploadState . MEDIA_IN_PROGRESS ) ; HttpContent content = mediaContent ; if ( metadata != null ) { content = new MultipartContent ( ) . setContentParts ( Arrays . asList ( metadata , mediaContent ) ) ; initiationRequestUrl . put ( "uploadType" , "multipart" ) ; } else { initiationRequestUrl . put ( "uploadType" , "media" ) ; } HttpRequest request = requestFactory . buildRequest ( initiationRequestMethod , initiationRequestUrl , content ) ; request . getHeaders ( ) . putAll ( initiationHeaders ) ; HttpResponse response = executeCurrentRequest ( request ) ; boolean responseProcessed = false ; try { if ( isMediaLengthKnown ( ) ) { totalBytesServerReceived = getMediaContentLength ( ) ; } updateStateAndNotifyListener ( UploadState . MEDIA_COMPLETE ) ; responseProcessed = true ; } finally { if ( ! responseProcessed ) { response . disconnect ( ) ; } } return response ; } | Direct Uploads the media . |
35,908 | private HttpResponse resumableUpload ( GenericUrl initiationRequestUrl ) throws IOException { HttpResponse initialResponse = executeUploadInitiation ( initiationRequestUrl ) ; if ( ! initialResponse . isSuccessStatusCode ( ) ) { return initialResponse ; } GenericUrl uploadUrl ; try { uploadUrl = new GenericUrl ( initialResponse . getHeaders ( ) . getLocation ( ) ) ; } finally { initialResponse . disconnect ( ) ; } contentInputStream = mediaContent . getInputStream ( ) ; if ( ! contentInputStream . markSupported ( ) && isMediaLengthKnown ( ) ) { contentInputStream = new BufferedInputStream ( contentInputStream ) ; } HttpResponse response ; while ( true ) { ContentChunk contentChunk = buildContentChunk ( ) ; currentRequest = requestFactory . buildPutRequest ( uploadUrl , null ) ; currentRequest . setContent ( contentChunk . getContent ( ) ) ; currentRequest . getHeaders ( ) . setContentRange ( contentChunk . getContentRange ( ) ) ; new MediaUploadErrorHandler ( this , currentRequest ) ; if ( isMediaLengthKnown ( ) ) { response = executeCurrentRequestWithoutGZip ( currentRequest ) ; } else { response = executeCurrentRequest ( currentRequest ) ; } boolean returningResponse = false ; try { if ( response . isSuccessStatusCode ( ) ) { totalBytesServerReceived = getMediaContentLength ( ) ; if ( mediaContent . getCloseInputStream ( ) ) { contentInputStream . close ( ) ; } updateStateAndNotifyListener ( UploadState . MEDIA_COMPLETE ) ; returningResponse = true ; return response ; } if ( response . getStatusCode ( ) != 308 ) { returningResponse = true ; return response ; } String updatedUploadUrl = response . getHeaders ( ) . getLocation ( ) ; if ( updatedUploadUrl != null ) { uploadUrl = new GenericUrl ( updatedUploadUrl ) ; } long newBytesServerReceived = getNextByteIndex ( response . getHeaders ( ) . getRange ( ) ) ; long currentBytesServerReceived = newBytesServerReceived - totalBytesServerReceived ; Preconditions . checkState ( currentBytesServerReceived >= 0 && currentBytesServerReceived <= currentChunkLength ) ; long copyBytes = currentChunkLength - currentBytesServerReceived ; if ( isMediaLengthKnown ( ) ) { if ( copyBytes > 0 ) { contentInputStream . reset ( ) ; long actualSkipValue = contentInputStream . skip ( currentBytesServerReceived ) ; Preconditions . checkState ( currentBytesServerReceived == actualSkipValue ) ; } } else if ( copyBytes == 0 ) { currentRequestContentBuffer = null ; } totalBytesServerReceived = newBytesServerReceived ; updateStateAndNotifyListener ( UploadState . MEDIA_IN_PROGRESS ) ; } finally { if ( ! returningResponse ) { response . disconnect ( ) ; } } } } | Uploads the media in a resumable manner . |
35,909 | private HttpResponse executeUploadInitiation ( GenericUrl initiationRequestUrl ) throws IOException { updateStateAndNotifyListener ( UploadState . INITIATION_STARTED ) ; initiationRequestUrl . put ( "uploadType" , "resumable" ) ; HttpContent content = metadata == null ? new EmptyContent ( ) : metadata ; HttpRequest request = requestFactory . buildRequest ( initiationRequestMethod , initiationRequestUrl , content ) ; initiationHeaders . set ( CONTENT_TYPE_HEADER , mediaContent . getType ( ) ) ; if ( isMediaLengthKnown ( ) ) { initiationHeaders . set ( CONTENT_LENGTH_HEADER , getMediaContentLength ( ) ) ; } request . getHeaders ( ) . putAll ( initiationHeaders ) ; HttpResponse response = executeCurrentRequest ( request ) ; boolean notificationCompleted = false ; try { updateStateAndNotifyListener ( UploadState . INITIATION_COMPLETE ) ; notificationCompleted = true ; } finally { if ( ! notificationCompleted ) { response . disconnect ( ) ; } } return response ; } | This method sends a POST request with empty content to get the unique upload URL . |
35,910 | private HttpResponse executeCurrentRequestWithoutGZip ( HttpRequest request ) throws IOException { new MethodOverride ( ) . intercept ( request ) ; request . setThrowExceptionOnExecuteError ( false ) ; HttpResponse response = request . execute ( ) ; return response ; } | Executes the current request with some minimal common code . |
35,911 | private HttpResponse executeCurrentRequest ( HttpRequest request ) throws IOException { if ( ! disableGZipContent && ! ( request . getContent ( ) instanceof EmptyContent ) ) { request . setEncoding ( new GZipEncoding ( ) ) ; } HttpResponse response = executeCurrentRequestWithoutGZip ( request ) ; return response ; } | Executes the current request with some common code that includes exponential backoff and GZip encoding . |
35,912 | private ContentChunk buildContentChunk ( ) throws IOException { int blockSize ; if ( isMediaLengthKnown ( ) ) { blockSize = ( int ) Math . min ( chunkSize , getMediaContentLength ( ) - totalBytesServerReceived ) ; } else { blockSize = chunkSize ; } AbstractInputStreamContent contentChunk ; int actualBlockSize = blockSize ; if ( isMediaLengthKnown ( ) ) { contentInputStream . mark ( blockSize ) ; InputStream limitInputStream = ByteStreams . limit ( contentInputStream , blockSize ) ; contentChunk = new InputStreamContent ( mediaContent . getType ( ) , limitInputStream ) . setRetrySupported ( true ) . setLength ( blockSize ) . setCloseInputStream ( false ) ; mediaContentLengthStr = String . valueOf ( getMediaContentLength ( ) ) ; } else { int actualBytesRead ; int bytesAllowedToRead ; int copyBytes = 0 ; if ( currentRequestContentBuffer == null ) { bytesAllowedToRead = cachedByte == null ? blockSize + 1 : blockSize ; currentRequestContentBuffer = new byte [ blockSize + 1 ] ; if ( cachedByte != null ) { currentRequestContentBuffer [ 0 ] = cachedByte ; } } else { copyBytes = ( int ) ( totalBytesClientSent - totalBytesServerReceived ) ; System . arraycopy ( currentRequestContentBuffer , currentChunkLength - copyBytes , currentRequestContentBuffer , 0 , copyBytes ) ; if ( cachedByte != null ) { currentRequestContentBuffer [ copyBytes ] = cachedByte ; } bytesAllowedToRead = blockSize - copyBytes ; } actualBytesRead = ByteStreams . read ( contentInputStream , currentRequestContentBuffer , blockSize + 1 - bytesAllowedToRead , bytesAllowedToRead ) ; if ( actualBytesRead < bytesAllowedToRead ) { actualBlockSize = copyBytes + Math . max ( 0 , actualBytesRead ) ; if ( cachedByte != null ) { actualBlockSize ++ ; cachedByte = null ; } if ( mediaContentLengthStr . equals ( "*" ) ) { mediaContentLengthStr = String . valueOf ( totalBytesServerReceived + actualBlockSize ) ; } } else { cachedByte = currentRequestContentBuffer [ blockSize ] ; } contentChunk = new ByteArrayContent ( mediaContent . getType ( ) , currentRequestContentBuffer , 0 , actualBlockSize ) ; totalBytesClientSent = totalBytesServerReceived + actualBlockSize ; } currentChunkLength = actualBlockSize ; String contentRange ; if ( actualBlockSize == 0 ) { contentRange = "bytes */" + mediaContentLengthStr ; } else { contentRange = "bytes " + totalBytesServerReceived + "-" + ( totalBytesServerReceived + actualBlockSize - 1 ) + "/" + mediaContentLengthStr ; } return new ContentChunk ( contentChunk , contentRange ) ; } | Sets the HTTP media content chunk and the required headers that should be used in the upload request . |
35,913 | public MediaHttpUploader setInitiationRequestMethod ( String initiationRequestMethod ) { Preconditions . checkArgument ( initiationRequestMethod . equals ( HttpMethods . POST ) || initiationRequestMethod . equals ( HttpMethods . PUT ) || initiationRequestMethod . equals ( HttpMethods . PATCH ) ) ; this . initiationRequestMethod = initiationRequestMethod ; return this ; } | Sets the HTTP method used for the initiation request . |
35,914 | private void updateStateAndNotifyListener ( UploadState uploadState ) throws IOException { this . uploadState = uploadState ; if ( progressListener != null ) { progressListener . progressChanged ( this ) ; } } | Sets the upload state and notifies the progress listener . |
35,915 | public static synchronized KeyStore getCertificateTrustStore ( ) throws IOException , GeneralSecurityException { if ( certTrustStore == null ) { certTrustStore = SecurityUtils . getJavaKeyStore ( ) ; InputStream keyStoreStream = GoogleUtils . class . getResourceAsStream ( "google.jks" ) ; SecurityUtils . loadKeyStore ( certTrustStore , keyStoreStream , "notasecret" ) ; } return certTrustStore ; } | Returns the key store for trusted root certificates to use for Google APIs . |
35,916 | private HttpResponse getFakeResponse ( final int statusCode , final InputStream partContent , List < String > headerNames , List < String > headerValues ) throws IOException { HttpRequest request = new FakeResponseHttpTransport ( statusCode , partContent , headerNames , headerValues ) . createRequestFactory ( ) . buildPostRequest ( new GenericUrl ( "http://google.com/" ) , null ) ; request . setLoggingEnabled ( false ) ; request . setThrowExceptionOnExecuteError ( false ) ; return request . execute ( ) ; } | Create a fake HTTP response object populated with the partContent and the statusCode . |
35,917 | public static GoogleAccountCredential usingOAuth2 ( Context context , Collection < String > scopes ) { Preconditions . checkArgument ( scopes != null && scopes . iterator ( ) . hasNext ( ) ) ; String scopesStr = "oauth2: " + Joiner . on ( ' ' ) . join ( scopes ) ; return new GoogleAccountCredential ( context , scopesStr ) ; } | Constructs a new instance using OAuth 2 . 0 scopes . |
35,918 | public static GoogleAccountCredential usingAudience ( Context context , String audience ) { Preconditions . checkArgument ( audience . length ( ) != 0 ) ; return new GoogleAccountCredential ( context , "audience:" + audience ) ; } | Sets the audience scope to use with Google Cloud Endpoints . |
35,919 | public final Intent newChooseAccountIntent ( ) { return AccountPicker . newChooseAccountIntent ( selectedAccount , null , new String [ ] { GoogleAccountManager . ACCOUNT_TYPE } , true , null , null , null , null ) ; } | Returns an intent to show the user to select a Google account or create a new one if there are none on the device yet . |
35,920 | public String getToken ( ) throws IOException , GoogleAuthException { if ( backOff != null ) { backOff . reset ( ) ; } while ( true ) { try { return GoogleAuthUtil . getToken ( context , accountName , scope ) ; } catch ( IOException e ) { try { if ( backOff == null || ! BackOffUtils . next ( sleeper , backOff ) ) { throw e ; } } catch ( InterruptedException e2 ) { } } } } | Returns an OAuth 2 . 0 access token . |
35,921 | public Details getDetails ( ) { Preconditions . checkArgument ( ( web == null ) != ( installed == null ) ) ; return web == null ? installed : web ; } | Returns the details for either installed or web applications . |
35,922 | private HttpResponse executeCurrentRequest ( long currentRequestLastBytePos , GenericUrl requestUrl , HttpHeaders requestHeaders , OutputStream outputStream ) throws IOException { HttpRequest request = requestFactory . buildGetRequest ( requestUrl ) ; if ( requestHeaders != null ) { request . getHeaders ( ) . putAll ( requestHeaders ) ; } if ( bytesDownloaded != 0 || currentRequestLastBytePos != - 1 ) { StringBuilder rangeHeader = new StringBuilder ( ) ; rangeHeader . append ( "bytes=" ) . append ( bytesDownloaded ) . append ( "-" ) ; if ( currentRequestLastBytePos != - 1 ) { rangeHeader . append ( currentRequestLastBytePos ) ; } request . getHeaders ( ) . setRange ( rangeHeader . toString ( ) ) ; } HttpResponse response = request . execute ( ) ; try { ByteStreams . copy ( response . getContent ( ) , outputStream ) ; } finally { response . disconnect ( ) ; } return response ; } | Executes the current request . |
35,923 | private void updateStateAndNotifyListener ( DownloadState downloadState ) throws IOException { this . downloadState = downloadState ; if ( progressListener != null ) { progressListener . progressChanged ( this ) ; } } | Sets the download state and notifies the progress listener . |
35,924 | public void execute ( ) throws IOException { boolean retryAllowed ; Preconditions . checkState ( ! requestInfos . isEmpty ( ) ) ; HttpRequest batchRequest = requestFactory . buildPostRequest ( this . batchUrl , null ) ; HttpExecuteInterceptor originalInterceptor = batchRequest . getInterceptor ( ) ; batchRequest . setInterceptor ( new BatchInterceptor ( originalInterceptor ) ) ; int retriesRemaining = batchRequest . getNumberOfRetries ( ) ; do { retryAllowed = retriesRemaining > 0 ; MultipartContent batchContent = new MultipartContent ( ) ; batchContent . getMediaType ( ) . setSubType ( "mixed" ) ; int contentId = 1 ; for ( RequestInfo < ? , ? > requestInfo : requestInfos ) { batchContent . addPart ( new MultipartContent . Part ( new HttpHeaders ( ) . setAcceptEncoding ( null ) . set ( "Content-ID" , contentId ++ ) , new HttpRequestContent ( requestInfo . request ) ) ) ; } batchRequest . setContent ( batchContent ) ; HttpResponse response = batchRequest . execute ( ) ; BatchUnparsedResponse batchResponse ; try { String boundary = "--" + response . getMediaType ( ) . getParameter ( "boundary" ) ; InputStream contentStream = response . getContent ( ) ; batchResponse = new BatchUnparsedResponse ( contentStream , boundary , requestInfos , retryAllowed ) ; while ( batchResponse . hasNext ) { batchResponse . parseNextResponse ( ) ; } } finally { response . disconnect ( ) ; } List < RequestInfo < ? , ? > > unsuccessfulRequestInfos = batchResponse . unsuccessfulRequestInfos ; if ( ! unsuccessfulRequestInfos . isEmpty ( ) ) { requestInfos = unsuccessfulRequestInfos ; } else { break ; } retriesRemaining -- ; } while ( retryAllowed ) ; requestInfos . clear ( ) ; } | Executes all queued HTTP requests in a single call parses the responses and invokes callbacks . |
35,925 | public final List < PublicKey > getPublicKeys ( ) throws GeneralSecurityException , IOException { lock . lock ( ) ; try { if ( publicKeys == null || clock . currentTimeMillis ( ) + REFRESH_SKEW_MILLIS > expirationTimeMilliseconds ) { refresh ( ) ; } return publicKeys ; } finally { lock . unlock ( ) ; } } | Returns an unmodifiable view of the public keys . |
35,926 | long getCacheTimeInSec ( HttpHeaders httpHeaders ) { long cacheTimeInSec = 0 ; if ( httpHeaders . getCacheControl ( ) != null ) { for ( String arg : httpHeaders . getCacheControl ( ) . split ( "," ) ) { Matcher m = MAX_AGE_PATTERN . matcher ( arg ) ; if ( m . matches ( ) ) { cacheTimeInSec = Long . parseLong ( m . group ( 1 ) ) ; break ; } } } if ( httpHeaders . getAge ( ) != null ) { cacheTimeInSec -= httpHeaders . getAge ( ) ; } return Math . max ( 0 , cacheTimeInSec ) ; } | Gets the cache time in seconds . max - age in Cache - Control header and Age header are considered . |
35,927 | public StoredChannel store ( DataStore < StoredChannel > dataStore ) throws IOException { lock . lock ( ) ; try { dataStore . set ( getId ( ) , this ) ; return this ; } finally { lock . unlock ( ) ; } } | Stores this notification channel in the given notification channel data store . |
35,928 | protected final void initializeMediaUpload ( AbstractInputStreamContent mediaContent ) { HttpRequestFactory requestFactory = abstractGoogleClient . getRequestFactory ( ) ; this . uploader = new MediaHttpUploader ( mediaContent , requestFactory . getTransport ( ) , requestFactory . getInitializer ( ) ) ; this . uploader . setInitiationRequestMethod ( requestMethod ) ; if ( httpContent != null ) { this . uploader . setMetadata ( httpContent ) ; } } | Initializes the media HTTP uploader based on the media content . |
35,929 | protected final void initializeMediaDownload ( ) { HttpRequestFactory requestFactory = abstractGoogleClient . getRequestFactory ( ) ; this . downloader = new MediaHttpDownloader ( requestFactory . getTransport ( ) , requestFactory . getInitializer ( ) ) ; } | Initializes the media HTTP downloader . |
35,930 | private HttpRequest buildHttpRequest ( boolean usingHead ) throws IOException { Preconditions . checkArgument ( uploader == null ) ; Preconditions . checkArgument ( ! usingHead || requestMethod . equals ( HttpMethods . GET ) ) ; String requestMethodToUse = usingHead ? HttpMethods . HEAD : requestMethod ; final HttpRequest httpRequest = getAbstractGoogleClient ( ) . getRequestFactory ( ) . buildRequest ( requestMethodToUse , buildHttpRequestUrl ( ) , httpContent ) ; new MethodOverride ( ) . intercept ( httpRequest ) ; httpRequest . setParser ( getAbstractGoogleClient ( ) . getObjectParser ( ) ) ; if ( httpContent == null && ( requestMethod . equals ( HttpMethods . POST ) || requestMethod . equals ( HttpMethods . PUT ) || requestMethod . equals ( HttpMethods . PATCH ) ) ) { httpRequest . setContent ( new EmptyContent ( ) ) ; } httpRequest . getHeaders ( ) . putAll ( requestHeaders ) ; if ( ! disableGZipContent ) { httpRequest . setEncoding ( new GZipEncoding ( ) ) ; } final HttpResponseInterceptor responseInterceptor = httpRequest . getResponseInterceptor ( ) ; httpRequest . setResponseInterceptor ( new HttpResponseInterceptor ( ) { public void interceptResponse ( HttpResponse response ) throws IOException { if ( responseInterceptor != null ) { responseInterceptor . interceptResponse ( response ) ; } if ( ! response . isSuccessStatusCode ( ) && httpRequest . getThrowExceptionOnExecuteError ( ) ) { throw newExceptionOnError ( response ) ; } } } ) ; return httpRequest ; } | Create a request suitable for use against this service . |
35,931 | public final < E > void queue ( BatchRequest batchRequest , Class < E > errorClass , BatchCallback < T , E > callback ) throws IOException { Preconditions . checkArgument ( uploader == null , "Batching media requests is not supported" ) ; batchRequest . queue ( buildHttpRequest ( ) , getResponseClass ( ) , errorClass , callback ) ; } | Queues the request into the specified batch request container using the specified error class . |
35,932 | @ SuppressWarnings ( "unchecked" ) public AbstractGoogleClientRequest < T > set ( String fieldName , Object value ) { return ( AbstractGoogleClientRequest < T > ) super . set ( fieldName , value ) ; } | for more details |
35,933 | public static GoogleJsonError parse ( JsonFactory jsonFactory , HttpResponse response ) throws IOException { JsonObjectParser jsonObjectParser = new JsonObjectParser . Builder ( jsonFactory ) . setWrapperKeys ( Collections . singleton ( "error" ) ) . build ( ) ; return jsonObjectParser . parseAndClose ( response . getContent ( ) , response . getContentCharset ( ) , GoogleJsonError . class ) ; } | Parses the given error HTTP response using the given JSON factory . |
35,934 | public void initialize ( AbstractGoogleClientRequest < ? > request ) throws IOException { if ( key != null ) { request . put ( "key" , key ) ; } if ( userIp != null ) { request . put ( "userIp" , userIp ) ; } } | Subclasses should call super implementation in order to set the key and userIp . |
35,935 | public void setEntryClasses ( Class < ? > ... entryClasses ) { int numEntries = entryClasses . length ; HashMap < String , Class < ? > > kindToEntryClassMap = this . kindToEntryClassMap ; for ( int i = 0 ; i < numEntries ; i ++ ) { Class < ? > entryClass = entryClasses [ i ] ; ClassInfo typeInfo = ClassInfo . of ( entryClass ) ; Field field = typeInfo . getField ( "@gd:kind" ) ; if ( field == null ) { throw new IllegalArgumentException ( "missing @gd:kind field for " + entryClass . getName ( ) ) ; } Object entry = Types . newInstance ( entryClass ) ; String kind = ( String ) FieldInfo . getFieldValue ( field , entry ) ; if ( kind == null ) { throw new IllegalArgumentException ( "missing value for @gd:kind field in " + entryClass . getName ( ) ) ; } kindToEntryClassMap . put ( kind , entryClass ) ; } } | Sets the entry classes to use when parsing . |
35,936 | public static < T , E > MultiKindFeedParser < T > create ( HttpResponse response , XmlNamespaceDictionary namespaceDictionary , Class < T > feedClass , Class < E > ... entryClasses ) throws IOException , XmlPullParserException { InputStream content = response . getContent ( ) ; try { Atom . checkContentType ( response . getContentType ( ) ) ; XmlPullParser parser = Xml . createParser ( ) ; parser . setInput ( content , null ) ; MultiKindFeedParser < T > result = new MultiKindFeedParser < T > ( namespaceDictionary , parser , content , feedClass ) ; result . setEntryClasses ( entryClasses ) ; return result ; } finally { content . close ( ) ; } } | Parses the given HTTP response using the given feed class and entry classes . |
35,937 | protected TransactionTypeEnum getType ( byte logstate ) { switch ( ( logstate & 0x60 ) >> 5 ) { case 0 : return TransactionTypeEnum . LOADED ; case 1 : return TransactionTypeEnum . UNLOADED ; case 2 : return TransactionTypeEnum . PURCHASE ; case 3 : return TransactionTypeEnum . REFUND ; } return null ; } | Method used to get the transaction type |
35,938 | protected void extractEF_ID ( final Application pApplication ) throws CommunicationException { byte [ ] data = template . get ( ) . getProvider ( ) . transceive ( new CommandApdu ( CommandEnum . READ_RECORD , 0x01 , 0xBC , 0 ) . toBytes ( ) ) ; if ( ResponseUtils . isSucceed ( data ) ) { pApplication . setReadingStep ( ApplicationStepEnum . READ ) ; SimpleDateFormat format = new SimpleDateFormat ( "MM/yy" , Locale . getDefault ( ) ) ; EmvTrack2 track2 = new EmvTrack2 ( ) ; track2 . setCardNumber ( BytesUtils . bytesToStringNoSpace ( Arrays . copyOfRange ( data , 4 , 9 ) ) ) ; try { track2 . setExpireDate ( format . parse ( String . format ( "%02x/%02x" , data [ 11 ] , data [ 10 ] ) ) ) ; } catch ( ParseException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } template . get ( ) . getCard ( ) . setTrack2 ( track2 ) ; } } | Method used to extract Ef_iD record |
35,939 | private Collection < AnnotationData > getAnnotationSet ( final Collection < TagAndLength > pTags ) { Collection < AnnotationData > ret = null ; if ( pTags != null ) { Map < ITag , AnnotationData > data = AnnotationUtils . getInstance ( ) . getMap ( ) . get ( getClass ( ) . getName ( ) ) ; ret = new ArrayList < AnnotationData > ( data . size ( ) ) ; for ( TagAndLength tal : pTags ) { AnnotationData ann = data . get ( tal . getTag ( ) ) ; if ( ann != null ) { ann . setSize ( tal . getLength ( ) * BitUtils . BYTE_SIZE ) ; } else { ann = new AnnotationData ( ) ; ann . setSkip ( true ) ; ann . setSize ( tal . getLength ( ) * BitUtils . BYTE_SIZE ) ; } ret . add ( ann ) ; } } else { ret = AnnotationUtils . getInstance ( ) . getMapSet ( ) . get ( getClass ( ) . getName ( ) ) ; } return ret ; } | Method to get the annotation set from the current class |
35,940 | public void parse ( final byte [ ] pData , final Collection < TagAndLength > pTags ) { Collection < AnnotationData > set = getAnnotationSet ( pTags ) ; BitUtils bit = new BitUtils ( pData ) ; Iterator < AnnotationData > it = set . iterator ( ) ; while ( it . hasNext ( ) ) { AnnotationData data = it . next ( ) ; if ( data . isSkip ( ) ) { bit . addCurrentBitIndex ( data . getSize ( ) ) ; } else { Object obj = DataFactory . getObject ( data , bit ) ; setField ( data . getField ( ) , this , obj ) ; } } } | Method to parse byte data |
35,941 | protected void setField ( final Field field , final IFile pData , final Object pValue ) { if ( field != null ) { try { field . set ( pData , pValue ) ; } catch ( IllegalArgumentException e ) { LOGGER . error ( "Parameters of fied.set are not valid" , e ) ; } catch ( IllegalAccessException e ) { LOGGER . error ( "Impossible to set the Field :" + field . getName ( ) , e ) ; } } } | Method used to set the value of a field |
35,942 | public static final Collection < String > getDescription ( final String pAtr ) { Collection < String > ret = null ; if ( StringUtils . isNotBlank ( pAtr ) ) { String val = StringUtils . deleteWhitespace ( pAtr ) . toUpperCase ( ) ; for ( String key : MAP . keySet ( ) ) { if ( val . matches ( "^" + key + "$" ) ) { ret = ( Collection < String > ) MAP . get ( key ) ; break ; } } } return ret ; } | Method used to find description from ATR |
35,943 | public static EmvTrack2 extractTrack2EquivalentData ( final byte [ ] pRawTrack2 ) { EmvTrack2 ret = null ; if ( pRawTrack2 != null ) { EmvTrack2 track2 = new EmvTrack2 ( ) ; track2 . setRaw ( pRawTrack2 ) ; String data = BytesUtils . bytesToStringNoSpace ( pRawTrack2 ) ; Matcher m = TRACK2_EQUIVALENT_PATTERN . matcher ( data ) ; if ( m . find ( ) ) { track2 . setCardNumber ( m . group ( 1 ) ) ; SimpleDateFormat sdf = new SimpleDateFormat ( "yyMM" , Locale . getDefault ( ) ) ; try { track2 . setExpireDate ( DateUtils . truncate ( sdf . parse ( m . group ( 2 ) ) , Calendar . MONTH ) ) ; } catch ( ParseException e ) { LOGGER . error ( "Unparsable expire card date : {}" , e . getMessage ( ) ) ; return ret ; } track2 . setService ( new Service ( m . group ( 3 ) ) ) ; ret = track2 ; } } return ret ; } | Extract track 2 Equivalent data |
35,944 | public static EmvTrack1 extractTrack1Data ( final byte [ ] pRawTrack1 ) { EmvTrack1 ret = null ; if ( pRawTrack1 != null ) { EmvTrack1 track1 = new EmvTrack1 ( ) ; track1 . setRaw ( pRawTrack1 ) ; Matcher m = TRACK1_PATTERN . matcher ( new String ( pRawTrack1 ) ) ; if ( m . find ( ) ) { track1 . setFormatCode ( m . group ( 1 ) ) ; track1 . setCardNumber ( m . group ( 2 ) ) ; String [ ] name = StringUtils . split ( m . group ( 4 ) . trim ( ) , CARD_HOLDER_NAME_SEPARATOR ) ; if ( name != null && name . length == 2 ) { track1 . setHolderLastname ( StringUtils . trimToNull ( name [ 0 ] ) ) ; track1 . setHolderFirstname ( StringUtils . trimToNull ( name [ 1 ] ) ) ; } SimpleDateFormat sdf = new SimpleDateFormat ( "yyMM" , Locale . getDefault ( ) ) ; try { track1 . setExpireDate ( DateUtils . truncate ( sdf . parse ( m . group ( 5 ) ) , Calendar . MONTH ) ) ; } catch ( ParseException e ) { LOGGER . error ( "Unparsable expire card date : {}" , e . getMessage ( ) ) ; return ret ; } track1 . setService ( new Service ( m . group ( 6 ) ) ) ; ret = track1 ; } } return ret ; } | Extract track 1 data |
35,945 | public void initFromAnnotation ( final Data pData ) { dateStandard = pData . dateStandard ( ) ; format = pData . format ( ) ; index = pData . index ( ) ; readHexa = pData . readHexa ( ) ; size = pData . size ( ) ; if ( pData . tag ( ) != null ) { tag = EmvTags . find ( BytesUtils . fromString ( pData . tag ( ) ) ) ; } } | Initialization from annotation |
35,946 | public static CPLC parse ( byte [ ] raw ) { CPLC ret = null ; if ( raw != null ) { byte [ ] cplc = null ; if ( raw . length == CPLC . SIZE + 2 ) { cplc = raw ; } else if ( raw . length == CPLC . SIZE + 5 ) { cplc = TlvUtil . getValue ( raw , CPLC_TAG ) ; } else { LOGGER . error ( "CPLC data not valid" ) ; return null ; } ret = new CPLC ( ) ; ret . parse ( cplc , null ) ; } return ret ; } | Method used to parse and extract CPLC data |
35,947 | public static boolean contains ( final byte [ ] pByte , final SwEnum ... pEnum ) { SwEnum val = SwEnum . getSW ( pByte ) ; if ( LOGGER . isDebugEnabled ( ) && pByte != null ) { LOGGER . debug ( "Response Status <" + BytesUtils . bytesToStringNoSpace ( Arrays . copyOfRange ( pByte , Math . max ( pByte . length - 2 , 0 ) , pByte . length ) ) + "> : " + ( val != null ? val . getDetail ( ) : "Unknow" ) ) ; } return val != null && ArrayUtils . contains ( pEnum , val ) ; } | Method used to check equality with the last command return SW1SW2 == pEnum |
35,948 | protected boolean extractPublicData ( final Application pApplication ) throws CommunicationException { boolean ret = false ; byte [ ] data = selectAID ( pApplication . getAid ( ) ) ; if ( ResponseUtils . contains ( data , SwEnum . SW_9000 , SwEnum . SW_6285 ) ) { pApplication . setReadingStep ( ApplicationStepEnum . SELECTED ) ; ret = parse ( data , pApplication ) ; if ( ret ) { String aid = BytesUtils . bytesToStringNoSpace ( TlvUtil . getValue ( data , EmvTags . DEDICATED_FILE_NAME ) ) ; String applicationLabel = extractApplicationLabel ( data ) ; if ( applicationLabel == null ) { applicationLabel = pApplication . getApplicationLabel ( ) ; } if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Application label:" + applicationLabel + " with Aid:" + aid ) ; } template . get ( ) . getCard ( ) . setType ( findCardScheme ( aid , template . get ( ) . getCard ( ) . getCardNumber ( ) ) ) ; pApplication . setAid ( BytesUtils . fromString ( aid ) ) ; pApplication . setApplicationLabel ( applicationLabel ) ; pApplication . setLeftPinTry ( getLeftPinTry ( ) ) ; pApplication . setTransactionCounter ( getTransactionCounter ( ) ) ; template . get ( ) . getCard ( ) . setState ( CardStateEnum . ACTIVE ) ; } } return ret ; } | Read public card data from parameter AID |
35,949 | protected EmvCardScheme findCardScheme ( final String pAid , final String pCardNumber ) { EmvCardScheme type = EmvCardScheme . getCardTypeByAid ( pAid ) ; if ( type == EmvCardScheme . CB ) { type = EmvCardScheme . getCardTypeByCardNumber ( pCardNumber ) ; if ( type != null ) { LOGGER . debug ( "Real type:" + type . getName ( ) ) ; } } return type ; } | Method used to find the real card scheme |
35,950 | protected boolean parse ( final byte [ ] pSelectResponse , final Application pApplication ) throws CommunicationException { boolean ret = false ; byte [ ] logEntry = getLogEntry ( pSelectResponse ) ; byte [ ] pdol = TlvUtil . getValue ( pSelectResponse , EmvTags . PDOL ) ; byte [ ] gpo = getGetProcessingOptions ( pdol ) ; extractBankData ( pSelectResponse ) ; if ( ! ResponseUtils . isSucceed ( gpo ) ) { if ( pdol != null ) { gpo = getGetProcessingOptions ( null ) ; } if ( pdol == null || ! ResponseUtils . isSucceed ( gpo ) ) { gpo = template . get ( ) . getProvider ( ) . transceive ( new CommandApdu ( CommandEnum . READ_RECORD , 1 , 0x0C , 0 ) . toBytes ( ) ) ; if ( ! ResponseUtils . isSucceed ( gpo ) ) { return false ; } } } pApplication . setReadingStep ( ApplicationStepEnum . READ ) ; if ( extractCommonsCardData ( gpo ) ) { pApplication . setListTransactions ( extractLogEntry ( logEntry ) ) ; ret = true ; } return ret ; } | Method used to parse EMV card |
35,951 | protected boolean extractCommonsCardData ( final byte [ ] pGpo ) throws CommunicationException { boolean ret = false ; byte data [ ] = TlvUtil . getValue ( pGpo , EmvTags . RESPONSE_MESSAGE_TEMPLATE_1 ) ; if ( data != null ) { data = ArrayUtils . subarray ( data , 2 , data . length ) ; } else { ret = extractTrackData ( template . get ( ) . getCard ( ) , pGpo ) ; if ( ! ret ) { data = TlvUtil . getValue ( pGpo , EmvTags . APPLICATION_FILE_LOCATOR ) ; } else { extractCardHolderName ( pGpo ) ; } } if ( data != null ) { List < Afl > listAfl = extractAfl ( data ) ; for ( Afl afl : listAfl ) { for ( int index = afl . getFirstRecord ( ) ; index <= afl . getLastRecord ( ) ; index ++ ) { byte [ ] info = template . get ( ) . getProvider ( ) . transceive ( new CommandApdu ( CommandEnum . READ_RECORD , index , afl . getSfi ( ) << 3 | 4 , 0 ) . toBytes ( ) ) ; if ( ResponseUtils . isSucceed ( info ) ) { extractCardHolderName ( info ) ; if ( extractTrackData ( template . get ( ) . getCard ( ) , info ) ) { return true ; } } } } } return ret ; } | Method used to extract commons card data |
35,952 | protected List < Afl > extractAfl ( final byte [ ] pAfl ) { List < Afl > list = new ArrayList < Afl > ( ) ; ByteArrayInputStream bai = new ByteArrayInputStream ( pAfl ) ; while ( bai . available ( ) >= 4 ) { Afl afl = new Afl ( ) ; afl . setSfi ( bai . read ( ) >> 3 ) ; afl . setFirstRecord ( bai . read ( ) ) ; afl . setLastRecord ( bai . read ( ) ) ; afl . setOfflineAuthentication ( bai . read ( ) == 1 ) ; list . add ( afl ) ; } return list ; } | Extract list of application file locator from Afl response |
35,953 | protected byte [ ] getGetProcessingOptions ( final byte [ ] pPdol ) throws CommunicationException { List < TagAndLength > list = TlvUtil . parseTagAndLength ( pPdol ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; try { out . write ( EmvTags . COMMAND_TEMPLATE . getTagBytes ( ) ) ; out . write ( TlvUtil . getLength ( list ) ) ; if ( list != null ) { for ( TagAndLength tl : list ) { out . write ( template . get ( ) . getTerminal ( ) . constructValue ( tl ) ) ; } } } catch ( IOException ioe ) { LOGGER . error ( "Construct GPO Command:" + ioe . getMessage ( ) , ioe ) ; } return template . get ( ) . getProvider ( ) . transceive ( new CommandApdu ( CommandEnum . GPO , out . toByteArray ( ) , 0 ) . toBytes ( ) ) ; } | Method used to create GPO command and execute it |
35,954 | protected boolean extractTrackData ( final EmvCard pEmvCard , final byte [ ] pData ) { template . get ( ) . getCard ( ) . setTrack1 ( TrackUtils . extractTrack1Data ( TlvUtil . getValue ( pData , EmvTags . TRACK1_DATA ) ) ) ; template . get ( ) . getCard ( ) . setTrack2 ( TrackUtils . extractTrack2EquivalentData ( TlvUtil . getValue ( pData , EmvTags . TRACK_2_EQV_DATA , EmvTags . TRACK2_DATA ) ) ) ; return pEmvCard . getTrack1 ( ) != null || pEmvCard . getTrack2 ( ) != null ; } | Method used to extract track data from response |
35,955 | private void extractAnnotation ( ) { for ( Class < ? extends IFile > clazz : LISTE_CLASS ) { Map < ITag , AnnotationData > maps = new HashMap < ITag , AnnotationData > ( ) ; Set < AnnotationData > set = new TreeSet < AnnotationData > ( ) ; Field [ ] fields = clazz . getDeclaredFields ( ) ; for ( Field field : fields ) { AnnotationData param = new AnnotationData ( ) ; field . setAccessible ( true ) ; param . setField ( field ) ; Data annotation = field . getAnnotation ( Data . class ) ; if ( annotation != null ) { param . initFromAnnotation ( annotation ) ; maps . put ( param . getTag ( ) , param ) ; try { set . add ( ( AnnotationData ) param . clone ( ) ) ; } catch ( CloneNotSupportedException e ) { } } } mapSet . put ( clazz . getName ( ) , set ) ; map . put ( clazz . getName ( ) , maps ) ; } } | Method to extract all annotation information and store them in the map |
35,956 | public String getHolderLastname ( ) { String ret = holderLastname ; if ( ret == null && track1 != null ) { ret = track1 . getHolderLastname ( ) ; } return ret ; } | Method used to get the field holderLastname |
35,957 | public String getHolderFirstname ( ) { String ret = holderFirstname ; if ( ret == null && track1 != null ) { ret = track1 . getHolderFirstname ( ) ; } return ret ; } | Method used to get the field holderFirstname |
35,958 | public String getCardNumber ( ) { String ret = null ; if ( track2 != null ) { ret = track2 . getCardNumber ( ) ; } if ( ret == null && track1 != null ) { ret = track1 . getCardNumber ( ) ; } return ret ; } | Method used to get the field cardNumber |
35,959 | public Date getExpireDate ( ) { Date ret = null ; if ( track2 != null ) { ret = track2 . getExpireDate ( ) ; } if ( ret == null && track1 != null ) { ret = track1 . getExpireDate ( ) ; } return ret ; } | Method used to get the field expireDate |
35,960 | private static String getTagValueAsString ( final ITag tag , final byte [ ] value ) { StringBuilder buf = new StringBuilder ( ) ; switch ( tag . getTagValueType ( ) ) { case TEXT : buf . append ( "=" ) ; buf . append ( new String ( value ) ) ; break ; case NUMERIC : buf . append ( "NUMERIC" ) ; break ; case BINARY : buf . append ( "BINARY" ) ; break ; case MIXED : buf . append ( "=" ) ; buf . append ( getSafePrintChars ( value ) ) ; break ; case DOL : buf . append ( "" ) ; break ; default : break ; } return buf . toString ( ) ; } | Method used get Tag value as String |
35,961 | public static List < TagAndLength > parseTagAndLength ( final byte [ ] data ) { List < TagAndLength > tagAndLengthList = new ArrayList < TagAndLength > ( ) ; if ( data != null ) { TLVInputStream stream = new TLVInputStream ( new ByteArrayInputStream ( data ) ) ; try { while ( stream . available ( ) > 0 ) { if ( stream . available ( ) < 2 ) { throw new TlvException ( "Data length < 2 : " + stream . available ( ) ) ; } ITag tag = searchTagById ( stream . readTag ( ) ) ; int tagValueLength = stream . readLength ( ) ; tagAndLengthList . add ( new TagAndLength ( tag , tagValueLength ) ) ; } } catch ( IOException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } finally { IOUtils . closeQuietly ( stream ) ; } } return tagAndLengthList ; } | Method used to parser Tag and length |
35,962 | public static List < TLV > getlistTLV ( final byte [ ] pData , final ITag ... pTag ) { List < TLV > list = new ArrayList < TLV > ( ) ; TLVInputStream stream = new TLVInputStream ( new ByteArrayInputStream ( pData ) ) ; try { while ( stream . available ( ) > 0 ) { TLV tlv = TlvUtil . getNextTLV ( stream ) ; if ( tlv == null ) { break ; } if ( ArrayUtils . contains ( pTag , tlv . getTag ( ) ) ) { list . add ( tlv ) ; } else if ( tlv . getTag ( ) . isConstructed ( ) ) { list . addAll ( TlvUtil . getlistTLV ( tlv . getValueBytes ( ) , pTag ) ) ; } } } catch ( IOException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } finally { IOUtils . closeQuietly ( stream ) ; } return list ; } | Method used to get the list of TLV corresponding to tags specified in parameters |
35,963 | public static byte [ ] getValue ( final byte [ ] pData , final ITag ... pTag ) { byte [ ] ret = null ; if ( pData != null ) { TLVInputStream stream = new TLVInputStream ( new ByteArrayInputStream ( pData ) ) ; try { while ( stream . available ( ) > 0 ) { TLV tlv = TlvUtil . getNextTLV ( stream ) ; if ( tlv == null ) { break ; } if ( ArrayUtils . contains ( pTag , tlv . getTag ( ) ) ) { return tlv . getValueBytes ( ) ; } else if ( tlv . getTag ( ) . isConstructed ( ) ) { ret = TlvUtil . getValue ( tlv . getValueBytes ( ) , pTag ) ; if ( ret != null ) { break ; } } } } catch ( IOException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } finally { IOUtils . closeQuietly ( stream ) ; } } return ret ; } | Method used to get Tag value |
35,964 | public static int getLength ( final List < TagAndLength > pList ) { int ret = 0 ; if ( pList != null ) { for ( TagAndLength tl : pList ) { ret += tl . getLength ( ) ; } } return ret ; } | Method used to get length of all Tags |
35,965 | private void addDefaultParsers ( ) { parsers = new ArrayList < IParser > ( ) ; parsers . add ( new GeldKarteParser ( this ) ) ; parsers . add ( new EmvParser ( this ) ) ; } | Add default parser implementation |
35,966 | public EmvTemplate addParsers ( final IParser ... pParsers ) { if ( pParsers != null ) { for ( IParser parser : pParsers ) { parsers . add ( 0 , parser ) ; } } return this ; } | Method used to add a list of parser to the current EMV template |
35,967 | public EmvCard readEmvCard ( ) throws CommunicationException { if ( config . readCplc ) { readCPLCInfos ( ) ; } if ( config . readAt ) { card . setAt ( BytesUtils . bytesToStringNoSpace ( provider . getAt ( ) ) ) ; card . setAtrDescription ( config . contactLess ? AtrUtils . getDescriptionFromAts ( card . getAt ( ) ) : AtrUtils . getDescription ( card . getAt ( ) ) ) ; } if ( ! readWithPSE ( ) ) { readWithAID ( ) ; } return card ; } | Method used to read public data from EMV card |
35,968 | protected boolean readWithPSE ( ) throws CommunicationException { boolean ret = false ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Try to read card with Payment System Environment" ) ; } byte [ ] data = selectPaymentEnvironment ( ) ; if ( ResponseUtils . isSucceed ( data ) ) { card . getApplications ( ) . addAll ( parseFCIProprietaryTemplate ( data ) ) ; Collections . sort ( card . getApplications ( ) ) ; for ( Application app : card . getApplications ( ) ) { boolean status = false ; String applicationAid = BytesUtils . bytesToStringNoSpace ( app . getAid ( ) ) ; for ( IParser impl : parsers ) { if ( impl . getId ( ) != null && impl . getId ( ) . matcher ( applicationAid ) . matches ( ) ) { status = impl . parse ( app ) ; break ; } } if ( ! ret && status ) { ret = status ; if ( ! config . readAllAids ) { break ; } } } if ( ! ret ) { card . setState ( CardStateEnum . LOCKED ) ; } } else if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( ( config . contactLess ? "PPSE" : "PSE" ) + " not found -> Use kown AID" ) ; } return ret ; } | Read EMV card with Payment System Environment or Proximity Payment System Environment |
35,969 | protected List < Application > parseFCIProprietaryTemplate ( final byte [ ] pData ) throws CommunicationException { List < Application > ret = new ArrayList < Application > ( ) ; byte [ ] data = TlvUtil . getValue ( pData , EmvTags . SFI ) ; if ( data != null ) { int sfi = BytesUtils . byteArrayToInt ( data ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "SFI found:" + sfi ) ; } for ( int rec = 0 ; rec < MAX_RECORD_SFI ; rec ++ ) { data = provider . transceive ( new CommandApdu ( CommandEnum . READ_RECORD , rec , sfi << 3 | 4 , 0 ) . toBytes ( ) ) ; if ( ResponseUtils . isSucceed ( data ) ) { ret . addAll ( getApplicationTemplate ( data ) ) ; } else { break ; } } } else { ret . addAll ( getApplicationTemplate ( pData ) ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "(FCI) Issuer Discretionary Data is already present" ) ; } } return ret ; } | Method used to parse FCI Proprietary Template |
35,970 | protected void readWithAID ( ) throws CommunicationException { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Try to read card with AID" ) ; } Application app = new Application ( ) ; for ( EmvCardScheme type : EmvCardScheme . values ( ) ) { for ( byte [ ] aid : type . getAidByte ( ) ) { app . setAid ( aid ) ; app . setApplicationLabel ( type . getName ( ) ) ; String applicationAid = BytesUtils . bytesToStringNoSpace ( aid ) ; for ( IParser impl : parsers ) { if ( impl . getId ( ) != null && impl . getId ( ) . matcher ( applicationAid ) . matches ( ) && impl . parse ( app ) ) { card . getApplications ( ) . clear ( ) ; card . getApplications ( ) . add ( app ) ; return ; } } } } } | Read EMV card with AID |
35,971 | protected byte [ ] selectPaymentEnvironment ( ) throws CommunicationException { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Select " + ( config . contactLess ? "PPSE" : "PSE" ) + " Application" ) ; } return provider . transceive ( new CommandApdu ( CommandEnum . SELECT , config . contactLess ? PPSE : PSE , 0 ) . toBytes ( ) ) ; } | Method used to select payment environment PSE or PPSE |
35,972 | protected byte [ ] selectAID ( final byte [ ] pAid ) throws CommunicationException { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Select AID: " + BytesUtils . bytesToString ( pAid ) ) ; } return template . get ( ) . getProvider ( ) . transceive ( new CommandApdu ( CommandEnum . SELECT , pAid , 0 ) . toBytes ( ) ) ; } | Select application with AID or RID |
35,973 | protected String extractApplicationLabel ( final byte [ ] pData ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Extract Application label" ) ; } String label = null ; byte [ ] labelByte = TlvUtil . getValue ( pData , EmvTags . APPLICATION_PREFERRED_NAME ) ; if ( labelByte == null ) { labelByte = TlvUtil . getValue ( pData , EmvTags . APPLICATION_LABEL ) ; } if ( labelByte != null ) { label = new String ( labelByte ) ; } return label ; } | Method used to extract application label |
35,974 | protected void extractCardHolderName ( final byte [ ] pData ) { byte [ ] cardHolderByte = TlvUtil . getValue ( pData , EmvTags . CARDHOLDER_NAME ) ; if ( cardHolderByte != null ) { String [ ] name = StringUtils . split ( new String ( cardHolderByte ) . trim ( ) , TrackUtils . CARD_HOLDER_NAME_SEPARATOR ) ; if ( name != null && name . length > 0 ) { template . get ( ) . getCard ( ) . setHolderLastname ( StringUtils . trimToNull ( name [ 0 ] ) ) ; if ( name . length == 2 ) { template . get ( ) . getCard ( ) . setHolderFirstname ( StringUtils . trimToNull ( name [ 1 ] ) ) ; } } } } | Extract card holder lastname and firstname |
35,975 | protected int getTransactionCounter ( ) throws CommunicationException { int ret = UNKNOW ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Get Transaction Counter ATC" ) ; } byte [ ] data = template . get ( ) . getProvider ( ) . transceive ( new CommandApdu ( CommandEnum . GET_DATA , 0x9F , 0x36 , 0 ) . toBytes ( ) ) ; if ( ResponseUtils . isSucceed ( data ) ) { byte [ ] val = TlvUtil . getValue ( data , EmvTags . APP_TRANSACTION_COUNTER ) ; if ( val != null ) { ret = BytesUtils . byteArrayToInt ( val ) ; } } return ret ; } | Method used to get Transaction counter |
35,976 | protected List < TagAndLength > getLogFormat ( ) throws CommunicationException { List < TagAndLength > ret = new ArrayList < TagAndLength > ( ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "GET log format" ) ; } byte [ ] data = template . get ( ) . getProvider ( ) . transceive ( new CommandApdu ( CommandEnum . GET_DATA , 0x9F , 0x4F , 0 ) . toBytes ( ) ) ; if ( ResponseUtils . isSucceed ( data ) ) { ret = TlvUtil . parseTagAndLength ( TlvUtil . getValue ( data , EmvTags . LOG_FORMAT ) ) ; } else { LOGGER . warn ( "No Log format found" ) ; } return ret ; } | Method used to get log format |
35,977 | protected List < EmvTransactionRecord > extractLogEntry ( final byte [ ] pLogEntry ) throws CommunicationException { List < EmvTransactionRecord > listRecord = new ArrayList < EmvTransactionRecord > ( ) ; if ( template . get ( ) . getConfig ( ) . readTransactions && pLogEntry != null ) { List < TagAndLength > tals = getLogFormat ( ) ; if ( tals != null && ! tals . isEmpty ( ) ) { for ( int rec = 1 ; rec <= pLogEntry [ 1 ] ; rec ++ ) { byte [ ] response = template . get ( ) . getProvider ( ) . transceive ( new CommandApdu ( CommandEnum . READ_RECORD , rec , pLogEntry [ 0 ] << 3 | 4 , 0 ) . toBytes ( ) ) ; if ( ResponseUtils . isSucceed ( response ) ) { try { EmvTransactionRecord record = new EmvTransactionRecord ( ) ; record . parse ( response , tals ) ; if ( record . getAmount ( ) != null ) { if ( record . getAmount ( ) >= 1500000000 ) { record . setAmount ( record . getAmount ( ) - 1500000000 ) ; } if ( record . getAmount ( ) == null || record . getAmount ( ) <= 1 ) { continue ; } } if ( record != null ) { if ( record . getCurrency ( ) == null ) { record . setCurrency ( CurrencyEnum . XXX ) ; } listRecord . add ( record ) ; } } catch ( Exception e ) { LOGGER . error ( "Error in transaction format: " + e . getMessage ( ) , e ) ; } } else { break ; } } } } return listRecord ; } | Method used to extract log entry from card |
35,978 | private static Date getDate ( final AnnotationData pAnnotation , final BitUtils pBit ) { Date date = null ; if ( pAnnotation . getDateStandard ( ) == BCD_DATE ) { date = pBit . getNextDate ( pAnnotation . getSize ( ) , pAnnotation . getFormat ( ) , true ) ; } else if ( pAnnotation . getDateStandard ( ) == CPCL_DATE ) { date = calculateCplcDate ( pBit . getNextByte ( pAnnotation . getSize ( ) ) ) ; } else { date = pBit . getNextDate ( pAnnotation . getSize ( ) , pAnnotation . getFormat ( ) ) ; } return date ; } | Method to get a date from the bytes array |
35,979 | public static Object getObject ( final AnnotationData pAnnotation , final BitUtils pBit ) { Object obj = null ; Class < ? > clazz = pAnnotation . getField ( ) . getType ( ) ; if ( clazz . equals ( Integer . class ) ) { obj = getInteger ( pAnnotation , pBit ) ; } else if ( clazz . equals ( Float . class ) ) { obj = getFloat ( pAnnotation , pBit ) ; } else if ( clazz . equals ( String . class ) ) { obj = getString ( pAnnotation , pBit ) ; } else if ( clazz . equals ( Date . class ) ) { obj = getDate ( pAnnotation , pBit ) ; } else if ( clazz . isEnum ( ) ) { obj = getEnum ( pAnnotation , pBit ) ; } return obj ; } | Method to read and object from the bytes tab |
35,980 | private static Float getFloat ( final AnnotationData pAnnotation , final BitUtils pBit ) { Float ret = null ; if ( BCD_FORMAT . equals ( pAnnotation . getFormat ( ) ) ) { ret = Float . parseFloat ( pBit . getNextHexaString ( pAnnotation . getSize ( ) ) ) ; } else { ret = ( float ) getInteger ( pAnnotation , pBit ) ; } return ret ; } | Method use to get float |
35,981 | @ SuppressWarnings ( "unchecked" ) private static IKeyEnum getEnum ( final AnnotationData pAnnotation , final BitUtils pBit ) { int val = 0 ; try { val = Integer . parseInt ( pBit . getNextHexaString ( pAnnotation . getSize ( ) ) , pAnnotation . isReadHexa ( ) ? 16 : 10 ) ; } catch ( NumberFormatException nfe ) { } return EnumUtils . getValue ( val , ( Class < ? extends IKeyEnum > ) pAnnotation . getField ( ) . getType ( ) ) ; } | This method is used to get an enum with his key |
35,982 | @ SuppressWarnings ( "unchecked" ) public static < T extends IKeyEnum > T getValue ( final int pKey , final Class < T > pClass ) { for ( IKeyEnum val : pClass . getEnumConstants ( ) ) { if ( val . getKey ( ) == pKey ) { return ( T ) val ; } } LOGGER . error ( "Unknow value:" + pKey + " for Enum:" + pClass . getName ( ) ) ; return null ; } | Get the value of and enum from his key |
35,983 | public static int [ ] getHashBuckets ( String key , int hashCount , int max , boolean applyWidth ) { byte [ ] b ; b = key . getBytes ( StandardCharsets . UTF_8 ) ; return getHashBuckets ( b , hashCount , max , applyWidth ) ; } | than performing further iterations of murmur . |
35,984 | private void status ( final String [ ] args ) throws FileNotFoundException { setWorkingDir ( args ) ; final Path statusFile = this . workingDir . resolve ( this . statusName ) ; readStatus ( true , statusFile ) ; if ( args . length > 2 && args [ 2 ] . equalsIgnoreCase ( "verbose" ) ) { System . out . println ( this . status ) ; } else { System . out . println ( this . status . shortStatus ( ) ) ; } } | Prints the status of the node running in the configured working directory . |
35,985 | public static int computeBestK ( int bucketsPerElement ) { assert bucketsPerElement >= 0 ; if ( bucketsPerElement >= optKPerBuckets . length ) { return optKPerBuckets [ optKPerBuckets . length - 1 ] ; } return optKPerBuckets [ bucketsPerElement ] ; } | Given the number of buckets that can be used per element return the optimal number of hash functions in order to minimize the false positive rate . |
35,986 | public Iterable < JsonObject > convertRecord ( JsonArray outputSchema , String strInputRecord , WorkUnitState workUnit ) throws DataConversionException { JsonParser jsonParser = new JsonParser ( ) ; JsonObject inputRecord = ( JsonObject ) jsonParser . parse ( strInputRecord ) ; if ( ! this . unpackComplexSchemas ) { return new SingleRecordIterable < > ( inputRecord ) ; } JsonSchema schema = new JsonSchema ( outputSchema ) ; JsonObject rec = parse ( inputRecord , schema ) ; return new SingleRecordIterable ( rec ) ; } | Takes in a record with format String and Uses the inputSchema to convert the record to a JsonObject |
35,987 | private JsonElement parseEnumType ( JsonSchema schema , JsonElement value ) throws DataConversionException { if ( schema . getSymbols ( ) . contains ( value ) ) { return value ; } throw new DataConversionException ( "Invalid symbol: " + value . getAsString ( ) + " allowed values: " + schema . getSymbols ( ) . toString ( ) ) ; } | Parses Enum type values |
35,988 | private JsonElement parseJsonArrayType ( JsonSchema schema , JsonElement value ) throws DataConversionException { Type arrayType = schema . getTypeOfArrayItems ( ) ; JsonArray tempArray = new JsonArray ( ) ; if ( Type . isPrimitive ( arrayType ) ) { return value ; } JsonSchema nestedSchema = schema . getItemsWithinDataType ( ) ; for ( JsonElement v : value . getAsJsonArray ( ) ) { tempArray . add ( parse ( v , nestedSchema ) ) ; } return tempArray ; } | Parses JsonArray type values |
35,989 | private JsonElement parseJsonObjectType ( JsonSchema schema , JsonElement value ) throws DataConversionException { JsonSchema valuesWithinDataType = schema . getValuesWithinDataType ( ) ; if ( schema . isType ( MAP ) ) { if ( Type . isPrimitive ( valuesWithinDataType . getType ( ) ) ) { return value ; } JsonObject map = new JsonObject ( ) ; for ( Entry < String , JsonElement > mapEntry : value . getAsJsonObject ( ) . entrySet ( ) ) { JsonElement mapValue = mapEntry . getValue ( ) ; map . add ( mapEntry . getKey ( ) , parse ( mapValue , valuesWithinDataType ) ) ; } return map ; } else if ( schema . isType ( RECORD ) ) { JsonSchema schemaArray = valuesWithinDataType . getValuesWithinDataType ( ) ; return parse ( ( JsonObject ) value , schemaArray ) ; } else { return JsonNull . INSTANCE ; } } | Parses JsonObject type values |
35,990 | private JsonElement parsePrimitiveType ( JsonSchema schema , JsonElement value ) throws DataConversionException { if ( ( schema . isType ( NULL ) || schema . isNullable ( ) ) && value . isJsonNull ( ) ) { return JsonNull . INSTANCE ; } if ( ( schema . isType ( NULL ) && ! value . isJsonNull ( ) ) || ( ! schema . isType ( NULL ) && value . isJsonNull ( ) ) ) { throw new DataConversionException ( "Type mismatch for " + value . toString ( ) + " of type " + schema . getDataTypes ( ) . toString ( ) ) ; } if ( schema . isType ( FIXED ) ) { int expectedSize = schema . getSizeOfFixedData ( ) ; if ( value . getAsString ( ) . length ( ) == expectedSize ) { return value ; } else { throw new DataConversionException ( "Fixed type value is not same as defined value expected fieldsCount: " + expectedSize ) ; } } else { return value ; } } | Parses primitive types |
35,991 | public static boolean isAncestor ( Path possibleAncestor , Path fullPath ) { return ! relativizePath ( fullPath , possibleAncestor ) . equals ( getPathWithoutSchemeAndAuthority ( fullPath ) ) ; } | Checks whether possibleAncestor is an ancestor of fullPath . |
35,992 | public static Path getPathWithoutSchemeAndAuthority ( Path path ) { return new Path ( null , null , path . toUri ( ) . getPath ( ) ) ; } | Removes the Scheme and Authority from a Path . |
35,993 | public static Path getRootPath ( Path path ) { if ( path . isRoot ( ) ) { return path ; } return getRootPath ( path . getParent ( ) ) ; } | Returns the root path for the specified path . |
35,994 | public static Path withoutLeadingSeparator ( Path path ) { return new Path ( StringUtils . removeStart ( path . toString ( ) , Path . SEPARATOR ) ) ; } | Removes the leading slash if present . |
35,995 | public static Path deepestNonGlobPath ( Path input ) { Path commonRoot = input ; while ( commonRoot != null && isGlob ( commonRoot ) ) { commonRoot = commonRoot . getParent ( ) ; } return commonRoot ; } | Finds the deepest ancestor of input that is not a glob . |
35,996 | public static void deleteEmptyParentDirectories ( FileSystem fs , Path limitPath , Path startPath ) throws IOException { if ( PathUtils . isAncestor ( limitPath , startPath ) && ! PathUtils . getPathWithoutSchemeAndAuthority ( limitPath ) . equals ( PathUtils . getPathWithoutSchemeAndAuthority ( startPath ) ) && fs . listStatus ( startPath ) . length == 0 ) { if ( ! fs . delete ( startPath , false ) ) { log . warn ( "Failed to delete empty directory " + startPath ) ; } else { log . info ( "Deleted empty directory " + startPath ) ; } deleteEmptyParentDirectories ( fs , limitPath , startPath . getParent ( ) ) ; } } | Deletes empty directories starting with startPath and all ancestors up to but not including limitPath . |
35,997 | public static Optional < Path > getPersistDir ( State state ) throws IOException { if ( state . contains ( PERSIST_DIR_KEY ) ) { return Optional . of ( new Path ( state . getProp ( PERSIST_DIR_KEY ) , UserGroupInformation . getCurrentUser ( ) . getShortUserName ( ) ) ) ; } return Optional . absent ( ) ; } | Get the persist directory for this job . |
35,998 | public boolean persistFile ( State state , CopyableFile file , Path path ) throws IOException { if ( ! this . persistDir . isPresent ( ) ) { return false ; } String guid = computeGuid ( state , file ) ; Path guidPath = new Path ( this . persistDir . get ( ) , guid ) ; if ( ! this . fs . exists ( guidPath ) ) { this . fs . mkdirs ( guidPath , new FsPermission ( FsAction . ALL , FsAction . READ , FsAction . NONE ) ) ; } Path targetPath = new Path ( guidPath , shortenPathName ( file . getOrigin ( ) . getPath ( ) , 250 - guid . length ( ) ) ) ; log . info ( String . format ( "Persisting file %s with guid %s to location %s." , path , guid , targetPath ) ) ; if ( this . fs . rename ( path , targetPath ) ) { this . fs . setTimes ( targetPath , System . currentTimeMillis ( ) , - 1 ) ; return true ; } return false ; } | Moves a copied path into a persistent location managed by gobblin - distcp . This method is used when an already copied file cannot be successfully published . In future runs instead of re - copying the file distcp will use the persisted file . |
35,999 | static String shortenPathName ( Path path , int bytes ) { String pathString = path . toUri ( ) . getPath ( ) ; String replaced = pathString . replace ( "/" , "_" ) ; if ( replaced . length ( ) <= bytes ) { return replaced ; } int bytesPerHalf = ( bytes - 3 ) / 2 ; return replaced . substring ( 0 , bytesPerHalf ) + "..." + replaced . substring ( replaced . length ( ) - bytesPerHalf ) ; } | Shorten an absolute path into a sanitized String of length at most bytes . This is useful for including a summary of an absolute path in a file name . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.