idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
30,300 | private int adjustAlpha ( int color , float factor ) { int alpha = Math . round ( Color . alpha ( color ) * factor ) ; int red = Color . red ( color ) ; int green = Color . green ( color ) ; int blue = Color . blue ( color ) ; return Color . argb ( alpha , red , green , blue ) ; } | Transparent the given color by the factor The more the factor closer to zero the more the color gets transparent | 75 | 21 |
30,301 | private JsonObject callGet ( final String urlString ) { return RetryUtils . retry ( new Callable < JsonObject > ( ) { @ Override public JsonObject call ( ) { return Json . parse ( RestClient . create ( urlString ) . withHeader ( "Authorization" , String . format ( "Bearer %s" , apiToken ) ) . withCaCertificate ( caCertificate ) . get ( ) ) . asObject ( ) ; } } , retries , NON_RETRYABLE_KEYWORDS ) ; } | Makes a REST call to Kubernetes API and returns the result JSON . | 121 | 17 |
30,302 | private SSLSocketFactory buildSslSocketFactory ( ) { try { KeyStore keyStore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; keyStore . load ( null , null ) ; keyStore . setCertificateEntry ( "ca" , generateCertificate ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; tmf . init ( keyStore ) ; SSLContext context = SSLContext . getInstance ( "TLSv1.2" ) ; context . init ( null , tmf . getTrustManagers ( ) , null ) ; return context . getSocketFactory ( ) ; } catch ( Exception e ) { throw new KubernetesClientException ( "Failure in generating SSLSocketFactory" , e ) ; } } | Builds SSL Socket Factory with the public CA Certificate from Kubernetes Master . | 181 | 17 |
30,303 | private Certificate generateCertificate ( ) throws IOException , CertificateException { InputStream caInput = null ; try { CertificateFactory cf = CertificateFactory . getInstance ( "X.509" ) ; caInput = new ByteArrayInputStream ( caCertificate . getBytes ( "UTF-8" ) ) ; return cf . generateCertificate ( caInput ) ; } finally { IOUtil . closeResource ( caInput ) ; } } | Generates CA Certificate from the default CA Cert file or from the externally provided ca - certificate property . | 91 | 20 |
30,304 | public boolean isOK ( PublicKey key ) { try { final var digester = MessageDigest . getInstance ( get ( DIGEST_KEY ) . getString ( ) ) ; final var ser = unsigned ( ) ; final var digestValue = digester . digest ( ser ) ; final var cipher = Cipher . getInstance ( key . getAlgorithm ( ) ) ; cipher . init ( Cipher . DECRYPT_MODE , key ) ; final var sigDigest = cipher . doFinal ( getSignature ( ) ) ; return Arrays . equals ( digestValue , sigDigest ) ; } catch ( Exception e ) { return false ; } } | Returns true if the license is signed and the authenticity of the signature can be checked successfully using the key . | 137 | 21 |
30,305 | private Feature [ ] featuresSorted ( Set < String > excluded ) { return this . features . values ( ) . stream ( ) . filter ( f -> ! excluded . contains ( f . name ( ) ) ) . sorted ( Comparator . comparing ( Feature :: name ) ) . toArray ( Feature [ ] :: new ) ; } | Get all the features in an array except the excluded ones in sorted order . The sorting is done on the name . | 69 | 23 |
30,306 | public byte [ ] serialized ( ) { final var nameBuffer = name . getBytes ( StandardCharsets . UTF_8 ) ; final var typeLength = Integer . BYTES ; final var nameLength = Integer . BYTES + nameBuffer . length ; final var valueLength = type . fixedSize == VARIABLE_LENGTH ? Integer . BYTES + value . length : type . fixedSize ; final var buffer = ByteBuffer . allocate ( typeLength + nameLength + valueLength ) . putInt ( type . serialized ) . putInt ( nameBuffer . length ) ; if ( type . fixedSize == VARIABLE_LENGTH ) { buffer . putInt ( value . length ) ; } buffer . put ( nameBuffer ) . put ( value ) ; return buffer . array ( ) ; } | Convert a feature to byte array . The bytes will have the following structure | 174 | 15 |
30,307 | public License read ( IOFormat format ) throws IOException { switch ( format ) { case BINARY : return License . Create . from ( ByteArrayReader . readInput ( is ) ) ; case BASE64 : return License . Create . from ( Base64 . getDecoder ( ) . decode ( ByteArrayReader . readInput ( is ) ) ) ; case STRING : return License . Create . from ( new String ( ByteArrayReader . readInput ( is ) , StandardCharsets . UTF_8 ) ) ; } throw new IllegalArgumentException ( "License format " + format + " is unknown." ) ; } | Read the license from the input assuming that the format of the license on the input has the format specified by the argument . | 131 | 24 |
30,308 | public void write ( LicenseKeyPair pair , IOFormat format ) throws IOException { switch ( format ) { case BINARY : osPrivate . write ( pair . getPrivate ( ) ) ; osPublic . write ( pair . getPublic ( ) ) ; return ; case BASE64 : osPrivate . write ( Base64 . getEncoder ( ) . encode ( pair . getPrivate ( ) ) ) ; osPublic . write ( Base64 . getEncoder ( ) . encode ( pair . getPublic ( ) ) ) ; return ; } throw new IllegalArgumentException ( "Key format " + format + " is unknown." ) ; } | Write the key pair into the output files . | 134 | 9 |
30,309 | public void write ( License license , IOFormat format ) throws IOException { switch ( format ) { case BINARY : os . write ( license . serialized ( ) ) ; return ; case BASE64 : os . write ( Base64 . getEncoder ( ) . encode ( license . serialized ( ) ) ) ; return ; case STRING : os . write ( license . toString ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ; return ; } throw new IllegalArgumentException ( "License format " + format + " is unknown" ) ; } | Write the license into the output . | 122 | 7 |
30,310 | public byte [ ] getPrivate ( ) { keyNotNull ( pair . getPrivate ( ) ) ; Key key = pair . getPrivate ( ) ; return getKeyBytes ( key ) ; } | Get the byte representation of the private key as it is returned by the underlying security library . This is NOT the byte array that contains the algorithm at the start . This is the key in raw format . | 40 | 40 |
30,311 | public byte [ ] getPublic ( ) { keyNotNull ( pair . getPublic ( ) ) ; Key key = pair . getPublic ( ) ; return getKeyBytes ( key ) ; } | Get the byte representation of the public key as it is returned by the underlying security library . This is NOT the byte array that contains the algorithm at the start . This is the key in raw format . | 40 | 40 |
30,312 | public String getMachineIdString ( ) throws NoSuchAlgorithmException , SocketException , UnknownHostException { return calculator . getMachineIdString ( useNetwork , useHostName , useArchitecture ) ; } | Get the machine id as an UUID string . | 44 | 10 |
30,313 | public boolean assertUUID ( final UUID uuid ) throws NoSuchAlgorithmException , SocketException , UnknownHostException { return calculator . assertUUID ( uuid , useNetwork , useHostName , useArchitecture ) ; } | Asserts that the current machine has the UUID . | 50 | 12 |
30,314 | @ Nonnull public String createSessionId ( @ Nonnull final String sessionId ) { return isEncodeNodeIdInSessionId ( ) ? _sessionIdFormat . createSessionId ( sessionId , _nodeIdService . getMemcachedNodeId ( ) ) : sessionId ; } | Creates a new sessionId based on the given one usually by appending a randomly selected memcached node id . If the memcachedNodes were configured using a single node without nodeId the sessionId is returned unchanged . | 61 | 47 |
30,315 | public void setNodeAvailable ( @ Nullable final String nodeId , final boolean available ) { if ( _nodeIdService != null ) { _nodeIdService . setNodeAvailable ( nodeId , available ) ; } } | Mark the given nodeId as available as specified . | 46 | 10 |
30,316 | public boolean isValidForMemcached ( final String sessionId ) { if ( isEncodeNodeIdInSessionId ( ) ) { final String nodeId = _sessionIdFormat . extractMemcachedId ( sessionId ) ; if ( nodeId == null ) { LOG . debug ( "The sessionId does not contain a nodeId so that the memcached node could not be identified." ) ; return false ; } } return true ; } | Can be used to determine if the given sessionId can be used to interact with memcached . | 94 | 20 |
30,317 | public boolean canHitMemcached ( final String sessionId ) { if ( isEncodeNodeIdInSessionId ( ) ) { final String nodeId = _sessionIdFormat . extractMemcachedId ( sessionId ) ; if ( nodeId == null ) { LOG . debug ( "The sessionId does not contain a nodeId so that the memcached node could not be identified." ) ; return false ; } if ( ! _nodeIdService . isNodeAvailable ( nodeId ) ) { LOG . debug ( "The node " + nodeId + " is not available, therefore " + sessionId + " cannot be loaded from this memcached." ) ; return false ; } } return true ; } | Can be used to determine if the given sessionId can be used to interact with memcached . This also checks if the related memcached is available . | 149 | 32 |
30,318 | public String setNodeAvailableForSessionId ( final String sessionId , final boolean available ) { if ( _nodeIdService != null && isEncodeNodeIdInSessionId ( ) ) { final String nodeId = _sessionIdFormat . extractMemcachedId ( sessionId ) ; if ( nodeId != null ) { _nodeIdService . setNodeAvailable ( nodeId , available ) ; return nodeId ; } else { LOG . warn ( "Got sessionId without nodeId: " + sessionId ) ; } } return null ; } | Mark the memcached node encoded in the given sessionId as available or not . If nodeIds shall not be encoded in the sessionId or if the given sessionId does not contain a nodeId no action will be taken . | 114 | 47 |
30,319 | public String changeSessionIdForTomcatFailover ( @ Nonnull final String sessionId , final String jvmRoute ) { final String newSessionId = jvmRoute != null && ! jvmRoute . trim ( ) . isEmpty ( ) ? _sessionIdFormat . changeJvmRoute ( sessionId , jvmRoute ) : _sessionIdFormat . stripJvmRoute ( sessionId ) ; if ( isEncodeNodeIdInSessionId ( ) ) { final String nodeId = _sessionIdFormat . extractMemcachedId ( newSessionId ) ; if ( _failoverNodeIds != null && _failoverNodeIds . contains ( nodeId ) ) { final String newNodeId = _nodeIdService . getAvailableNodeId ( nodeId ) ; if ( newNodeId != null ) { return _sessionIdFormat . createNewSessionId ( newSessionId , newNodeId ) ; } } } return newSessionId ; } | Changes the sessionId by setting the given jvmRoute and replacing the memcachedNodeId if it s currently set to a failoverNodeId . | 202 | 31 |
30,320 | public List < URI > getCouchbaseBucketURIs ( ) { if ( ! isCouchbaseBucketConfig ( ) ) throw new IllegalStateException ( "This is not a couchbase bucket configuration." ) ; final List < URI > result = new ArrayList < URI > ( _address2Ids . size ( ) ) ; final Matcher matcher = COUCHBASE_BUCKET_NODE_PATTERN . matcher ( _memcachedNodes ) ; while ( matcher . find ( ) ) { try { result . add ( new URI ( matcher . group ( ) ) ) ; } catch ( final URISyntaxException e ) { throw new RuntimeException ( e ) ; } } return result ; } | Returns a list of couchbase REST interface uris if the current configuration is a couchbase bucket configuration . | 160 | 21 |
30,321 | public void setMaxActiveSessions ( final int max ) { final int oldMaxActiveSessions = _maxActiveSessions ; _maxActiveSessions = max ; support . firePropertyChange ( "maxActiveSessions" , Integer . valueOf ( oldMaxActiveSessions ) , Integer . valueOf ( _maxActiveSessions ) ) ; } | Set the maximum number of active Sessions allowed or - 1 for no limit . | 74 | 15 |
30,322 | public void modifyingRequest ( final String requestId ) { if ( _log . isDebugEnabled ( ) ) { _log . debug ( "Registering modifying request: " + requestId ) ; } incrementOrPut ( _blacklist , requestId ) ; _readOnlyRequests . remove ( requestId ) ; } | Registers the given requestURI as a modifying request which can be seen as a blacklist for readonly requests . There s a limit on number and time for modifying requests beeing stored . | 66 | 37 |
30,323 | public boolean isReadOnlyRequest ( final String requestId ) { if ( _log . isDebugEnabled ( ) ) { _log . debug ( "Asked for readonly request: " + requestId + " (" + _readOnlyRequests . containsKey ( requestId ) + ")" ) ; } // TODO: add some threshold return _readOnlyRequests . containsKey ( requestId ) ; } | Determines if the given requestURI is a readOnly request and not blacklisted as a modifying request . | 85 | 22 |
30,324 | @ Override public ConcurrentMap < String , Object > deserializeAttributes ( final byte [ ] in ) { final InputStreamReader inputStream = new InputStreamReader ( new ByteArrayInputStream ( in ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "deserialize the stream" ) ; } try { return deserializer . deserializeInto ( inputStream , new ConcurrentHashMap < String , Object > ( ) ) ; } catch ( final RuntimeException e ) { LOG . warn ( "Caught Exception deserializing JSON " + e ) ; throw new TranscoderDeserializationException ( e ) ; } } | Return the deserialized map | 142 | 6 |
30,325 | protected void onBackupWithoutLoadedSession ( @ Nonnull final String sessionId , @ Nonnull final String requestId , @ Nonnull final BackupSessionService backupSessionService ) { if ( ! _sessionIdFormat . isValid ( sessionId ) ) { return ; } try { final long start = System . currentTimeMillis ( ) ; final String validityKey = _sessionIdFormat . createValidityInfoKeyName ( sessionId ) ; final SessionValidityInfo validityInfo = loadSessionValidityInfoForValidityKey ( validityKey ) ; if ( validityInfo == null ) { _log . warn ( "Found no validity info for session id " + sessionId ) ; return ; } final int maxInactiveInterval = validityInfo . getMaxInactiveInterval ( ) ; final byte [ ] validityData = encode ( maxInactiveInterval , System . currentTimeMillis ( ) , System . currentTimeMillis ( ) ) ; // fix for #88, along with the change in session.getMemcachedExpirationTimeToSet final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval ; final Future < Boolean > validityResult = _storage . set ( validityKey , toMemcachedExpiration ( expiration ) , validityData ) ; if ( ! _manager . isSessionBackupAsync ( ) ) { validityResult . get ( _manager . getSessionBackupTimeout ( ) , TimeUnit . MILLISECONDS ) ; } /* * - ping session * - ping session backup * - save validity backup */ final Callable < ? > backupSessionTask = new OnBackupWithoutLoadedSessionTask ( sessionId , _storeSecondaryBackup , validityKey , validityData , maxInactiveInterval ) ; _executor . submit ( backupSessionTask ) ; if ( _log . isDebugEnabled ( ) ) { _log . debug ( "Stored session validity info for session " + sessionId ) ; } _stats . registerSince ( NON_STICKY_ON_BACKUP_WITHOUT_LOADED_SESSION , start ) ; } catch ( final Throwable e ) { _log . warn ( "An error when trying to load/update validity info." , e ) ; } } | Is invoked for the backup of a non - sticky session that was not accessed for the current request . | 477 | 20 |
30,326 | protected void onAfterBackupSession ( @ Nonnull final MemcachedBackupSession session , final boolean backupWasForced , @ Nonnull final Future < BackupResult > result , @ Nonnull final String requestId , @ Nonnull final BackupSessionService backupSessionService ) { if ( ! _sessionIdFormat . isValid ( session . getIdInternal ( ) ) ) { return ; } try { final long start = System . currentTimeMillis ( ) ; final int maxInactiveInterval = session . getMaxInactiveInterval ( ) ; final byte [ ] validityData = encode ( maxInactiveInterval , session . getLastAccessedTimeInternal ( ) , session . getThisAccessedTimeInternal ( ) ) ; final String validityKey = _sessionIdFormat . createValidityInfoKeyName ( session . getIdInternal ( ) ) ; // fix for #88, along with the change in session.getMemcachedExpirationTimeToSet final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval ; final Future < Boolean > validityResult = _storage . set ( validityKey , toMemcachedExpiration ( expiration ) , validityData ) ; if ( ! _manager . isSessionBackupAsync ( ) ) { // TODO: together with session backup wait not longer than sessionBackupTimeout. // Details: Now/here we're waiting the whole session backup timeout, even if (perhaps) some time // was spent before when waiting for session backup result. // For sync session backup it would be better to set both the session data and // validity info and afterwards wait for both results (but in sum no longer than sessionBackupTimeout) validityResult . get ( _manager . getSessionBackupTimeout ( ) , TimeUnit . MILLISECONDS ) ; } if ( _log . isDebugEnabled ( ) ) { _log . debug ( "Stored session validity info for session " + session . getIdInternal ( ) ) ; } /* The following task are performed outside of the request thread (includes waiting for the backup result): * - ping session if the backup was skipped (depends on the backup result) * - save secondary session backup if session was modified (backup not skipped) * - ping secondary session backup if the backup was skipped * - save secondary validity backup */ final boolean pingSessionIfBackupWasSkipped = ! backupWasForced ; final boolean performAsyncTasks = pingSessionIfBackupWasSkipped || _storeSecondaryBackup ; if ( performAsyncTasks ) { final Callable < ? > backupSessionTask = new OnAfterBackupSessionTask ( session , result , pingSessionIfBackupWasSkipped , backupSessionService , _storeSecondaryBackup , validityKey , validityData ) ; _executor . submit ( backupSessionTask ) ; } _stats . registerSince ( NON_STICKY_AFTER_BACKUP , start ) ; } catch ( final Throwable e ) { _log . warn ( "An error occurred during onAfterBackupSession." , e ) ; } } | Is invoked after the backup of the session is initiated it s represented by the provided backupResult . The requestId is identifying the request . | 649 | 27 |
30,327 | protected void onAfterDeleteFromMemcached ( @ Nonnull final String sessionId ) { final long start = System . currentTimeMillis ( ) ; final String validityInfoKey = _sessionIdFormat . createValidityInfoKeyName ( sessionId ) ; _storage . delete ( validityInfoKey ) ; if ( _storeSecondaryBackup ) { try { _storage . delete ( _sessionIdFormat . createBackupKey ( sessionId ) ) ; _storage . delete ( _sessionIdFormat . createBackupKey ( validityInfoKey ) ) ; } catch ( Exception e ) { _log . info ( "Could not delete backup data for session " + sessionId + " (not critical, data will be evicted by memcached automatically)." , e ) ; } } _stats . registerSince ( NON_STICKY_AFTER_DELETE_FROM_MEMCACHED , start ) ; } | Invoked after a non - sticky session is removed from memcached . | 196 | 15 |
30,328 | void startInternal ( ) throws LifecycleException { _log . info ( getClass ( ) . getSimpleName ( ) + " starts initialization... (configured" + " nodes definition " + _memcachedNodes + ", failover nodes " + _failoverNodes + ")" ) ; _statistics = Statistics . create ( _enableStatistics ) ; _memcachedNodesManager = createMemcachedNodesManager ( _memcachedNodes , _failoverNodes ) ; if ( _storage == null ) { _storage = createStorageClient ( _memcachedNodesManager , _statistics ) ; } final String sessionCookieName = _manager . getSessionCookieName ( ) ; _currentRequest = new CurrentRequest ( ) ; _trackingHostValve = createRequestTrackingHostValve ( sessionCookieName , _currentRequest ) ; final Context context = _manager . getContext ( ) ; context . getParent ( ) . getPipeline ( ) . addValve ( _trackingHostValve ) ; _trackingContextValve = createRequestTrackingContextValve ( sessionCookieName ) ; context . getPipeline ( ) . addValve ( _trackingContextValve ) ; initNonStickyLockingMode ( _memcachedNodesManager ) ; _transcoderService = createTranscoderService ( _statistics ) ; _backupSessionService = new BackupSessionService ( _transcoderService , _sessionBackupAsync , _sessionBackupTimeout , _backupThreadCount , _storage , _memcachedNodesManager , _statistics ) ; _log . info ( "--------\n- " + getClass ( ) . getSimpleName ( ) + " finished initialization:" + "\n- sticky: " + _sticky + "\n- operation timeout: " + _operationTimeout + "\n- node ids: " + _memcachedNodesManager . getPrimaryNodeIds ( ) + "\n- failover node ids: " + _memcachedNodesManager . getFailoverNodeIds ( ) + "\n- storage key prefix: " + _memcachedNodesManager . getStorageKeyFormat ( ) . prefix + "\n- locking mode: " + _lockingMode + " (expiration: " + _lockExpiration + "s)" + "\n--------" ) ; } | Initialize this manager . | 514 | 5 |
30,329 | public Future < BackupResult > backupSession ( final String sessionId , final boolean sessionIdChanged , final String requestId ) { if ( ! _enabled . get ( ) ) { return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } final MemcachedBackupSession msmSession = _manager . getSessionInternal ( sessionId ) ; if ( msmSession == null ) { if ( _log . isDebugEnabled ( ) ) _log . debug ( "No session found in session map for " + sessionId ) ; if ( ! _sticky ) { // Issue 116/137: Only notify the lockingStrategy if the session was loaded and has not been removed/invalidated if ( ! _invalidSessionsCache . containsKey ( sessionId ) ) { _lockingStrategy . onBackupWithoutLoadedSession ( sessionId , requestId , _backupSessionService ) ; } } return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } if ( ! msmSession . isValidInternal ( ) ) { if ( _log . isDebugEnabled ( ) ) _log . debug ( "Non valid session found in session map for " + sessionId ) ; return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } if ( ! _sticky ) { synchronized ( _manager . getSessionsInternal ( ) ) { // if another thread in the meantime retrieved the session // we must not remove it as this would case session data loss // for the other request if ( msmSession . releaseReference ( ) > 0 ) { if ( _log . isDebugEnabled ( ) ) _log . debug ( "Session " + sessionId + " is still used by another request, skipping backup and (optional) lock handling/release." ) ; return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } msmSession . passivate ( ) ; _manager . removeInternal ( msmSession , false ) ; } } final boolean force = sessionIdChanged || msmSession . isSessionIdChanged ( ) || ! _sticky && ( msmSession . getSecondsSinceLastBackup ( ) >= msmSession . getMaxInactiveInterval ( ) ) ; final Future < BackupResult > result = _backupSessionService . backupSession ( msmSession , force ) ; if ( ! _sticky ) { _lockingStrategy . onAfterBackupSession ( msmSession , force , result , requestId , _backupSessionService ) ; } return result ; } | Backup the session for the provided session id in memcached if the session was modified or if the session needs to be relocated . In non - sticky session - mode the session should not be loaded from memcached for just storing it again but only metadata should be updated . | 546 | 56 |
30,330 | @ Nonnull public String createSessionId ( @ Nonnull final String sessionId , @ Nullable final String memcachedId ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Creating new session id with orig id '" + sessionId + "' and memcached id '" + memcachedId + "'." ) ; } if ( memcachedId == null ) { return sessionId ; } final int idx = sessionId . indexOf ( ' ' ) ; if ( idx < 0 ) { return sessionId + "-" + memcachedId ; } else { return sessionId . substring ( 0 , idx ) + "-" + memcachedId + sessionId . substring ( idx ) ; } } | Create a session id including the provided memcachedId . | 162 | 12 |
30,331 | @ CheckForNull public String extractMemcachedId ( @ Nonnull final String sessionId ) { final int idxDash = sessionId . indexOf ( ' ' ) ; if ( idxDash < 0 ) { return null ; } final int idxDot = sessionId . indexOf ( ' ' ) ; if ( idxDot < 0 ) { return sessionId . substring ( idxDash + 1 ) ; } else if ( idxDot < idxDash ) /* The dash was part of the jvmRoute */ { return null ; } else { return sessionId . substring ( idxDash + 1 , idxDot ) ; } } | Extract the memcached id from the given session id . | 143 | 13 |
30,332 | @ CheckForNull public String extractJvmRoute ( @ Nonnull final String sessionId ) { final int idxDot = sessionId . indexOf ( ' ' ) ; return idxDot < 0 ? null : sessionId . substring ( idxDot + 1 ) ; } | Extract the jvm route from the given session id if existing . | 62 | 14 |
30,333 | @ Nonnull public String stripJvmRoute ( @ Nonnull final String sessionId ) { final int idxDot = sessionId . indexOf ( ' ' ) ; return idxDot < 0 ? sessionId : sessionId . substring ( 0 , idxDot ) ; } | Remove the jvm route from the given session id if existing . | 62 | 13 |
30,334 | public Future < BackupResult > backupSession ( final String sessionId , final boolean sessionIdChanged , final String requestId ) { final MemcachedBackupSession session = _manager . getSessionInternal ( sessionId ) ; if ( session == null ) { if ( _log . isDebugEnabled ( ) ) _log . debug ( "No session found in session map for " + sessionId ) ; return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } _log . info ( "Serializing session data for session " + session . getIdInternal ( ) ) ; final long startSerialization = System . currentTimeMillis ( ) ; final byte [ ] data = _transcoderService . serializeAttributes ( ( MemcachedBackupSession ) session , ( ( MemcachedBackupSession ) session ) . getAttributesFiltered ( ) ) ; _log . info ( String . format ( "Serializing %1$,.3f kb session data for session %2$s took %3$d ms." , ( double ) data . length / 1000 , session . getIdInternal ( ) , System . currentTimeMillis ( ) - startSerialization ) ) ; _sessionData . put ( session . getIdInternal ( ) , data ) ; _statistics . registerSince ( ATTRIBUTES_SERIALIZATION , startSerialization ) ; _statistics . register ( CACHED_DATA_SIZE , data . length ) ; return new SimpleFuture < BackupResult > ( new BackupResult ( BackupResultStatus . SUCCESS ) ) ; } | Store the provided session in memcached if the session was modified or if the session needs to be relocated . | 335 | 22 |
30,335 | private boolean filterAttribute ( final String name ) { if ( this . manager == null ) { throw new IllegalStateException ( "There's no manager set." ) ; } final Pattern pattern = ( ( SessionManager ) manager ) . getMemcachedSessionService ( ) . getSessionAttributePattern ( ) ; if ( pattern == null ) { return true ; } return pattern . matcher ( name ) . matches ( ) ; } | Check whether the given attribute name matches our name pattern and shall be stored in memcached . | 88 | 19 |
30,336 | int getMemcachedExpirationTime ( ) { if ( ! _sticky ) { throw new IllegalStateException ( "The memcached expiration time cannot be determined in non-sticky mode." ) ; } if ( _lastMemcachedExpirationTime == 0 ) { return 0 ; } final long timeIdleInMillis = _lastBackupTime == 0 ? 0 : System . currentTimeMillis ( ) - _lastBackupTime ; /* rounding is just for tests, as they are using actually seconds for testing. * with a default setup 1 second difference wouldn't matter... */ final int timeIdle = Math . round ( ( float ) timeIdleInMillis / 1000L ) ; final int expirationTime = _lastMemcachedExpirationTime - timeIdle ; /* prevent negative expiration times. * because 0 means no expiration at all, we use 1 as min value here */ return max ( 1 , expirationTime ) ; } | Gets the time in seconds when this session will expire in memcached . If the session was stored in memcached with expiration 0 this method will just return 0 . | 201 | 35 |
30,337 | public ConcurrentMap < String , Object > getAttributesFiltered ( ) { if ( this . manager == null ) { throw new IllegalStateException ( "There's no manager set." ) ; } final Pattern pattern = ( ( SessionManager ) manager ) . getMemcachedSessionService ( ) . getSessionAttributePattern ( ) ; final ConcurrentMap < String , Object > attributes = getAttributesInternal ( ) ; if ( pattern == null ) { return attributes ; } final ConcurrentMap < String , Object > result = new ConcurrentHashMap < String , Object > ( attributes . size ( ) ) ; for ( final Map . Entry < String , Object > entry : attributes . entrySet ( ) ) { if ( pattern . matcher ( entry . getKey ( ) ) . matches ( ) ) { result . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return result ; } | Filter map of attributes using our name pattern . | 192 | 9 |
30,338 | public V put ( final K key , final V value ) { synchronized ( _map ) { final ManagedItem < V > previous = _map . put ( key , new ManagedItem < V > ( value , System . currentTimeMillis ( ) ) ) ; while ( _map . size ( ) > _size ) { _map . remove ( _map . keySet ( ) . iterator ( ) . next ( ) ) ; } return previous != null ? previous . _value : null ; } } | Put the key and value . | 106 | 6 |
30,339 | public V get ( final K key ) { synchronized ( _map ) { final ManagedItem < V > item = _map . get ( key ) ; if ( item == null ) { return null ; } if ( _ttl > - 1 && System . currentTimeMillis ( ) - item . _insertionTime > _ttl ) { _map . remove ( key ) ; return null ; } return item . _value ; } } | Returns the value that was stored to the given key . | 93 | 11 |
30,340 | public List < K > getKeys ( ) { synchronized ( _map ) { return new java . util . ArrayList < K > ( _map . keySet ( ) ) ; } } | The list of all keys whose order is the order in which its entries were last accessed from least - recently accessed to most - recently . | 39 | 27 |
30,341 | public List < K > getKeysSortedByValue ( final Comparator < V > comparator ) { synchronized ( _map ) { @ SuppressWarnings ( "unchecked" ) final Entry < K , ManagedItem < V > > [ ] a = _map . entrySet ( ) . toArray ( new Map . Entry [ _map . size ( ) ] ) ; final Comparator < Entry < K , ManagedItem < V > > > c = new Comparator < Entry < K , ManagedItem < V > > > ( ) { @ Override public int compare ( final Entry < K , ManagedItem < V > > o1 , final Entry < K , ManagedItem < V > > o2 ) { return comparator . compare ( o1 . getValue ( ) . _value , o2 . getValue ( ) . _value ) ; } } ; Arrays . sort ( a , c ) ; return new LRUCache . ArrayList < K , V > ( a ) ; } } | The keys sorted by the given value comparator . | 217 | 10 |
30,342 | public boolean isNodeAvailable ( @ Nonnull final K key ) { final ManagedItem < Boolean > item = _map . get ( key ) ; if ( item == null ) { return updateIsNodeAvailable ( key ) ; } else if ( isExpired ( item ) ) { _map . remove ( key ) ; return updateIsNodeAvailable ( key ) ; } else { return item . _value ; } } | Determines if the node is available . If it s not cached it s loaded from the cache loader . | 87 | 22 |
30,343 | public Set < K > getUnavailableNodes ( ) { final Set < K > result = new HashSet < K > ( ) ; for ( final Map . Entry < K , ManagedItem < Boolean > > entry : _map . entrySet ( ) ) { if ( ! entry . getValue ( ) . _value . booleanValue ( ) && ! isExpired ( entry . getValue ( ) ) ) { result . add ( entry . getKey ( ) ) ; } } return result ; } | A set of nodes that are stored as unavailable . | 106 | 10 |
30,344 | @ GET @ Path ( "/health" ) @ Produces ( MediaType . APPLICATION_JSON ) public HealthStatus health ( ) throws ExecutionException , InterruptedException { final HealthStatus status = new HealthStatus ( ) ; final Future < HealthDetails > dbStatus = healthDBService . dbStatus ( ) ; final Future < List < HealthDetails > > networkStatus = healthNetworkService . networkStatus ( ) ; status . add ( dbStatus . get ( ) ) ; networkStatus . get ( ) . forEach ( status :: add ) ; return status ; } | Get health status | 118 | 3 |
30,345 | @ Produces @ LoggedIn public String extractUsername ( ) { final KeycloakPrincipal principal = ( KeycloakPrincipal ) httpServletRequest . getUserPrincipal ( ) ; if ( principal != null ) { logger . debug ( "Running with Keycloak context" ) ; KeycloakSecurityContext kcSecurityContext = principal . getKeycloakSecurityContext ( ) ; return kcSecurityContext . getToken ( ) . getPreferredUsername ( ) ; } logger . debug ( "Running outside of Keycloak context" ) ; final String basicUsername = HttpBasicHelper . extractUsernameAndPasswordFromBasicHeader ( httpServletRequest ) [ 0 ] ; if ( ! basicUsername . isEmpty ( ) ) { logger . debug ( "running HttpBasic auth" ) ; return basicUsername ; } logger . debug ( "Running without any Auth context" ) ; return "admin" ; // by default, we are admin! } | Extract the username to be used in multiple queries | 206 | 10 |
30,346 | public static String extractAeroGearSenderInformation ( final HttpServletRequest request ) { String client = request . getHeader ( "aerogear-sender" ) ; if ( hasValue ( client ) ) { return client ; } // if there was no usage of our custom header, we simply return the user-agent value return request . getHeader ( "user-agent" ) ; } | Reads the aerogear - sender header to check if an AeroGear Sender client was used . If the header value is NULL the value of the standard user - agent header is returned | 84 | 38 |
30,347 | @ PUT @ Path ( "/{androidID}" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response updateAndroidVariant ( @ PathParam ( "pushAppID" ) String id , @ PathParam ( "androidID" ) String androidID , AndroidVariant updatedAndroidApplication ) { AndroidVariant androidVariant = ( AndroidVariant ) variantService . findByVariantID ( androidID ) ; if ( androidVariant != null ) { // some validation try { validateModelClass ( updatedAndroidApplication ) ; } catch ( ConstraintViolationException cve ) { logger . info ( "Unable to update Android Variant '{}'" , androidVariant . getVariantID ( ) ) ; logger . debug ( "Details: {}" , cve ) ; // Build and return the 400 (Bad Request) response ResponseBuilder builder = createBadRequestResponse ( cve . getConstraintViolations ( ) ) ; return builder . build ( ) ; } // apply updated data: androidVariant . setGoogleKey ( updatedAndroidApplication . getGoogleKey ( ) ) ; androidVariant . setProjectNumber ( updatedAndroidApplication . getProjectNumber ( ) ) ; androidVariant . setName ( updatedAndroidApplication . getName ( ) ) ; androidVariant . setDescription ( updatedAndroidApplication . getDescription ( ) ) ; logger . trace ( "Updating Android Variant '{}'" , androidID ) ; variantService . updateVariant ( androidVariant ) ; return Response . ok ( androidVariant ) . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . entity ( "Could not find requested Variant" ) . build ( ) ; } | Update Android Variant | 372 | 3 |
30,348 | public static boolean isValidDeviceTokenForVariant ( final String deviceToken , final VariantType type ) { switch ( type ) { case IOS : return IOS_DEVICE_TOKEN . matcher ( deviceToken ) . matches ( ) ; case ANDROID : return ANDROID_DEVICE_TOKEN . matcher ( deviceToken ) . matches ( ) ; case WINDOWS_WNS : return WINDOWS_DEVICE_TOKEN . matcher ( deviceToken ) . matches ( ) ; } return false ; } | Helper to run quick up - front validations . | 114 | 10 |
30,349 | private boolean tryToDispatchTokens ( MessageHolderWithTokens msg ) { try { dispatchTokensEvent . fire ( msg ) ; return true ; } catch ( MessageDeliveryException e ) { Throwable cause = e . getCause ( ) ; if ( isQueueFullException ( cause ) ) { return false ; } throw e ; } } | Tries to dispatch tokens ; returns true if tokens were successfully queued . Detects when queue is full and in that case returns false . | 69 | 28 |
30,350 | private int delete ( String urlS ) throws IOException { URL url = new URL ( urlS ) ; HttpURLConnection conn = prepareAuthorizedConnection ( url ) ; conn . setRequestMethod ( "DELETE" ) ; conn . connect ( ) ; return conn . getResponseCode ( ) ; } | Sends DELETE HTTP request to provided URL . Request is authorized using Google API key . | 65 | 19 |
30,351 | private String get ( String urlS ) throws IOException { URL url = new URL ( urlS ) ; HttpURLConnection conn = prepareAuthorizedConnection ( url ) ; conn . setRequestMethod ( "GET" ) ; // Read response StringBuilder result = new StringBuilder ( ) ; try ( BufferedReader rd = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ) { String line ; while ( ( line = rd . readLine ( ) ) != null ) { result . append ( line ) ; } } return result . toString ( ) ; } | Sends GET HTTP request to provided URL . Request is authorized using Google API key . | 127 | 17 |
30,352 | public static boolean isCategoryOnlyCriteria ( final Criteria criteria ) { return isEmpty ( criteria . getAliases ( ) ) && // we are not subscribing to alias topic (yet) isEmpty ( criteria . getDeviceTypes ( ) ) && // we are not subscribing to device type topic (yet) ! isEmpty ( criteria . getCategories ( ) ) ; // BUT! categories are mapped to topics } | Helper method to check if only categories are applied . Useful in FCM land where we use topics | 85 | 19 |
30,353 | public static boolean isEmptyCriteria ( final Criteria criteria ) { return isEmpty ( criteria . getAliases ( ) ) && isEmpty ( criteria . getDeviceTypes ( ) ) && isEmpty ( criteria . getCategories ( ) ) ; } | Helper method to check if all criteria are empty . Useful in FCM land where we use topics . | 52 | 20 |
30,354 | @ Override public DashboardData loadDashboardData ( ) { long totalApps = totalApplicationNumber ( ) ; long totalDevices = totalDeviceNumber ( ) ; long totalMessages = totalMessages ( ) ; final DashboardData data = new DashboardData ( ) ; data . setApplications ( totalApps ) ; data . setDevices ( totalDevices ) ; data . setMessages ( totalMessages ) ; return data ; } | Receives the dashboard data for the given user | 94 | 10 |
30,355 | @ Override public List < ApplicationVariant > getVariantsWithWarnings ( ) { final List < String > warningIDs = flatPushMessageInformationDao . findVariantIDsWithWarnings ( ) ; if ( warningIDs . isEmpty ( ) ) { return Collections . emptyList ( ) ; } return wrapApplicationVariant ( pushApplicationDao . findByVariantIds ( warningIDs ) ) ; } | Loads all the Variant objects where we did notice some failures on sending for the given user | 90 | 18 |
30,356 | @ GET @ Path ( "/application/{id}" ) @ Produces ( MediaType . APPLICATION_JSON ) public Response pushMessageInformationPerApplication ( @ PathParam ( "id" ) String id , @ QueryParam ( "page" ) Integer page , @ QueryParam ( "per_page" ) Integer pageSize , @ QueryParam ( "sort" ) String sorting , @ QueryParam ( "search" ) String search ) { pageSize = parsePageSize ( pageSize ) ; if ( page == null ) { page = 0 ; } if ( id == null ) { return Response . status ( Response . Status . NOT_FOUND ) . entity ( "Could not find requested information" ) . build ( ) ; } PageResult < FlatPushMessageInformation , MessageMetrics > pageResult = metricsService . findAllFlatsForPushApplication ( id , search , isAscendingOrder ( sorting ) , page , pageSize ) ; return Response . ok ( pageResult . getResultList ( ) ) . header ( "total" , pageResult . getAggregate ( ) . getCount ( ) ) . header ( "receivers" , "0" ) . header ( "appOpenedCounter" , pageResult . getAggregate ( ) . getAppOpenedCounter ( ) ) . build ( ) ; } | GET info about submitted push messages for the given Push Application | 278 | 11 |
30,357 | public static String tryGetGlobalProperty ( String key , String defaultValue ) { try { String value = System . getenv ( formatEnvironmentVariable ( key ) ) ; if ( value == null ) { value = tryGetProperty ( key , defaultValue ) ; } return value ; } catch ( SecurityException e ) { logger . error ( "Could not get value of global property {} due to SecurityManager. Using default value." , key , e ) ; return defaultValue ; } } | Get a global string property . This method will first try to get the value from an environment variable and if that does not exist it will look up a system property . | 99 | 33 |
30,358 | public static Integer tryGetGlobalIntegerProperty ( String key , Integer defaultValue ) { try { String value = System . getenv ( formatEnvironmentVariable ( key ) ) ; if ( value == null ) { return tryGetIntegerProperty ( key , defaultValue ) ; } else { return Integer . parseInt ( value ) ; } } catch ( SecurityException | NumberFormatException e ) { logger . error ( "Could not get value of global property {} due to SecurityManager. Using default value." , key , e ) ; return defaultValue ; } } | Get a global integer property . This method will first try to get the value from an environment variable and if that does not exist it will look up a system property . | 113 | 33 |
30,359 | @ GET @ Produces ( MediaType . APPLICATION_JSON ) public Response listAllWindowsVariationsForPushApp ( @ PathParam ( "pushAppID" ) String pushApplicationID ) { final PushApplication application = getSearch ( ) . findByPushApplicationIDForDeveloper ( pushApplicationID ) ; return Response . ok ( getVariants ( application ) ) . build ( ) ; } | List Windows Variants for Push Application | 82 | 7 |
30,360 | @ PUT @ Path ( "/{windowsID}" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response updateWindowsVariant ( @ PathParam ( "windowsID" ) String windowsID , WindowsVariant updatedWindowsVariant ) { WindowsVariant windowsVariant = ( WindowsVariant ) variantService . findByVariantID ( windowsID ) ; if ( windowsVariant != null ) { // some validation try { validateModelClass ( updatedWindowsVariant ) ; } catch ( ConstraintViolationException cve ) { logger . info ( "Unable to update Windows Variant '{}'" , windowsVariant . getVariantID ( ) ) ; logger . debug ( "Details: {}" , cve ) ; // Build and return the 400 (Bad Request) response Response . ResponseBuilder builder = createBadRequestResponse ( cve . getConstraintViolations ( ) ) ; return builder . build ( ) ; } // apply updated data: if ( windowsVariant instanceof WindowsWNSVariant ) { WindowsWNSVariant windowsWNSVariant = ( WindowsWNSVariant ) windowsVariant ; windowsWNSVariant . setClientSecret ( ( ( WindowsWNSVariant ) updatedWindowsVariant ) . getClientSecret ( ) ) ; windowsWNSVariant . setSid ( ( ( WindowsWNSVariant ) updatedWindowsVariant ) . getSid ( ) ) ; } windowsVariant . setName ( updatedWindowsVariant . getName ( ) ) ; windowsVariant . setDescription ( updatedWindowsVariant . getDescription ( ) ) ; logger . trace ( "Updating Windows Variant '{}'" , windowsVariant . getVariantID ( ) ) ; variantService . updateVariant ( windowsVariant ) ; return Response . ok ( windowsVariant ) . build ( ) ; } return Response . status ( Response . Status . NOT_FOUND ) . entity ( "Could not find requested Variant" ) . build ( ) ; } | Update Windows Variant | 436 | 3 |
30,361 | protected void sendNonTransacted ( Destination destination , Serializable message ) { send ( destination , message , null , null , false ) ; } | Sends message to the destination in non - transactional manner . | 29 | 13 |
30,362 | protected void sendTransacted ( Destination destination , Serializable message ) { send ( destination , message , null , null , true ) ; } | Sends message to the destination in transactional manner . | 28 | 11 |
30,363 | protected void sendNonTransacted ( Destination destination , Serializable message , String propertyName , String propertValue ) { send ( destination , message , propertyName , propertValue , false ) ; } | Sends message to destination with given JMS message property name and value in non - transactional manner . | 41 | 21 |
30,364 | protected void sendTransacted ( Destination destination , Serializable message , String propertyName , String propertValue ) { send ( destination , message , propertyName , propertValue , true ) ; } | Sends message to destination with given JMS message property name and value in transactional manner . | 40 | 19 |
30,365 | public void disconnectOnChange ( @ Observes final iOSVariantUpdateEvent iOSVariantUpdateEvent ) { final iOSVariant variant = iOSVariantUpdateEvent . getiOSVariant ( ) ; final String connectionKey = extractConnectionKey ( variant ) ; final ApnsClient client = apnsClientExpiringMap . remove ( connectionKey ) ; logger . debug ( "Removed client from cache for {}" , variant . getVariantID ( ) ) ; if ( client != null ) { tearDownApnsHttp2Connection ( client ) ; } } | Receives iOS variant change event to remove client from the cache and also tear down the connection . | 115 | 20 |
30,366 | @ Override public ResultsStream . QueryBuilder < String > findAllDeviceTokenForVariantIDByCriteria ( String variantID , List < String > categories , List < String > aliases , List < String > deviceTypes , int maxResults , String lastTokenFromPreviousBatch ) { return installationDao . findAllDeviceTokenForVariantIDByCriteria ( variantID , categories , aliases , deviceTypes , maxResults , lastTokenFromPreviousBatch , false ) ; } | Finder for send used for Android and iOS clients | 101 | 10 |
30,367 | @ GET @ Path ( "/{installationID}" ) @ Produces ( MediaType . APPLICATION_JSON ) public Response findInstallation ( @ PathParam ( "variantID" ) String variantId , @ PathParam ( "installationID" ) String installationId ) { Installation installation = clientInstallationService . findById ( installationId ) ; if ( installation == null ) { return Response . status ( Response . Status . NOT_FOUND ) . entity ( "Could not find requested Installation" ) . build ( ) ; } return Response . ok ( installation ) . build ( ) ; } | Get Installation of specified Variant | 123 | 5 |
30,368 | @ PUT @ Path ( "/{installationID}" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response updateInstallation ( Installation entity , @ PathParam ( "variantID" ) String variantId , @ PathParam ( "installationID" ) String installationId ) { Installation installation = clientInstallationService . findById ( installationId ) ; if ( installation == null ) { return Response . status ( Response . Status . NOT_FOUND ) . entity ( "Could not find requested Installation" ) . build ( ) ; } clientInstallationService . updateInstallation ( installation , entity ) ; return Response . noContent ( ) . build ( ) ; } | Update Installation of specified Variant | 151 | 5 |
30,369 | @ GET @ Path ( "/{variantId}/installations/" ) @ Produces ( MediaType . APPLICATION_JSON ) @ GZIP public Response exportInstallations ( @ PathParam ( "variantId" ) String variantId ) { return Response . ok ( getSearch ( ) . findAllInstallationsByVariantForDeveloper ( variantId , 0 , Integer . MAX_VALUE , null ) . getResultList ( ) ) . build ( ) ; } | Endpoint for exporting as JSON file device installations for a given variant . Only Keycloak authenticated can access it | 99 | 22 |
30,370 | private void processFCM ( AndroidVariant androidVariant , List < String > pushTargets , Message fcmMessage , ConfigurableFCMSender sender ) throws IOException { // push targets can be registration IDs OR topics (starting /topic/), but they can't be mixed. if ( pushTargets . get ( 0 ) . startsWith ( Constants . TOPIC_PREFIX ) ) { // perform the topic delivery for ( String topic : pushTargets ) { logger . info ( String . format ( "Sent push notification to FCM topic: %s" , topic ) ) ; Result result = sender . sendNoRetry ( fcmMessage , topic ) ; logger . trace ( "Response from FCM topic request: {}" , result ) ; } } else { logger . info ( String . format ( "Sent push notification to FCM Server for %d registrationIDs" , pushTargets . size ( ) ) ) ; MulticastResult multicastResult = sender . sendNoRetry ( fcmMessage , pushTargets ) ; logger . trace ( "Response from FCM request: {}" , multicastResult ) ; // after sending, let's identify the inactive/invalid registrationIDs and trigger their deletion: cleanupInvalidRegistrationIDsForVariant ( androidVariant . getVariantID ( ) , multicastResult , pushTargets ) ; } } | Process the HTTP POST to the FCM infrastructure for the given list of registrationIDs . | 295 | 17 |
30,371 | @ POST @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response registerPushApplication ( PushApplication pushApp ) { try { validateModelClass ( pushApp ) ; } catch ( ConstraintViolationException cve ) { logger . trace ( "Unable to create Push Application" ) ; return createBadRequestResponse ( cve . getConstraintViolations ( ) ) . build ( ) ; } try { logger . trace ( "Invoke service to create a push application" ) ; pushAppService . addPushApplication ( pushApp ) ; } catch ( IllegalArgumentException e ) { return Response . status ( Status . CONFLICT ) . entity ( e . getMessage ( ) ) . build ( ) ; } final URI uri = UriBuilder . fromResource ( PushApplicationEndpoint . class ) . path ( pushApp . getPushApplicationID ( ) ) . build ( ) ; return Response . created ( uri ) . entity ( pushApp ) . build ( ) ; } | Create Push Application | 222 | 3 |
30,372 | @ GET @ Produces ( MediaType . APPLICATION_JSON ) public Response listAllPushApplications ( @ QueryParam ( "page" ) Integer page , @ QueryParam ( "per_page" ) Integer pageSize , @ QueryParam ( "includeDeviceCount" ) @ DefaultValue ( "false" ) boolean includeDeviceCount , @ QueryParam ( "includeActivity" ) @ DefaultValue ( "false" ) boolean includeActivity ) { if ( pageSize != null ) { pageSize = Math . min ( MAX_PAGE_SIZE , pageSize ) ; } else { pageSize = DEFAULT_PAGE_SIZE ; } if ( page == null ) { page = 0 ; } logger . trace ( "Query paged push applications with {} items for page {}" , pageSize , page ) ; final PageResult < PushApplication , Count > pageResult = getSearch ( ) . findAllPushApplicationsForDeveloper ( page , pageSize ) ; ResponseBuilder response = Response . ok ( pageResult . getResultList ( ) ) ; response . header ( "total" , pageResult . getAggregate ( ) . getCount ( ) ) ; for ( PushApplication app : pageResult . getResultList ( ) ) { if ( includeActivity ) { logger . trace ( "Include activity header" ) ; putActivityIntoResponseHeaders ( app , response ) ; } if ( includeDeviceCount ) { logger . trace ( "Include device count header" ) ; putDeviceCountIntoResponseHeaders ( app , response ) ; } } return response . build ( ) ; } | List Push Applications | 331 | 3 |
30,373 | @ GET @ Path ( "/{pushAppID}" ) @ Produces ( MediaType . APPLICATION_JSON ) public Response findById ( @ PathParam ( "pushAppID" ) String pushApplicationID , @ QueryParam ( "includeDeviceCount" ) @ DefaultValue ( "false" ) boolean includeDeviceCount , @ QueryParam ( "includeActivity" ) @ DefaultValue ( "false" ) boolean includeActivity ) { PushApplication pushApp = getSearch ( ) . findByPushApplicationIDForDeveloper ( pushApplicationID ) ; if ( pushApp != null ) { logger . trace ( "Query details for push application {}" , pushApp . getName ( ) ) ; ResponseBuilder response = Response . ok ( pushApp ) ; if ( includeActivity ) { logger . trace ( "Include activity header" ) ; putActivityIntoResponseHeaders ( pushApp , response ) ; } if ( includeDeviceCount ) { logger . trace ( "Include device count header" ) ; putDeviceCountIntoResponseHeaders ( pushApp , response ) ; } return response . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . entity ( "Could not find requested PushApplicationEntity" ) . build ( ) ; } | Get Push Application . | 262 | 4 |
30,374 | @ PUT @ Path ( "/{pushAppID}" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response updatePushApplication ( @ PathParam ( "pushAppID" ) String pushApplicationID , PushApplication updatedPushApp ) { PushApplication pushApp = getSearch ( ) . findByPushApplicationIDForDeveloper ( pushApplicationID ) ; if ( pushApp != null ) { // some validation try { validateModelClass ( updatedPushApp ) ; } catch ( ConstraintViolationException cve ) { logger . info ( "Unable to update Push Application '{}'" , pushApplicationID ) ; logger . debug ( "Details: {}" , cve ) ; // Build and return the 400 (Bad Request) response ResponseBuilder builder = createBadRequestResponse ( cve . getConstraintViolations ( ) ) ; return builder . build ( ) ; } // update name/desc: pushApp . setDescription ( updatedPushApp . getDescription ( ) ) ; pushApp . setName ( updatedPushApp . getName ( ) ) ; logger . trace ( "Invoke service to update a push application" ) ; pushAppService . updatePushApplication ( pushApp ) ; return Response . noContent ( ) . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . entity ( "Could not find requested PushApplicationEntity" ) . build ( ) ; } | Update Push Application | 309 | 3 |
30,375 | @ PUT @ Path ( "/{pushAppID}/reset" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response resetMasterSecret ( @ PathParam ( "pushAppID" ) String pushApplicationID ) { //PushApplication pushApp = pushAppService.findByPushApplicationIDForDeveloper(pushApplicationID, extractUsername(request)); PushApplication pushApp = getSearch ( ) . findByPushApplicationIDForDeveloper ( pushApplicationID ) ; if ( pushApp != null ) { // generate the new 'masterSecret' and apply it: String newMasterSecret = UUID . randomUUID ( ) . toString ( ) ; pushApp . setMasterSecret ( newMasterSecret ) ; logger . info ( "Invoke service to change master secret of a push application '{}'" , pushApp . getPushApplicationID ( ) ) ; pushAppService . updatePushApplication ( pushApp ) ; return Response . ok ( pushApp ) . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . entity ( "Could not find requested PushApplicationEntity" ) . build ( ) ; } | Reset MasterSecret for Push Application | 253 | 7 |
30,376 | @ DELETE @ Path ( "/{pushAppID}" ) @ Produces ( MediaType . APPLICATION_JSON ) public Response deletePushApplication ( @ PathParam ( "pushAppID" ) String pushApplicationID ) { PushApplication pushApp = getSearch ( ) . findByPushApplicationIDForDeveloper ( pushApplicationID ) ; if ( pushApp != null ) { logger . trace ( "Invoke service to delete a push application" ) ; pushAppService . removePushApplication ( pushApp ) ; return Response . noContent ( ) . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . entity ( "Could not find requested PushApplicationEntity" ) . build ( ) ; } | Delete Push Application | 151 | 3 |
30,377 | @ GET @ Path ( "/{pushAppID}/count" ) @ Produces ( MediaType . APPLICATION_JSON ) public Response countInstallations ( @ PathParam ( "pushAppID" ) String pushApplicationID ) { logger . trace ( "counting devices by type for push application '{}'" , pushApplicationID ) ; Map < String , Long > result = pushAppService . countInstallationsByType ( pushApplicationID ) ; return Response . ok ( result ) . build ( ) ; } | Count Push Applications | 108 | 3 |
30,378 | private SenderConfiguration validateAndSanitizeConfiguration ( VariantType type , SenderConfiguration configuration ) { switch ( type ) { case ANDROID : if ( configuration . batchSize ( ) > 1000 ) { logger . warn ( String . format ( "Sender configuration -D%s=%s is invalid: at most 1000 tokens can be submitted to GCM in one batch" , getSystemPropertyName ( type , ConfigurationProperty . batchSize ) , configuration . batchSize ( ) ) ) ; configuration . setBatchSize ( 1000 ) ; } break ; default : break ; } return configuration ; } | Validates that configuration is correct with regards to push networks limitations or implementation etc . | 125 | 16 |
30,379 | public static Boolean isAscendingOrder ( String sorting ) { return "desc" . equalsIgnoreCase ( sorting ) ? Boolean . FALSE : Boolean . TRUE ; } | Verify if the string sorting matches with asc or desc Returns FALSE when sorting query value matches desc otherwise it returns TRUE . | 35 | 24 |
30,380 | public String toStrippedJsonString ( ) { try { final Map < String , Object > json = new LinkedHashMap <> ( ) ; json . put ( "alert" , this . message . getAlert ( ) ) ; json . put ( "priority" , this . message . getPriority ( ) . toString ( ) ) ; if ( this . getMessage ( ) . getBadge ( ) > 0 ) { json . put ( "badge" , Integer . toString ( this . getMessage ( ) . getBadge ( ) ) ) ; } json . put ( "criteria" , this . criteria ) ; json . put ( "config" , this . config ) ; return OBJECT_MAPPER . writeValueAsString ( json ) ; } catch ( JsonProcessingException e ) { return "[\"invalid json\"]" ; } catch ( IOException e ) { return "[\"invalid json\"]" ; } } | Returns a JSON representation of the payload . This does not include any pushed data just the alert of the message . This also contains the entire criteria object . | 204 | 30 |
30,381 | public String toMinimizedJsonString ( ) { try { final Map < String , Object > json = new LinkedHashMap <> ( ) ; json . put ( "alert" , this . message . getAlert ( ) ) ; if ( this . getMessage ( ) . getBadge ( ) > 0 ) { json . put ( "badge" , Integer . toString ( this . getMessage ( ) . getBadge ( ) ) ) ; } json . put ( "config" , this . config ) ; // we strip down the criteria too, as alias/category can be quite long, based on use-case final Map < String , Object > shrinkedCriteriaJSON = new LinkedHashMap <> ( ) ; shrinkedCriteriaJSON . put ( "variants" , this . criteria . getVariants ( ) ) ; shrinkedCriteriaJSON . put ( "deviceType" , this . criteria . getDeviceTypes ( ) ) ; json . put ( "criteria" , shrinkedCriteriaJSON ) ; return OBJECT_MAPPER . writeValueAsString ( json ) ; } catch ( JsonProcessingException e ) { return "[\"invalid json\"]" ; } catch ( IOException e ) { return "[\"invalid json\"]" ; } } | Returns a minimized JSON representation of the payload . This does not include potentially large objects like alias or category from the given criteria . | 275 | 25 |
30,382 | protected void validateModelClass ( Object model ) { final Set < ConstraintViolation < Object > > violations = validator . validate ( model ) ; // in case of an invalid model, we throw a ConstraintViolationException, containing the violations: if ( ! violations . isEmpty ( ) ) { throw new ConstraintViolationException ( new HashSet <> ( violations ) ) ; } } | Generic validator used to identify constraint violations of the given model class . | 86 | 14 |
30,383 | protected ResponseBuilder createBadRequestResponse ( Set < ConstraintViolation < ? > > violations ) { final Map < String , String > responseObj = violations . stream ( ) . collect ( Collectors . toMap ( v -> v . getPropertyPath ( ) . toString ( ) , ConstraintViolation :: getMessage ) ) ; return Response . status ( Response . Status . BAD_REQUEST ) . entity ( responseObj ) ; } | Helper function to create a 400 Bad Request response containing a JSON map giving details about the violations | 94 | 18 |
30,384 | private static void checkBlockEndContext ( RenderUnitNode node , Context endContext ) { if ( ! endContext . isValidEndContextForContentKind ( MoreObjects . firstNonNull ( node . getContentKind ( ) , SanitizedContentKind . HTML ) ) ) { String msg = String . format ( "A block of kind=\"%s\" cannot end in context %s. Likely cause is %s." , node . getContentKind ( ) . asAttributeValue ( ) , endContext , endContext . getLikelyEndContextMismatchCause ( node . getContentKind ( ) ) ) ; throw SoyAutoescapeException . createWithNode ( msg , node ) ; } } | Checks that the end context of a block is compatible with its start context . | 146 | 16 |
30,385 | static void inferStrictRenderUnitNode ( RenderUnitNode node , Inferences inferences , ErrorReporter errorReporter ) { InferenceEngine inferenceEngine = new InferenceEngine ( inferences , errorReporter ) ; // Context started off as startContext and we have propagated context through all of // node's children, so now context is the node's end context. Context endContext = inferenceEngine . inferChildren ( node , Context . getStartContextForContentKind ( node . getContentKind ( ) ) ) ; // Checking that start and end context is same. checkBlockEndContext ( node , endContext ) ; } | Applies strict contextual autoescaping to the given node s children . | 130 | 15 |
30,386 | private static String parseFormat ( List < ? extends TargetExpr > args ) { String numberFormatType = ! args . isEmpty ( ) ? args . get ( 0 ) . getText ( ) : "'" + DEFAULT_FORMAT + "'" ; if ( ! JS_ARGS_TO_ENUM . containsKey ( numberFormatType ) ) { String validKeys = Joiner . on ( "', '" ) . join ( JS_ARGS_TO_ENUM . keySet ( ) ) ; throw new IllegalArgumentException ( "First argument to formatNum must be constant, and one of: '" + validKeys + "'." ) ; } return numberFormatType ; } | Validates that the provided format matches a supported format and returns the value if not this throws an exception . | 147 | 21 |
30,387 | private ProtoClass clazz ( ) { ProtoClass localClazz = clazz ; if ( localClazz == null ) { localClazz = classCache . getUnchecked ( proto . getDescriptorForType ( ) ) ; clazz = localClazz ; } return localClazz ; } | it if we can | 63 | 4 |
30,388 | public SoyValue getProtoField ( String name ) { FieldWithInterpreter field = clazz ( ) . fields . get ( name ) ; if ( field == null ) { throw new IllegalArgumentException ( "Proto " + proto . getClass ( ) . getName ( ) + " does not have a field of name " + name ) ; } if ( field . shouldCheckFieldPresenceToEmulateJspbNullability ( ) && ! proto . hasField ( field . getDescriptor ( ) ) ) { return NullData . INSTANCE ; } return field . interpretField ( proto ) ; } | Gets a value for the field for the underlying proto object . Not intended for general use . | 131 | 19 |
30,389 | public static < T extends Field > ImmutableMap < String , T > getFieldsForType ( Descriptor descriptor , Set < FieldDescriptor > extensions , Factory < T > factory ) { ImmutableMap . Builder < String , T > fields = ImmutableMap . builder ( ) ; for ( FieldDescriptor fieldDescriptor : descriptor . getFields ( ) ) { if ( ProtoUtils . shouldJsIgnoreField ( fieldDescriptor ) ) { continue ; } T field = factory . create ( fieldDescriptor ) ; fields . put ( field . getName ( ) , field ) ; } SetMultimap < String , T > extensionsBySoyName = MultimapBuilder . hashKeys ( ) . hashSetValues ( ) . build ( ) ; for ( FieldDescriptor extension : extensions ) { T field = factory . create ( extension ) ; extensionsBySoyName . put ( field . getName ( ) , field ) ; } for ( Map . Entry < String , Set < T > > group : Multimaps . asMap ( extensionsBySoyName ) . entrySet ( ) ) { Set < T > ambiguousFields = group . getValue ( ) ; String fieldName = group . getKey ( ) ; if ( ambiguousFields . size ( ) == 1 ) { fields . put ( fieldName , Iterables . getOnlyElement ( ambiguousFields ) ) ; } else { T value = factory . createAmbiguousFieldSet ( ambiguousFields ) ; logger . severe ( "Proto " + descriptor . getFullName ( ) + " has multiple extensions with the name \"" + fieldName + "\": " + fullFieldNames ( ambiguousFields ) + "\nThis field will not be accessible from soy" ) ; fields . put ( fieldName , value ) ; } } return fields . build ( ) ; } | Returns the set of fields indexed by soy accessor name for the given type . | 396 | 16 |
30,390 | private Optional < SoyType > soyTypeForProtoOrEnum ( Class < ? > type , Method method ) { // Message isn't supported because we can't get a descriptor from it. if ( type == Message . class ) { reporter . invalidReturnType ( Message . class , method ) ; return Optional . absent ( ) ; } Optional < String > fullName = nameFromDescriptor ( type ) ; if ( ! fullName . isPresent ( ) ) { reporter . incompatibleReturnType ( type , method ) ; return Optional . absent ( ) ; } SoyType returnType = registry . getType ( fullName . get ( ) ) ; if ( returnType == null ) { reporter . incompatibleReturnType ( type , method ) ; return Optional . absent ( ) ; } return Optional . of ( returnType ) ; } | Attempts to discover the SoyType for a proto or proto enum reporting an error if unable to . | 172 | 19 |
30,391 | private boolean isOrContains ( SoyType type , SoyType . Kind kind ) { if ( type . getKind ( ) == kind ) { return true ; } if ( type . getKind ( ) == SoyType . Kind . UNION ) { for ( SoyType member : ( ( UnionType ) type ) . getMembers ( ) ) { if ( member . getKind ( ) == kind ) { return true ; } } } return false ; } | Returns true if the type is the given kind or contains the given kind . | 94 | 15 |
30,392 | public static String getFieldName ( Descriptors . FieldDescriptor field , boolean capitializeFirstLetter ) { String fieldName = field . getName ( ) ; if ( SPECIAL_CASES . containsKey ( fieldName ) ) { String output = SPECIAL_CASES . get ( fieldName ) ; if ( capitializeFirstLetter ) { return output ; } else { return ( ( char ) ( output . charAt ( 0 ) + ( ' ' - ' ' ) ) ) + output . substring ( 1 ) ; } } return underscoresToCamelCase ( fieldName , capitializeFirstLetter ) ; } | Returns the Java name for a proto field . | 134 | 9 |
30,393 | public static String underscoresToCamelCase ( String input , boolean capitializeNextLetter ) { StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < input . length ( ) ; i ++ ) { char ch = input . charAt ( i ) ; if ( ' ' <= ch && ch <= ' ' ) { if ( capitializeNextLetter ) { result . append ( ( char ) ( ch + ( ' ' - ' ' ) ) ) ; } else { result . append ( ch ) ; } capitializeNextLetter = false ; } else if ( ' ' <= ch && ch <= ' ' ) { if ( i == 0 && ! capitializeNextLetter ) { // Force first letter to lower-case unless explicitly told to // capitalize it. result . append ( ( char ) ( ch + ( ' ' - ' ' ) ) ) ; } else { // Capital letters after the first are left as-is. result . append ( ch ) ; } capitializeNextLetter = false ; } else if ( ' ' <= ch && ch <= ' ' ) { result . append ( ch ) ; capitializeNextLetter = true ; } else { capitializeNextLetter = true ; } } return result . toString ( ) ; } | Converts underscore field names to camel case while preserving camel case field names . | 269 | 15 |
30,394 | private static boolean hasConflictingClassName ( DescriptorProto messageDesc , String name ) { if ( name . equals ( messageDesc . getName ( ) ) ) { return true ; } for ( EnumDescriptorProto enumDesc : messageDesc . getEnumTypeList ( ) ) { if ( name . equals ( enumDesc . getName ( ) ) ) { return true ; } } for ( DescriptorProto nestedMessageDesc : messageDesc . getNestedTypeList ( ) ) { if ( hasConflictingClassName ( nestedMessageDesc , name ) ) { return true ; } } return false ; } | Used by the other overload descends recursively into messages . | 136 | 13 |
30,395 | private static boolean hasConflictingClassName ( FileDescriptorProto file , String name ) { for ( EnumDescriptorProto enumDesc : file . getEnumTypeList ( ) ) { if ( name . equals ( enumDesc . getName ( ) ) ) { return true ; } } for ( ServiceDescriptorProto serviceDesc : file . getServiceList ( ) ) { if ( name . equals ( serviceDesc . getName ( ) ) ) { return true ; } } for ( DescriptorProto messageDesc : file . getMessageTypeList ( ) ) { if ( hasConflictingClassName ( messageDesc , name ) ) { return true ; } } return false ; } | Checks whether any generated classes conflict with the given name . | 152 | 12 |
30,396 | public static IntegerData forValue ( long value ) { if ( value > 10 || value < - 1 ) { return new IntegerData ( value ) ; } switch ( ( int ) value ) { case - 1 : return MINUS_ONE ; case 0 : return ZERO ; case 1 : return ONE ; case 2 : return TWO ; case 3 : return THREE ; case 4 : return FOUR ; case 5 : return FIVE ; case 6 : return SIX ; case 7 : return SEVEN ; case 8 : return EIGHT ; case 9 : return NINE ; case 10 : return TEN ; default : throw new AssertionError ( "Impossible case" ) ; } } | Gets a IntegerData instance for the given value . | 142 | 11 |
30,397 | PyExpr exec ( CallNode callNode , LocalVariableStack localVarStack , ErrorReporter errorReporter ) { this . localVarStack = localVarStack ; this . errorReporter = errorReporter ; PyExpr callExpr = visit ( callNode ) ; this . localVarStack = null ; this . errorReporter = null ; return callExpr ; } | Generates the Python expression for a given call . | 80 | 10 |
30,398 | @ Override protected PyExpr visitCallBasicNode ( CallBasicNode node ) { String calleeName = node . getCalleeName ( ) ; // Build the Python expr text for the callee. String calleeExprText ; TemplateNode template = getTemplateIfInSameFile ( node ) ; if ( template != null ) { // If in the same module no namespace is required. calleeExprText = getLocalTemplateName ( template ) ; } else { // If in another module, the module name is required along with the function name. int secondToLastDotIndex = calleeName . lastIndexOf ( ' ' , calleeName . lastIndexOf ( ' ' ) - 1 ) ; calleeExprText = calleeName . substring ( secondToLastDotIndex + 1 ) ; } String callExprText = calleeExprText + "(" + genObjToPass ( node ) + ", ijData)" ; return escapeCall ( callExprText , node . getEscapingDirectives ( ) ) ; } | Visits basic call nodes and builds the call expression . If the callee is in the file it can be accessed directly but if it s in another file the module name must be prefixed . | 225 | 39 |
30,399 | @ Override protected PyExpr visitCallDelegateNode ( CallDelegateNode node ) { ExprRootNode variantSoyExpr = node . getDelCalleeVariantExpr ( ) ; PyExpr variantPyExpr ; if ( variantSoyExpr == null ) { // Case 1: Delegate call with empty variant. variantPyExpr = new PyStringExpr ( "''" ) ; } else { // Case 2: Delegate call with variant expression. TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor ( localVarStack , pluginValueFactory , errorReporter ) ; variantPyExpr = translator . exec ( variantSoyExpr ) ; } String calleeExprText = new PyFunctionExprBuilder ( "runtime.get_delegate_fn" ) . addArg ( node . getDelCalleeName ( ) ) . addArg ( variantPyExpr ) . addArg ( node . allowEmptyDefault ( ) ) . build ( ) ; String callExprText = calleeExprText + "(" + genObjToPass ( node ) + ", ijData)" ; return escapeCall ( callExprText , node . getEscapingDirectives ( ) ) ; } | Visits a delegate call node and builds the call expression to retrieve the function and execute it . The get_delegate_fn returns the function directly so its output can be called directly . | 270 | 38 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.