idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
19,700
public void sendDeliveredNotification ( Jid to , String packetID ) throws NotConnectedException , InterruptedException { Message msg = new Message ( to ) ; MessageEvent messageEvent = new MessageEvent ( ) ; messageEvent . setDelivered ( true ) ; messageEvent . setStanzaId ( packetID ) ; msg . addExtension ( messageEvent ) ; connection ( ) . sendStanza ( msg ) ; }
Sends the notification that the message was delivered to the sender of the original message .
19,701
public void sendDisplayedNotification ( Jid to , String packetID ) throws NotConnectedException , InterruptedException { Message msg = new Message ( to ) ; MessageEvent messageEvent = new MessageEvent ( ) ; messageEvent . setDisplayed ( true ) ; messageEvent . setStanzaId ( packetID ) ; msg . addExtension ( messageEvent ) ; connection ( ) . sendStanza ( msg ) ; }
Sends the notification that the message was displayed to the sender of the original message .
19,702
public void sendComposingNotification ( Jid to , String packetID ) throws NotConnectedException , InterruptedException { Message msg = new Message ( to ) ; MessageEvent messageEvent = new MessageEvent ( ) ; messageEvent . setComposing ( true ) ; messageEvent . setStanzaId ( packetID ) ; msg . addExtension ( messageEvent ) ; connection ( ) . sendStanza ( msg ) ; }
Sends the notification that the receiver of the message is composing a reply .
19,703
public void sendCancelledNotification ( Jid to , String packetID ) throws NotConnectedException , InterruptedException { Message msg = new Message ( to ) ; MessageEvent messageEvent = new MessageEvent ( ) ; messageEvent . setCancelled ( true ) ; messageEvent . setStanzaId ( packetID ) ; msg . addExtension ( messageEvent ) ; connection ( ) . sendStanza ( msg ) ; }
Sends the notification that the receiver of the message has cancelled composing a reply .
19,704
protected static StreamInitiation createInitiationAccept ( StreamInitiation streamInitiationOffer , String [ ] namespaces ) { StreamInitiation response = new StreamInitiation ( ) ; response . setTo ( streamInitiationOffer . getFrom ( ) ) ; response . setFrom ( streamInitiationOffer . getTo ( ) ) ; response . setType ( IQ . Type . result ) ; response . setStanzaId ( streamInitiationOffer . getStanzaId ( ) ) ; DataForm form = new DataForm ( DataForm . Type . submit ) ; FormField field = new FormField ( FileTransferNegotiator . STREAM_DATA_FIELD_NAME ) ; for ( String namespace : namespaces ) { field . addValue ( namespace ) ; } form . addField ( field ) ; response . setFeatureNegotiationForm ( form ) ; return response ; }
Creates the initiation acceptance stanza to forward to the stream initiator .
19,705
public static synchronized AccountManager getInstance ( XMPPConnection connection ) { AccountManager accountManager = INSTANCES . get ( connection ) ; if ( accountManager == null ) { accountManager = new AccountManager ( connection ) ; INSTANCES . put ( connection , accountManager ) ; } return accountManager ; }
Returns the AccountManager instance associated with a given XMPPConnection .
19,706
public boolean supportsAccountCreation ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { if ( accountCreationSupported ) { return true ; } if ( info == null ) { getRegistrationInfo ( ) ; accountCreationSupported = info . getType ( ) != IQ . Type . error ; } return accountCreationSupported ; }
Returns true if the server supports creating new accounts . Many servers require that you not be currently authenticated when creating new accounts so the safest behavior is to only create new accounts before having logged in to a server .
19,707
public void createAccount ( Localpart username , String password ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { Map < String , String > attributes = new HashMap < > ( ) ; for ( String attributeName : getAccountAttributes ( ) ) { attributes . put ( attributeName , "" ) ; } createAccount ( username , password , attributes ) ; }
Creates a new account using the specified username and password . The server may require a number of extra account attributes such as an email address and phone number . In that case Smack will attempt to automatically set all required attributes with blank values which may or may not be accepted by the server . Therefore it s recommended to check the required account attributes and to let the end - user populate them with real values instead .
19,708
public void changePassword ( String newPassword ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { if ( ! connection ( ) . isSecureConnection ( ) && ! allowSensitiveOperationOverInsecureConnection ) { throw new IllegalStateException ( "Changing password over insecure connection." ) ; } Map < String , String > map = new HashMap < > ( ) ; map . put ( "username" , connection ( ) . getUser ( ) . getLocalpart ( ) . toString ( ) ) ; map . put ( "password" , newPassword ) ; Registration reg = new Registration ( map ) ; reg . setType ( IQ . Type . set ) ; reg . setTo ( connection ( ) . getXMPPServiceDomain ( ) ) ; createStanzaCollectorAndSend ( reg ) . nextResultOrThrow ( ) ; }
Changes the password of the currently logged - in account . This operation can only be performed after a successful login operation has been completed . Not all servers support changing passwords ; an XMPPException will be thrown when that is the case .
19,709
public void deleteAccount ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { Map < String , String > attributes = new HashMap < > ( ) ; attributes . put ( "remove" , "" ) ; Registration reg = new Registration ( attributes ) ; reg . setType ( IQ . Type . set ) ; reg . setTo ( connection ( ) . getXMPPServiceDomain ( ) ) ; createStanzaCollectorAndSend ( reg ) . nextResultOrThrow ( ) ; }
Deletes the currently logged - in account from the server . This operation can only be performed after a successful login operation has been completed . Not all servers support deleting accounts ; an XMPPException will be thrown when that is the case .
19,710
private synchronized void maybeSchedulePingServerTask ( int delta ) { maybeStopPingServerTask ( ) ; if ( pingInterval > 0 ) { int nextPingIn = pingInterval - delta ; LOGGER . fine ( "Scheduling ServerPingTask in " + nextPingIn + " seconds (pingInterval=" + pingInterval + ", delta=" + delta + ")" ) ; nextAutomaticPing = schedule ( pingServerRunnable , nextPingIn , TimeUnit . SECONDS ) ; } }
Cancels any existing periodic ping task if there is one and schedules a new ping task if pingInterval is greater then zero .
19,711
static void addDiscoverInfoByNode ( String nodeVer , DiscoverInfo info ) { CAPS_CACHE . put ( nodeVer , info ) ; if ( persistentCache != null ) persistentCache . addDiscoverInfoByNodePersistent ( nodeVer , info ) ; }
Add DiscoverInfo to the database .
19,712
public static DiscoverInfo getDiscoveryInfoByNodeVer ( String nodeVer ) { DiscoverInfo info = CAPS_CACHE . lookup ( nodeVer ) ; if ( info == null && persistentCache != null ) { info = persistentCache . lookup ( nodeVer ) ; if ( info != null ) { CAPS_CACHE . put ( nodeVer , info ) ; } } if ( info != null ) info = new DiscoverInfo ( info ) ; return info ; }
Retrieve DiscoverInfo for a specific node .
19,713
public boolean areEntityCapsSupported ( Jid jid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return sdm . supportsFeature ( jid , NAMESPACE ) ; }
Returns true if Entity Caps are supported by a given JID .
19,714
private void updateLocalEntityCaps ( ) { XMPPConnection connection = connection ( ) ; DiscoverInfo discoverInfo = new DiscoverInfo ( ) ; discoverInfo . setType ( IQ . Type . result ) ; sdm . addDiscoverInfoTo ( discoverInfo ) ; currentCapsVersion = generateVerificationString ( discoverInfo ) ; final String localNodeVer = getLocalNodeVer ( ) ; discoverInfo . setNode ( localNodeVer ) ; addDiscoverInfoByNode ( localNodeVer , discoverInfo ) ; if ( lastLocalCapsVersions . size ( ) > 10 ) { CapsVersionAndHash oldCapsVersion = lastLocalCapsVersions . poll ( ) ; sdm . removeNodeInformationProvider ( entityNode + '#' + oldCapsVersion . version ) ; } lastLocalCapsVersions . add ( currentCapsVersion ) ; if ( connection != null ) JID_TO_NODEVER_CACHE . put ( connection . getUser ( ) , new NodeVerHash ( entityNode , currentCapsVersion ) ) ; final List < Identity > identities = new LinkedList < > ( ServiceDiscoveryManager . getInstanceFor ( connection ) . getIdentities ( ) ) ; sdm . setNodeInformationProvider ( localNodeVer , new AbstractNodeInformationProvider ( ) { List < String > features = sdm . getFeatures ( ) ; List < ExtensionElement > packetExtensions = sdm . getExtendedInfoAsList ( ) ; public List < String > getNodeFeatures ( ) { return features ; } public List < Identity > getNodeIdentities ( ) { return identities ; } public List < ExtensionElement > getNodePacketExtensions ( ) { return packetExtensions ; } } ) ; if ( connection != null && connection . isAuthenticated ( ) && presenceSend != null ) { try { connection . sendStanza ( presenceSend . cloneWithNewId ( ) ) ; } catch ( InterruptedException | NotConnectedException e ) { LOGGER . log ( Level . WARNING , "Could could not update presence with caps info" , e ) ; } } }
Updates the local user Entity Caps information with the data provided
19,715
public static boolean verifyDiscoverInfoVersion ( String ver , String hash , DiscoverInfo info ) { if ( info . containsDuplicateIdentities ( ) ) return false ; if ( info . containsDuplicateFeatures ( ) ) return false ; if ( verifyPacketExtensions ( info ) ) return false ; String calculatedVer = generateVerificationString ( info , hash ) . version ; if ( ! ver . equals ( calculatedVer ) ) return false ; return true ; }
Verify DiscoverInfo and Caps Node as defined in XEP - 0115 5 . 4 Processing Method .
19,716
public HashMap < Integer , byte [ ] > preKeyPublicKeysForBundle ( TreeMap < Integer , T_PreKey > preKeyHashMap ) { HashMap < Integer , byte [ ] > out = new HashMap < > ( ) ; for ( Map . Entry < Integer , T_PreKey > e : preKeyHashMap . entrySet ( ) ) { out . put ( e . getKey ( ) , preKeyForBundle ( e . getValue ( ) ) ) ; } return out ; }
Prepare a whole bunche of preKeys for transport .
19,717
public static int addInBounds ( int value , int added ) { int avail = Integer . MAX_VALUE - value ; if ( avail < added ) { return added - avail ; } else { return value + added ; } }
Add integers modulo MAX_VALUE .
19,718
public void addItems ( Collection < Item > itemsToAdd ) { if ( itemsToAdd == null ) return ; for ( Item i : itemsToAdd ) { addItem ( i ) ; } }
Adds a collection of items to the discovered information . Does nothing if itemsToAdd is null
19,719
public void sendMessage ( Message message ) throws NotConnectedException , InterruptedException { message . setTo ( participant ) ; message . setType ( Message . Type . chat ) ; message . setThread ( threadID ) ; chatManager . sendMessage ( this , message ) ; }
Sends a message to the other chat participant . The thread ID recipient and message type of the message will automatically set to those of this chat .
19,720
public static synchronized CarbonManager getInstanceFor ( XMPPConnection connection ) { CarbonManager carbonManager = INSTANCES . get ( connection ) ; if ( carbonManager == null ) { carbonManager = new CarbonManager ( connection ) ; INSTANCES . put ( connection , carbonManager ) ; } return carbonManager ; }
Obtain the CarbonManager responsible for a connection .
19,721
public synchronized void setCarbonsEnabled ( final boolean new_state ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { if ( enabled_state == new_state ) return ; IQ setIQ = carbonsEnabledIQ ( new_state ) ; connection ( ) . createStanzaCollectorAndSend ( setIQ ) . nextResultOrThrow ( ) ; enabled_state = new_state ; }
Notify server to change the carbons state . This method blocks some time until the server replies to the IQ and returns true on success .
19,722
public static boolean isServiceEnabled ( XMPPConnection connection ) { connection . getXMPPServiceDomain ( ) ; return ServiceDiscoveryManager . getInstanceFor ( connection ) . includesFeature ( AMPExtension . NAMESPACE ) ; }
Returns true if the AMP support is enabled for the given connection .
19,723
public static boolean isActionSupported ( XMPPConnection connection , AMPExtension . Action action ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { String featureName = AMPExtension . NAMESPACE + "?action=" + action . toString ( ) ; return isFeatureSupportedByServer ( connection , featureName ) ; }
Check if server supports specified action .
19,724
public static boolean isConditionSupported ( XMPPConnection connection , String conditionName ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { String featureName = AMPExtension . NAMESPACE + "?condition=" + conditionName ; return isFeatureSupportedByServer ( connection , featureName ) ; }
Check if server supports specified condition .
19,725
private int getTotalCommandBytes ( SubProcessCommandLineArgs commands ) { int size = 0 ; for ( SubProcessCommandLineArgs . Command c : commands . getParameters ( ) ) { size += c . value . length ( ) ; } return size ; }
Add up the total bytes used by the process .
19,726
private byte [ ] collectProcessResultsBytes ( Process process , ProcessBuilder builder , SubProcessIOFiles outPutFiles ) throws Exception { Byte [ ] results ; try { LOG . debug ( String . format ( "Executing process %s" , createLogEntryFromInputs ( builder . command ( ) ) ) ) ; if ( process . exitValue ( ) != 0 ) { outPutFiles . copyOutPutFilesToBucket ( configuration , FileUtils . toStringParams ( builder ) ) ; String log = createLogEntryForProcessFailure ( process , builder . command ( ) , outPutFiles ) ; throw new Exception ( log ) ; } if ( ! Files . exists ( outPutFiles . resultFile ) ) { String log = createLogEntryForProcessFailure ( process , builder . command ( ) , outPutFiles ) ; outPutFiles . copyOutPutFilesToBucket ( configuration , FileUtils . toStringParams ( builder ) ) ; throw new Exception ( log ) ; } return Files . readAllBytes ( outPutFiles . resultFile ) ; } catch ( Exception ex ) { String log = String . format ( "Unexpected error runnng process. %s error message was %s" , createLogEntryFromInputs ( builder . command ( ) ) , ex . getMessage ( ) ) ; throw new Exception ( log ) ; } }
Used when the reault file contains binary data .
19,727
private ProcessBuilder appendExecutablePath ( ProcessBuilder builder ) { String executable = builder . command ( ) . get ( 0 ) ; if ( executable == null ) { throw new IllegalArgumentException ( "No executable provided to the Process Builder... we will do... nothing... " ) ; } builder . command ( ) . set ( 0 , FileUtils . getFileResourceId ( configuration . getWorkerPath ( ) , executable ) . toString ( ) ) ; return builder ; }
Pass the Path of the binary to the SubProcess in Command position 0
19,728
protected static Map < String , WriteWindowedToBigQuery . FieldInfo < Double > > configureSessionWindowWrite ( ) { Map < String , WriteWindowedToBigQuery . FieldInfo < Double > > tableConfigure = new HashMap < > ( ) ; tableConfigure . put ( "window_start" , new WriteWindowedToBigQuery . FieldInfo < > ( "STRING" , ( c , w ) -> { IntervalWindow window = ( IntervalWindow ) w ; return GameConstants . DATE_TIME_FORMATTER . print ( window . start ( ) ) ; } ) ) ; tableConfigure . put ( "mean_duration" , new WriteWindowedToBigQuery . FieldInfo < > ( "FLOAT" , ( c , w ) -> c . element ( ) ) ) ; return tableConfigure ; }
Create a map of information that describes how to write pipeline output to BigQuery . This map is used to write information about mean user session time .
19,729
public static void createDirectoriesOnWorker ( SubProcessConfiguration configuration ) throws IOException { try { Path path = Paths . get ( configuration . getWorkerPath ( ) ) ; if ( ! path . toFile ( ) . exists ( ) ) { Files . createDirectories ( path ) ; LOG . info ( String . format ( "Created Folder %s " , path . toFile ( ) ) ) ; } } catch ( FileAlreadyExistsException ex ) { LOG . warn ( String . format ( " Tried to create folder %s which already existsed, this should not happen!" , configuration . getWorkerPath ( ) ) , ex ) ; } }
Create directories needed based on configuration .
19,730
public static Pubsub getClient ( final HttpTransport httpTransport , final JsonFactory jsonFactory ) throws IOException { checkNotNull ( httpTransport ) ; checkNotNull ( jsonFactory ) ; GoogleCredential credential = GoogleCredential . getApplicationDefault ( httpTransport , jsonFactory ) ; if ( credential . createScopedRequired ( ) ) { credential = credential . createScoped ( PubsubScopes . all ( ) ) ; } if ( credential . getClientAuthentication ( ) != null ) { System . out . println ( "\n***Warning! You are not using service account credentials to " + "authenticate.\nYou need to use service account credentials for this example," + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run " + "out of PubSub quota very quickly.\nSee " + "https://developers.google.com/identity/protocols/application-default-credentials." ) ; System . exit ( 1 ) ; } HttpRequestInitializer initializer = new RetryHttpInitializerWrapper ( credential ) ; return new Pubsub . Builder ( httpTransport , jsonFactory , initializer ) . setApplicationName ( APP_NAME ) . build ( ) ; }
Builds a new Pubsub client and returns it .
19,731
public static void createTopic ( Pubsub client , String fullTopicName ) throws IOException { System . out . println ( "fullTopicName " + fullTopicName ) ; try { client . projects ( ) . topics ( ) . get ( fullTopicName ) . execute ( ) ; } catch ( GoogleJsonResponseException e ) { if ( e . getStatusCode ( ) == HttpStatusCodes . STATUS_CODE_NOT_FOUND ) { Topic topic = client . projects ( ) . topics ( ) . create ( fullTopicName , new Topic ( ) ) . execute ( ) ; System . out . printf ( "Topic %s was created.%n" , topic . getName ( ) ) ; } } }
Create a topic if it doesn t exist .
19,732
private static Map < String , FieldInfo < KV < String , Integer > > > configureCompleteWindowedTableWrite ( ) { Map < String , WriteWindowedToBigQuery . FieldInfo < KV < String , Integer > > > tableConfigure = new HashMap < > ( ) ; tableConfigure . put ( "team" , new WriteWindowedToBigQuery . FieldInfo < > ( "STRING" , ( c , w ) -> c . element ( ) . getKey ( ) ) ) ; tableConfigure . put ( "total_score" , new WriteWindowedToBigQuery . FieldInfo < > ( "INTEGER" , ( c , w ) -> c . element ( ) . getValue ( ) ) ) ; tableConfigure . put ( "processing_time" , new WriteWindowedToBigQuery . FieldInfo < > ( "STRING" , ( c , w ) -> GameConstants . DATE_TIME_FORMATTER . print ( Instant . now ( ) ) ) ) ; return tableConfigure ; }
Create a map of information that describes how to write pipeline output to BigQuery . This map is used to write team score sums .
19,733
public void delete ( URI src ) { Path dst = null ; try { dst = paths . get ( src ) ; } catch ( ExecutionException e ) { throw new RuntimeException ( e ) ; } try { Files . deleteIfExists ( dst ) ; paths . invalidate ( src ) ; } catch ( IOException e ) { String msg = String . format ( "Failed to delete %s -> %s" , src , dst ) ; LOG . error ( msg , e ) ; } }
Delete a single downloaded local file .
19,734
public void delete ( List < URI > srcs ) { for ( URI src : srcs ) { delete ( src ) ; } paths . invalidateAll ( srcs ) ; }
Delete a batch of downloaded local files .
19,735
private static void copyToLocal ( Metadata src , Path dst ) throws IOException { FileChannel dstCh = FileChannel . open ( dst , StandardOpenOption . WRITE , StandardOpenOption . CREATE_NEW ) ; ReadableByteChannel srcCh = FileSystems . open ( src . resourceId ( ) ) ; long srcSize = src . sizeBytes ( ) ; long copied = 0 ; do { copied += dstCh . transferFrom ( srcCh , copied , srcSize - copied ) ; } while ( copied < srcSize ) ; dstCh . close ( ) ; srcCh . close ( ) ; Preconditions . checkState ( copied == srcSize ) ; }
Copy a single file from remote source to local destination
19,736
private static void copyToRemote ( Path src , URI dst ) throws IOException { ResourceId dstId = FileSystems . matchNewResource ( dst . toString ( ) , false ) ; WritableByteChannel dstCh = FileSystems . create ( dstId , MimeTypes . BINARY ) ; FileChannel srcCh = FileChannel . open ( src , StandardOpenOption . READ ) ; long srcSize = srcCh . size ( ) ; long copied = 0 ; do { copied += srcCh . transferTo ( copied , srcSize - copied , dstCh ) ; } while ( copied < srcSize ) ; dstCh . close ( ) ; srcCh . close ( ) ; Preconditions . checkState ( copied == srcSize ) ; }
Copy a single file from local source to remote destination
19,737
static PCollection < String > joinEvents ( PCollection < TableRow > eventsTable , PCollection < TableRow > countryCodes ) throws Exception { final TupleTag < String > eventInfoTag = new TupleTag < > ( ) ; final TupleTag < String > countryInfoTag = new TupleTag < > ( ) ; PCollection < KV < String , String > > eventInfo = eventsTable . apply ( ParDo . of ( new ExtractEventDataFn ( ) ) ) ; PCollection < KV < String , String > > countryInfo = countryCodes . apply ( ParDo . of ( new ExtractCountryInfoFn ( ) ) ) ; PCollection < KV < String , CoGbkResult > > kvpCollection = KeyedPCollectionTuple . of ( eventInfoTag , eventInfo ) . and ( countryInfoTag , countryInfo ) . apply ( CoGroupByKey . create ( ) ) ; PCollection < KV < String , String > > finalResultCollection = kvpCollection . apply ( "Process" , ParDo . of ( new DoFn < KV < String , CoGbkResult > , KV < String , String > > ( ) { public void processElement ( ProcessContext c ) { KV < String , CoGbkResult > e = c . element ( ) ; String countryCode = e . getKey ( ) ; String countryName = "none" ; countryName = e . getValue ( ) . getOnly ( countryInfoTag ) ; for ( String eventInfo : c . element ( ) . getValue ( ) . getAll ( eventInfoTag ) ) { c . output ( KV . of ( countryCode , "Country name: " + countryName + ", Event info: " + eventInfo ) ) ; } } } ) ) ; PCollection < String > formattedResults = finalResultCollection . apply ( "Format" , ParDo . of ( new DoFn < KV < String , String > , String > ( ) { public void processElement ( ProcessContext c ) { String outputstring = "Country code: " + c . element ( ) . getKey ( ) + ", " + c . element ( ) . getValue ( ) ; c . output ( outputstring ) ; } } ) ) ; return formattedResults ; }
Join two collections using country code as the key .
19,738
protected static Map < String , WriteWindowedToBigQuery . FieldInfo < KV < String , Integer > > > configureWindowedTableWrite ( ) { Map < String , WriteWindowedToBigQuery . FieldInfo < KV < String , Integer > > > tableConfigure = new HashMap < > ( ) ; tableConfigure . put ( "team" , new WriteWindowedToBigQuery . FieldInfo < > ( "STRING" , ( c , w ) -> c . element ( ) . getKey ( ) ) ) ; tableConfigure . put ( "total_score" , new WriteWindowedToBigQuery . FieldInfo < > ( "INTEGER" , ( c , w ) -> c . element ( ) . getValue ( ) ) ) ; tableConfigure . put ( "window_start" , new WriteWindowedToBigQuery . FieldInfo < > ( "STRING" , ( c , w ) -> { IntervalWindow window = ( IntervalWindow ) w ; return GameConstants . DATE_TIME_FORMATTER . print ( window . start ( ) ) ; } ) ) ; tableConfigure . put ( "processing_time" , new WriteWindowedToBigQuery . FieldInfo < > ( "STRING" , ( c , w ) -> GameConstants . DATE_TIME_FORMATTER . print ( Instant . now ( ) ) ) ) ; tableConfigure . put ( "timing" , new WriteWindowedToBigQuery . FieldInfo < > ( "STRING" , ( c , w ) -> c . pane ( ) . getTiming ( ) . toString ( ) ) ) ; return tableConfigure ; }
Create a map of information that describes how to write pipeline output to BigQuery . This map is used to write team score sums and includes event timing information .
19,739
protected static Map < String , WriteToBigQuery . FieldInfo < KV < String , Integer > > > configureGlobalWindowBigQueryWrite ( ) { Map < String , WriteToBigQuery . FieldInfo < KV < String , Integer > > > tableConfigure = configureBigQueryWrite ( ) ; tableConfigure . put ( "processing_time" , new WriteToBigQuery . FieldInfo < > ( "STRING" , ( c , w ) -> GameConstants . DATE_TIME_FORMATTER . print ( Instant . now ( ) ) ) ) ; return tableConfigure ; }
Create a map of information that describes how to write pipeline output to BigQuery . This map is used to write user score sums .
19,740
public static String formatCoGbkResults ( String name , Iterable < String > emails , Iterable < String > phones ) { List < String > emailsList = new ArrayList < > ( ) ; for ( String elem : emails ) { emailsList . add ( "'" + elem + "'" ) ; } Collections . sort ( emailsList ) ; String emailsStr = "[" + String . join ( ", " , emailsList ) + "]" ; List < String > phonesList = new ArrayList < > ( ) ; for ( String elem : phones ) { phonesList . add ( "'" + elem + "'" ) ; } Collections . sort ( phonesList ) ; String phonesStr = "[" + String . join ( ", " , phonesList ) + "]" ; return name + "; " + emailsStr + "; " + phonesStr ; }
Helper function to format results in coGroupByKeyTuple .
19,741
public static PCollection < String > coGroupByKeyTuple ( TupleTag < String > emailsTag , TupleTag < String > phonesTag , PCollection < KV < String , String > > emails , PCollection < KV < String , String > > phones ) { PCollection < KV < String , CoGbkResult > > results = KeyedPCollectionTuple . of ( emailsTag , emails ) . and ( phonesTag , phones ) . apply ( CoGroupByKey . create ( ) ) ; PCollection < String > contactLines = results . apply ( ParDo . of ( new DoFn < KV < String , CoGbkResult > , String > ( ) { public void processElement ( ProcessContext c ) { KV < String , CoGbkResult > e = c . element ( ) ; String name = e . getKey ( ) ; Iterable < String > emailsIter = e . getValue ( ) . getAll ( emailsTag ) ; Iterable < String > phonesIter = e . getValue ( ) . getAll ( phonesTag ) ; String formattedResult = Snippets . formatCoGbkResults ( name , emailsIter , phonesIter ) ; c . output ( formattedResult ) ; } } ) ) ; return contactLines ; }
Using a CoGroupByKey transform .
19,742
public static Map < String , Integer > getClusterSizes ( final String projectId , final String instanceId ) throws IOException , GeneralSecurityException { try ( BigtableClusterUtilities clusterUtil = BigtableClusterUtilities . forInstance ( projectId , instanceId ) ) { return Collections . unmodifiableMap ( clusterUtil . getClusters ( ) . getClustersList ( ) . stream ( ) . collect ( Collectors . toMap ( cn -> cn . getName ( ) . substring ( cn . getName ( ) . indexOf ( "/clusters/" ) + 10 ) , Cluster :: getServeNodes ) ) ) ; } }
Get size of all clusters for specified Bigtable instance .
19,743
public void setupBigQueryTable ( ) throws IOException { ExampleBigQueryTableOptions bigQueryTableOptions = options . as ( ExampleBigQueryTableOptions . class ) ; if ( bigQueryTableOptions . getBigQueryDataset ( ) != null && bigQueryTableOptions . getBigQueryTable ( ) != null && bigQueryTableOptions . getBigQuerySchema ( ) != null ) { pendingMessages . add ( "******************Set Up Big Query Table*******************" ) ; setupBigQueryTable ( bigQueryTableOptions . getProject ( ) , bigQueryTableOptions . getBigQueryDataset ( ) , bigQueryTableOptions . getBigQueryTable ( ) , bigQueryTableOptions . getBigQuerySchema ( ) ) ; pendingMessages . add ( "The BigQuery table has been set up for this example: " + bigQueryTableOptions . getProject ( ) + ":" + bigQueryTableOptions . getBigQueryDataset ( ) + "." + bigQueryTableOptions . getBigQueryTable ( ) ) ; } }
Sets up the BigQuery table with the given schema .
19,744
private void tearDown ( ) { pendingMessages . add ( "*************************Tear Down*************************" ) ; ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = options . as ( ExamplePubsubTopicAndSubscriptionOptions . class ) ; if ( ! pubsubOptions . getPubsubTopic ( ) . isEmpty ( ) ) { try { deletePubsubTopic ( pubsubOptions . getPubsubTopic ( ) ) ; pendingMessages . add ( "The Pub/Sub topic has been deleted: " + pubsubOptions . getPubsubTopic ( ) ) ; } catch ( IOException e ) { pendingMessages . add ( "Failed to delete the Pub/Sub topic : " + pubsubOptions . getPubsubTopic ( ) ) ; } if ( ! pubsubOptions . getPubsubSubscription ( ) . isEmpty ( ) ) { try { deletePubsubSubscription ( pubsubOptions . getPubsubSubscription ( ) ) ; pendingMessages . add ( "The Pub/Sub subscription has been deleted: " + pubsubOptions . getPubsubSubscription ( ) ) ; } catch ( IOException e ) { pendingMessages . add ( "Failed to delete the Pub/Sub subscription : " + pubsubOptions . getPubsubSubscription ( ) ) ; } } } ExampleBigQueryTableOptions bigQueryTableOptions = options . as ( ExampleBigQueryTableOptions . class ) ; if ( bigQueryTableOptions . getBigQueryDataset ( ) != null && bigQueryTableOptions . getBigQueryTable ( ) != null && bigQueryTableOptions . getBigQuerySchema ( ) != null ) { pendingMessages . add ( "The BigQuery table might contain the example's output, " + "and it is not deleted automatically: " + bigQueryTableOptions . getProject ( ) + ":" + bigQueryTableOptions . getBigQueryDataset ( ) + "." + bigQueryTableOptions . getBigQueryTable ( ) ) ; pendingMessages . add ( "Please go to the Developers Console to delete it manually." + " Otherwise, you may be charged for its usage." ) ; } }
Tears down external resources that can be deleted upon the example s completion .
19,745
public void waitToFinish ( PipelineResult result ) { pipelinesToCancel . add ( result ) ; if ( ! options . as ( ExampleOptions . class ) . getKeepJobsRunning ( ) ) { addShutdownHook ( pipelinesToCancel ) ; } try { result . waitUntilFinish ( ) ; } catch ( UnsupportedOperationException e ) { tearDown ( ) ; printPendingMessages ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "Failed to wait the pipeline until finish: " + result ) ; } }
Waits for the pipeline to finish and cancels it before the program exists .
19,746
public static void main ( String [ ] args ) throws IOException { StreamingWordExtractOptions options = PipelineOptionsFactory . fromArgs ( args ) . withValidation ( ) . as ( StreamingWordExtractOptions . class ) ; options . setStreaming ( true ) ; options . setBigQuerySchema ( StringToRowConverter . getSchema ( ) ) ; ExampleUtils exampleUtils = new ExampleUtils ( options ) ; exampleUtils . setup ( ) ; Pipeline pipeline = Pipeline . create ( options ) ; String tableSpec = new StringBuilder ( ) . append ( options . getProject ( ) ) . append ( ":" ) . append ( options . getBigQueryDataset ( ) ) . append ( "." ) . append ( options . getBigQueryTable ( ) ) . toString ( ) ; pipeline . apply ( "ReadLines" , TextIO . read ( ) . from ( options . getInputFile ( ) ) ) . apply ( ParDo . of ( new ExtractWords ( ) ) ) . apply ( ParDo . of ( new Uppercase ( ) ) ) . apply ( ParDo . of ( new StringToRowConverter ( ) ) ) . apply ( BigQueryIO . writeTableRows ( ) . to ( tableSpec ) . withSchema ( StringToRowConverter . getSchema ( ) ) ) ; PipelineResult result = pipeline . run ( ) ; exampleUtils . waitToFinish ( result ) ; }
Sets up and starts streaming pipeline .
19,747
public void close ( ) throws IOException { if ( Files . exists ( outFile ) ) { Files . delete ( outFile ) ; } if ( Files . exists ( errFile ) ) { Files . delete ( errFile ) ; } if ( Files . exists ( resultFile ) ) { Files . delete ( resultFile ) ; } }
Clean up the files that have been created on the local worker file system . Without this expect both performance issues and eventual failure
19,748
public void copyOutPutFilesToBucket ( SubProcessConfiguration configuration , String params ) { if ( Files . exists ( outFile ) || Files . exists ( errFile ) ) { try { outFileLocation = FileUtils . copyFileFromWorkerToGCS ( configuration , outFile ) ; } catch ( Exception ex ) { LOG . error ( "Error uploading log file to storage " , ex ) ; } try { errFileLocation = FileUtils . copyFileFromWorkerToGCS ( configuration , errFile ) ; } catch ( Exception ex ) { LOG . error ( "Error uploading log file to storage " , ex ) ; } LOG . info ( String . format ( "Log Files for process: %s outFile was: %s errFile was: %s" , params , outFileLocation , errFileLocation ) ) ; } else { LOG . error ( String . format ( "There was no output file or err file for process %s" , params ) ) ; } }
Will copy the output files to the GCS path setup via the configuration .
19,749
protected TableSchema getSchema ( ) { List < TableFieldSchema > fields = new ArrayList < > ( ) ; for ( Map . Entry < String , FieldInfo < InputT > > entry : fieldInfo . entrySet ( ) ) { String key = entry . getKey ( ) ; FieldInfo < InputT > fcnInfo = entry . getValue ( ) ; String bqType = fcnInfo . getFieldType ( ) ; fields . add ( new TableFieldSchema ( ) . setName ( key ) . setType ( bqType ) ) ; } return new TableSchema ( ) . setFields ( fields ) ; }
Build the output table schema .
19,750
static TableReference getTable ( String projectId , String datasetId , String tableName ) { TableReference table = new TableReference ( ) ; table . setDatasetId ( datasetId ) ; table . setProjectId ( projectId ) ; table . setTableId ( tableName ) ; return table ; }
Utility to construct an output table reference .
19,751
private void flush ( Consumer < Result > outputFn ) { Result r = results . poll ( ) ; while ( r != null ) { outputFn . accept ( r ) ; resultCount ++ ; r = results . poll ( ) ; } }
Flush pending errors and results
19,752
public void open ( ) throws IOException , InterruptedException { if ( queryConfig != null ) { ref = executeQueryAndWaitForCompletion ( ) ; } schema = getTable ( ref ) . getSchema ( ) ; }
Opens the table for read .
19,753
private Object getTypedCellValue ( TableFieldSchema fieldSchema , Object v ) { if ( Data . isNull ( v ) ) { return null ; } if ( Objects . equals ( fieldSchema . getMode ( ) , "REPEATED" ) ) { TableFieldSchema elementSchema = fieldSchema . clone ( ) . setMode ( "REQUIRED" ) ; @ SuppressWarnings ( "unchecked" ) List < Map < String , Object > > rawCells = ( List < Map < String , Object > > ) v ; ImmutableList . Builder < Object > values = ImmutableList . builder ( ) ; for ( Map < String , Object > element : rawCells ) { values . add ( getTypedCellValue ( elementSchema , element . get ( "v" ) ) ) ; } return values . build ( ) ; } if ( fieldSchema . getType ( ) . equals ( "RECORD" ) ) { @ SuppressWarnings ( "unchecked" ) Map < String , Object > typedV = ( Map < String , Object > ) v ; return getTypedTableRow ( fieldSchema . getFields ( ) , typedV ) ; } if ( fieldSchema . getType ( ) . equals ( "FLOAT" ) ) { return Double . parseDouble ( ( String ) v ) ; } if ( fieldSchema . getType ( ) . equals ( "BOOLEAN" ) ) { return Boolean . parseBoolean ( ( String ) v ) ; } if ( fieldSchema . getType ( ) . equals ( "TIMESTAMP" ) ) { return formatTimestamp ( ( String ) v ) ; } return v ; }
Adjusts a field returned from the BigQuery API to match what we will receive when running BigQuery s export - to - GCS and parallel read which is the efficient parallel implementation used for batch jobs executed on the Beam Runners that perform initial splitting .
19,754
private Table getTable ( TableReference ref ) throws IOException , InterruptedException { Bigquery . Tables . Get get = client . tables ( ) . get ( ref . getProjectId ( ) , ref . getDatasetId ( ) , ref . getTableId ( ) ) ; return executeWithBackOff ( get , String . format ( "Error opening BigQuery table %s of dataset %s." , ref . getTableId ( ) , ref . getDatasetId ( ) ) ) ; }
Get the BiqQuery table .
19,755
private void deleteTable ( String datasetId , String tableId ) throws IOException , InterruptedException { executeWithBackOff ( client . tables ( ) . delete ( projectId , datasetId , tableId ) , String . format ( "Error when trying to delete the temporary table %s in dataset %s of project %s. " + "Manual deletion may be required." , tableId , datasetId , projectId ) ) ; }
Delete the given table that is available in the given dataset .
19,756
private void deleteDataset ( String datasetId ) throws IOException , InterruptedException { executeWithBackOff ( client . datasets ( ) . delete ( projectId , datasetId ) , String . format ( "Error when trying to delete the temporary dataset %s in project %s. " + "Manual deletion may be required." , datasetId , projectId ) ) ; }
Delete the given dataset . This will fail if the given dataset has any tables .
19,757
public static < T > T executeWithBackOff ( AbstractGoogleClientRequest < T > client , String error ) throws IOException , InterruptedException { Sleeper sleeper = Sleeper . DEFAULT ; BackOff backOff = BackOffAdapter . toGcpBackOff ( FluentBackoff . DEFAULT . withMaxRetries ( MAX_RETRIES ) . withInitialBackoff ( INITIAL_BACKOFF_TIME ) . backoff ( ) ) ; T result = null ; while ( true ) { try { result = client . execute ( ) ; break ; } catch ( IOException e ) { LOG . error ( "{}" , error , e ) ; if ( ! BackOffUtils . next ( sleeper , backOff ) ) { String errorMessage = String . format ( "%s Failing to execute job after %d attempts." , error , MAX_RETRIES + 1 ) ; LOG . error ( "{}" , errorMessage , e ) ; throw new IOException ( errorMessage , e ) ; } } } return result ; }
formatter parameter .
19,758
private static String randomElement ( ArrayList < String > list ) { int index = random . nextInt ( list . size ( ) ) ; return list . get ( index ) ; }
Utility to grab a random element from an array of Strings .
19,759
private static TeamInfo randomTeam ( ArrayList < TeamInfo > list ) { int index = random . nextInt ( list . size ( ) ) ; TeamInfo team = list . get ( index ) ; long currTime = System . currentTimeMillis ( ) ; if ( ( team . getEndTimeInMillis ( ) < currTime ) || team . numMembers ( ) == 0 ) { System . out . println ( "\nteam " + team + " is too old; replacing." ) ; System . out . println ( "start time: " + team . getStartTimeInMillis ( ) + ", end time: " + team . getEndTimeInMillis ( ) + ", current time:" + currTime ) ; removeTeam ( index ) ; return ( addLiveTeam ( ) ) ; } else { return team ; } }
Get and return a random team . If the selected team is too old w . r . t its expiration remove it replacing it with a new team .
19,760
private static synchronized TeamInfo addLiveTeam ( ) { String teamName = randomElement ( COLORS ) + randomElement ( ANIMALS ) ; String robot = null ; if ( random . nextInt ( ROBOT_PROBABILITY ) == 0 ) { robot = "Robot-" + random . nextInt ( NUM_ROBOTS ) ; } TeamInfo newTeam = new TeamInfo ( teamName , System . currentTimeMillis ( ) , robot ) ; liveTeams . add ( newTeam ) ; System . out . println ( "[+" + newTeam + "]" ) ; return newTeam ; }
Create and add a team . Possibly add a robot to the team .
19,761
private static synchronized void removeTeam ( int teamIndex ) { TeamInfo removedTeam = liveTeams . remove ( teamIndex ) ; System . out . println ( "[-" + removedTeam + "]" ) ; }
Remove a specific team .
19,762
private static String generateEvent ( Long currTime , int delayInMillis ) { TeamInfo team = randomTeam ( liveTeams ) ; String teamName = team . getTeamName ( ) ; String user ; final int parseErrorRate = 900000 ; String robot = team . getRobot ( ) ; if ( robot != null ) { if ( random . nextInt ( team . numMembers ( ) / 2 ) == 0 ) { user = robot ; } else { user = team . getRandomUser ( ) ; } } else { user = team . getRandomUser ( ) ; } String event = user + "," + teamName + "," + random . nextInt ( MAX_SCORE ) ; if ( random . nextInt ( parseErrorRate ) == 0 ) { System . out . println ( "Introducing a parse error." ) ; event = "THIS LINE REPRESENTS CORRUPT DATA AND WILL CAUSE A PARSE ERROR" ; } return addTimeInfoToEvent ( event , currTime , delayInMillis ) ; }
Generate a user gaming event .
19,763
private static String addTimeInfoToEvent ( String message , Long currTime , int delayInMillis ) { String eventTimeString = Long . toString ( ( currTime - delayInMillis ) / 1000 * 1000 ) ; String dateString = GameConstants . DATE_TIME_FORMATTER . print ( currTime ) ; message = message + "," + eventTimeString + "," + dateString ; return message ; }
Add time info to a generated gaming event .
19,764
public static void publishData ( int numMessages , int delayInMillis ) throws IOException { List < PubsubMessage > pubsubMessages = new ArrayList < > ( ) ; for ( int i = 0 ; i < Math . max ( 1 , numMessages ) ; i ++ ) { Long currTime = System . currentTimeMillis ( ) ; String message = generateEvent ( currTime , delayInMillis ) ; PubsubMessage pubsubMessage = new PubsubMessage ( ) . encodeData ( message . getBytes ( "UTF-8" ) ) ; pubsubMessage . setAttributes ( ImmutableMap . of ( GameConstants . TIMESTAMP_ATTRIBUTE , Long . toString ( ( currTime - delayInMillis ) / 1000 * 1000 ) ) ) ; if ( delayInMillis != 0 ) { System . out . println ( pubsubMessage . getAttributes ( ) ) ; System . out . println ( "late data for: " + message ) ; } pubsubMessages . add ( pubsubMessage ) ; } PublishRequest publishRequest = new PublishRequest ( ) ; publishRequest . setMessages ( pubsubMessages ) ; pubsub . projects ( ) . topics ( ) . publish ( topic , publishRequest ) . execute ( ) ; }
Publish numMessages arbitrary events from live users with the provided delay to a PubSub topic .
19,765
public static void publishDataToFile ( String fileName , int numMessages , int delayInMillis ) throws IOException { PrintWriter out = new PrintWriter ( new OutputStreamWriter ( new BufferedOutputStream ( new FileOutputStream ( fileName , true ) ) , "UTF-8" ) ) ; try { for ( int i = 0 ; i < Math . max ( 1 , numMessages ) ; i ++ ) { Long currTime = System . currentTimeMillis ( ) ; String message = generateEvent ( currTime , delayInMillis ) ; out . println ( message ) ; } } catch ( Exception e ) { System . err . print ( "Error in writing generated events to file" ) ; e . printStackTrace ( ) ; } finally { out . flush ( ) ; out . close ( ) ; } }
Publish generated events to a file .
19,766
public boolean isDeleted ( Cell cell ) { if ( isLive ( ) ) return false ; if ( cell . timestamp ( ) <= topLevel . markedForDeleteAt ) return true ; if ( ! topLevel . isLive ( ) && cell instanceof CounterCell ) return true ; return ranges != null && ranges . isDeleted ( cell ) ; }
Return whether a given cell is deleted by the container having this deletion info .
19,767
public DeletionInfo diff ( DeletionInfo superset ) { RangeTombstoneList rangeDiff = superset . ranges == null || superset . ranges . isEmpty ( ) ? null : ranges == null ? superset . ranges : ranges . diff ( superset . ranges ) ; return topLevel . markedForDeleteAt != superset . topLevel . markedForDeleteAt || rangeDiff != null ? new DeletionInfo ( superset . topLevel , rangeDiff ) : DeletionInfo . live ( ) ; }
Evaluates difference between this deletion info and superset for read repair
19,768
public void updateDigest ( MessageDigest digest ) { if ( topLevel . markedForDeleteAt != Long . MIN_VALUE ) digest . update ( ByteBufferUtil . bytes ( topLevel . markedForDeleteAt ) ) ; if ( ranges != null ) ranges . updateDigest ( digest ) ; }
Digests deletion info . Used to trigger read repair on mismatch .
19,769
public DeletionInfo add ( DeletionInfo newInfo ) { add ( newInfo . topLevel ) ; if ( ranges == null ) ranges = newInfo . ranges == null ? null : newInfo . ranges . copy ( ) ; else if ( newInfo . ranges != null ) ranges . addAll ( newInfo . ranges ) ; return this ; }
Combines another DeletionInfo with this one and returns the result . Whichever top - level tombstone has the higher markedForDeleteAt timestamp will be kept along with its localDeletionTime . The range tombstones will be combined .
19,770
public long minTimestamp ( ) { return ranges == null ? topLevel . markedForDeleteAt : Math . min ( topLevel . markedForDeleteAt , ranges . minMarkedAt ( ) ) ; }
Returns the minimum timestamp in any of the range tombstones or the top - level tombstone .
19,771
public long maxTimestamp ( ) { return ranges == null ? topLevel . markedForDeleteAt : Math . max ( topLevel . markedForDeleteAt , ranges . maxMarkedAt ( ) ) ; }
Returns the maximum timestamp in any of the range tombstones or the top - level tombstone .
19,772
public static CqlBulkRecordWriter newWriter ( Configuration conf , String host , int port , String username , String password , String keyspace , String table , String partitioner , String tableSchema , String insertStatement ) throws IOException { Config . setClientMode ( true ) ; ConfigHelper . setOutputInitialAddress ( conf , host ) ; if ( port >= 0 ) { ConfigHelper . setOutputRpcPort ( conf , String . valueOf ( port ) ) ; } if ( username != null && password != null ) { ConfigHelper . setOutputKeyspaceUserNameAndPassword ( conf , username , password ) ; } ConfigHelper . setOutputKeyspace ( conf , keyspace ) ; ConfigHelper . setOutputColumnFamily ( conf , table ) ; ConfigHelper . setOutputPartitioner ( conf , partitioner ) ; CqlBulkOutputFormat . setTableSchema ( conf , table , tableSchema ) ; CqlBulkOutputFormat . setTableInsertStatement ( conf , table , insertStatement ) ; conf . set ( CqlBulkRecordWriter . OUTPUT_LOCATION , Files . createTempDirectory ( "scio-cassandra-" ) . toString ( ) ) ; if ( ! System . getProperties ( ) . containsKey ( "hadoop.home.dir" ) && ! System . getenv ( ) . containsKey ( "HADOOP_HOME" ) ) { System . setProperty ( "hadoop.home.dir" , "/" ) ; } return new CqlBulkRecordWriter ( conf ) ; }
Workaround to expose package private constructor .
19,773
public final void initialize ( final HttpRequest request ) { request . setReadTimeout ( 2 * ONEMINITUES ) ; final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler ( new ExponentialBackOff ( ) ) . setSleeper ( sleeper ) ; request . setInterceptor ( wrappedCredential ) ; request . setUnsuccessfulResponseHandler ( ( request1 , response , supportsRetry ) -> { if ( wrappedCredential . handleResponse ( request1 , response , supportsRetry ) ) { return true ; } else if ( backoffHandler . handleResponse ( request1 , response , supportsRetry ) ) { LOG . info ( "Retrying " + request1 . getUrl ( ) . toString ( ) ) ; return true ; } else { return false ; } } ) ; request . setIOExceptionHandler ( new HttpBackOffIOExceptionHandler ( new ExponentialBackOff ( ) ) . setSleeper ( sleeper ) ) ; }
Initializes the given request .
19,774
public LineMessagingClientBuilder okHttpClientBuilder ( final OkHttpClient . Builder okHttpClientBuilder , final boolean addAuthenticationHeader ) { this . okHttpClientBuilder = okHttpClientBuilder ; this . addAuthenticationHeader = addAuthenticationHeader ; return this ; }
Set customized OkHttpClient . Builder .
19,775
static byte [ ] parseBytesOrNull ( final String deviceMessageAsHex ) { if ( deviceMessageAsHex == null ) { return null ; } final int length = deviceMessageAsHex . length ( ) ; final int resultSize = length / 2 ; if ( length % 2 != 0 ) { throw new IllegalArgumentException ( "hex string needs to be even-length: " + deviceMessageAsHex ) ; } final byte [ ] bytes = new byte [ resultSize ] ; for ( int pos = 0 ; pos < resultSize ; pos ++ ) { bytes [ pos ] = ( byte ) Integer . parseInt ( deviceMessageAsHex . substring ( pos * 2 , pos * 2 + 2 ) , 16 ) ; } return bytes ; }
Parse hext presentation to byte array .
19,776
public static void main ( final String ... args ) throws Exception { try ( ConfigurableApplicationContext context = SpringApplication . run ( Application . class , args ) ) { log . info ( "Arguments: {}" , Arrays . asList ( args ) ) ; try { context . getBean ( Application . class ) . run ( context ) ; } catch ( Exception e ) { log . error ( "Exception in command execution" , e ) ; } } }
Entry point of line - bot - cli .
19,777
public void onScrollChanged ( int scrollY , Scrollable s ) { FlexibleSpaceWithImageBaseFragment fragment = ( FlexibleSpaceWithImageBaseFragment ) mPagerAdapter . getItemAt ( mPager . getCurrentItem ( ) ) ; if ( fragment == null ) { return ; } View view = fragment . getView ( ) ; if ( view == null ) { return ; } Scrollable scrollable = ( Scrollable ) view . findViewById ( R . id . scroll ) ; if ( scrollable == null ) { return ; } if ( scrollable == s ) { int adjustedScrollY = Math . min ( scrollY , mFlexibleSpaceHeight - mTabHeight ) ; translateTab ( adjustedScrollY , false ) ; propagateScroll ( adjustedScrollY ) ; } }
Called by children Fragments when their scrollY are changed . They all call this method even when they are inactive but this Activity should listen only the active child so each Fragments will pass themselves for Activity to check if they are active .
19,778
public static float [ ] cmykFromRgb ( int rgbColor ) { int red = ( 0xff0000 & rgbColor ) >> 16 ; int green = ( 0xff00 & rgbColor ) >> 8 ; int blue = ( 0xff & rgbColor ) ; float black = Math . min ( 1.0f - red / 255.0f , Math . min ( 1.0f - green / 255.0f , 1.0f - blue / 255.0f ) ) ; float cyan = 1.0f ; float magenta = 1.0f ; float yellow = 1.0f ; if ( black != 1.0f ) { cyan = ( 1.0f - ( red / 255.0f ) - black ) / ( 1.0f - black ) ; magenta = ( 1.0f - ( green / 255.0f ) - black ) / ( 1.0f - black ) ; yellow = ( 1.0f - ( blue / 255.0f ) - black ) / ( 1.0f - black ) ; } return new float [ ] { cyan , magenta , yellow , black } ; }
Convert RGB color to CMYK color .
19,779
public static int rgbFromCmyk ( float [ ] cmyk ) { float cyan = cmyk [ 0 ] ; float magenta = cmyk [ 1 ] ; float yellow = cmyk [ 2 ] ; float black = cmyk [ 3 ] ; int red = ( int ) ( ( 1.0f - Math . min ( 1.0f , cyan * ( 1.0f - black ) + black ) ) * 255 ) ; int green = ( int ) ( ( 1.0f - Math . min ( 1.0f , magenta * ( 1.0f - black ) + black ) ) * 255 ) ; int blue = ( int ) ( ( 1.0f - Math . min ( 1.0f , yellow * ( 1.0f - black ) + black ) ) * 255 ) ; return ( ( 0xff & red ) << 16 ) + ( ( 0xff & green ) << 8 ) + ( 0xff & blue ) ; }
Convert CYMK color to RGB color . This method doesn t check if cmyk is not null or have 4 elements in array .
19,780
private void initFragment ( ) { FragmentManager fm = getSupportFragmentManager ( ) ; if ( fm . findFragmentByTag ( FragmentTransitionDefaultFragment . FRAGMENT_TAG ) == null ) { FragmentTransaction ft = fm . beginTransaction ( ) ; ft . add ( R . id . fragment , new FragmentTransitionDefaultFragment ( ) , FragmentTransitionDefaultFragment . FRAGMENT_TAG ) ; ft . commit ( ) ; fm . executePendingTransactions ( ) ; } }
Fragment should be added programmatically . Using fragment tag in XML causes IllegalStateException on rotation of screen or restoring states of activity .
19,781
public List < String > getRolesForUser ( String name ) { try { return model . model . get ( "g" ) . get ( "g" ) . rm . getRoles ( name ) ; } catch ( Error e ) { if ( ! e . getMessage ( ) . equals ( "error: name does not exist" ) ) { throw e ; } } return null ; }
getRolesForUser gets the roles that a user has .
19,782
public List < String > getUsersForRole ( String name ) { try { return model . model . get ( "g" ) . get ( "g" ) . rm . getUsers ( name ) ; } catch ( Error e ) { if ( ! e . getMessage ( ) . equals ( "error: name does not exist" ) ) { throw e ; } } return null ; }
getUsersForRole gets the users that has a role .
19,783
public boolean hasRoleForUser ( String name , String role ) { List < String > roles = getRolesForUser ( name ) ; boolean hasRole = false ; for ( String r : roles ) { if ( r . equals ( role ) ) { hasRole = true ; break ; } } return hasRole ; }
hasRoleForUser determines whether a user has a role .
19,784
public List < List < String > > getPermissionsForUserInDomain ( String user , String domain ) { return getFilteredPolicy ( 0 , user , domain ) ; }
getPermissionsForUserInDomain gets permissions for a user or role inside a domain .
19,785
public List < String > getRoles ( String name , String ... domain ) { if ( domain . length == 1 ) { name = domain [ 0 ] + "::" + name ; } else if ( domain . length > 1 ) { throw new Error ( "error: domain should be 1 parameter" ) ; } if ( ! hasRole ( name ) ) { throw new Error ( "error: name does not exist" ) ; } List < String > roles = createRole ( name ) . getRoles ( ) ; if ( domain . length == 1 ) { for ( int i = 0 ; i < roles . size ( ) ; i ++ ) { roles . set ( i , roles . get ( i ) . substring ( domain [ 0 ] . length ( ) + 2 , roles . get ( i ) . length ( ) ) ) ; } } return roles ; }
getRoles gets the roles that a subject inherits . domain is a prefix to the roles .
19,786
public List < String > getUsers ( String name ) { if ( ! hasRole ( name ) ) { throw new Error ( "error: name does not exist" ) ; } List < String > names = new ArrayList < > ( ) ; for ( Role role : allRoles . values ( ) ) { if ( role . hasDirectRole ( name ) ) { names . add ( role . name ) ; } } return names ; }
getUsers gets the users that inherits a subject . domain is an unreferenced parameter here may be used in other implementations .
19,787
public void printRoles ( ) { for ( Role role : allRoles . values ( ) ) { Util . logPrint ( role . toString ( ) ) ; } }
printRoles prints all the roles to log .
19,788
public void buildRoleLinks ( RoleManager rm ) { if ( model . containsKey ( "g" ) ) { for ( Assertion ast : model . get ( "g" ) . values ( ) ) { ast . buildRoleLinks ( rm ) ; } } }
buildRoleLinks initializes the roles in RBAC .
19,789
public void printPolicy ( ) { Util . logPrint ( "Policy:" ) ; if ( model . containsKey ( "p" ) ) { for ( Map . Entry < String , Assertion > entry : model . get ( "p" ) . entrySet ( ) ) { String key = entry . getKey ( ) ; Assertion ast = entry . getValue ( ) ; Util . logPrint ( key + ": " + ast . value + ": " + ast . policy ) ; } } if ( model . containsKey ( "g" ) ) { for ( Map . Entry < String , Assertion > entry : model . get ( "g" ) . entrySet ( ) ) { String key = entry . getKey ( ) ; Assertion ast = entry . getValue ( ) ; Util . logPrint ( key + ": " + ast . value + ": " + ast . policy ) ; } } }
printPolicy prints the policy to log .
19,790
public void clearPolicy ( ) { if ( model . containsKey ( "p" ) ) { for ( Assertion ast : model . get ( "p" ) . values ( ) ) { ast . policy = new ArrayList < > ( ) ; } } if ( model . containsKey ( "g" ) ) { for ( Assertion ast : model . get ( "g" ) . values ( ) ) { ast . policy = new ArrayList < > ( ) ; } } }
clearPolicy clears all current policy .
19,791
public List < List < String > > getPolicy ( String sec , String ptype ) { return model . get ( sec ) . get ( ptype ) . policy ; }
getPolicy gets all rules in a policy .
19,792
public List < List < String > > getFilteredPolicy ( String sec , String ptype , int fieldIndex , String ... fieldValues ) { List < List < String > > res = new ArrayList < > ( ) ; for ( List < String > rule : model . get ( sec ) . get ( ptype ) . policy ) { boolean matched = true ; for ( int i = 0 ; i < fieldValues . length ; i ++ ) { String fieldValue = fieldValues [ i ] ; if ( ! fieldValue . equals ( "" ) && ! rule . get ( fieldIndex + i ) . equals ( fieldValue ) ) { matched = false ; break ; } } if ( matched ) { res . add ( rule ) ; } } return res ; }
getFilteredPolicy gets rules based on field filters from a policy .
19,793
public boolean hasPolicy ( String sec , String ptype , List < String > rule ) { for ( List < String > r : model . get ( sec ) . get ( ptype ) . policy ) { if ( Util . arrayEquals ( rule , r ) ) { return true ; } } return false ; }
hasPolicy determines whether a model has the specified policy rule .
19,794
public boolean addPolicy ( String sec , String ptype , List < String > rule ) { if ( ! hasPolicy ( sec , ptype , rule ) ) { model . get ( sec ) . get ( ptype ) . policy . add ( rule ) ; return true ; } return false ; }
addPolicy adds a policy rule to the model .
19,795
public boolean removePolicy ( String sec , String ptype , List < String > rule ) { for ( int i = 0 ; i < model . get ( sec ) . get ( ptype ) . policy . size ( ) ; i ++ ) { List < String > r = model . get ( sec ) . get ( ptype ) . policy . get ( i ) ; if ( Util . arrayEquals ( rule , r ) ) { model . get ( sec ) . get ( ptype ) . policy . remove ( i ) ; return true ; } } return false ; }
removePolicy removes a policy rule from the model .
19,796
public List < String > getValuesForFieldInPolicy ( String sec , String ptype , int fieldIndex ) { List < String > values = new ArrayList < > ( ) ; for ( List < String > rule : model . get ( sec ) . get ( ptype ) . policy ) { values . add ( rule . get ( fieldIndex ) ) ; } Util . arrayRemoveDuplicates ( values ) ; return values ; }
getValuesForFieldInPolicy gets all values for a field for all rules in a policy duplicated values are removed .
19,797
public static void logPrintf ( String format , String ... v ) { if ( enableLog ) { String tmp = String . format ( format , ( Object [ ] ) v ) ; logger . log ( Level . INFO , tmp ) ; } }
logPrintf prints the log with the format .
19,798
public static String escapeAssertion ( String s ) { if ( s . startsWith ( "r" ) || s . startsWith ( "p" ) ) { s = s . replaceFirst ( "\\." , "_" ) ; } String regex = "(\\|| |=|\\)|\\(|&|<|>|,|\\+|-|!|\\*|\\/)(r|p)\\." ; Pattern p = Pattern . compile ( regex ) ; Matcher m = p . matcher ( s ) ; StringBuffer sb = new StringBuffer ( ) ; while ( m . find ( ) ) { m . appendReplacement ( sb , m . group ( ) . replace ( "." , "_" ) ) ; } m . appendTail ( sb ) ; return sb . toString ( ) ; }
escapeAssertion escapes the dots in the assertion because the expression evaluation doesn t support such variable names .
19,799
public static boolean arrayEquals ( List < String > a , List < String > b ) { if ( a == null ) { a = new ArrayList < > ( ) ; } if ( b == null ) { b = new ArrayList < > ( ) ; } if ( a . size ( ) != b . size ( ) ) { return false ; } for ( int i = 0 ; i < a . size ( ) ; i ++ ) { if ( ! a . get ( i ) . equals ( b . get ( i ) ) ) { return false ; } } return true ; }
arrayEquals determines whether two string arrays are identical .