idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
141,600 | public double computePhase ( int idx ) { double r = real [ idx ] ; double i = imag [ idx ] ; return atan2 ( r , i ) ; } | Calculates the phase of the pixel at the specified index . The phase is the argument of the complex number i . e . the angle of the complex vector in the complex plane . | 39 | 37 |
141,601 | private Map findLoaders ( ) { Map loaders = getContainer ( ) . getComponentDescriptorMap ( ProviderLoader . class . getName ( ) ) ; if ( loaders == null ) { throw new Error ( "No provider loaders found" ) ; } Set keys = loaders . keySet ( ) ; Map found = null ; ProviderLoader defaultLoader = null ; for ( Iterator iter = keys . iterator ( ) ; iter . hasNext ( ) ; ) { String key = ( String ) iter . next ( ) ; ProviderLoader loader ; try { loader = ( ProviderLoader ) getContainer ( ) . lookup ( ProviderLoader . class . getName ( ) , key ) ; } catch ( Exception e ) { log . warn ( "Failed to lookup provider loader for key: {}" , key , e ) ; continue ; } if ( loader != null ) { if ( found == null ) { // we need an ordered map found = new LinkedHashMap ( ) ; } if ( key . equals ( SELECT_DEFAULT ) ) { defaultLoader = loader ; } else { found . put ( key , loader ) ; } } } // the default should be added at the end (as fallback) assert defaultLoader != null ; found . put ( SELECT_DEFAULT , defaultLoader ) ; return found ; } | Find any provider loaders which are available in the container . | 278 | 12 |
141,602 | public static byte [ ] getBytes ( String text ) { byte [ ] bytes = new byte [ ] { } ; try { bytes = text . getBytes ( "utf-8" ) ; } catch ( UnsupportedEncodingException e ) { } return bytes ; } | Get UTF - 8 without BOM encoded bytes from String | 56 | 11 |
141,603 | public static byte [ ] loadBytesFromFile ( File file ) { byte [ ] bytes = null ; try { bytes = Files . readAllBytes ( Paths . get ( file . getAbsolutePath ( ) ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return bytes ; } | load from file | 69 | 3 |
141,604 | public static void saveBytesToFile ( byte [ ] data , File file ) { if ( data == null ) { return ; } FileOutputStream fos = null ; BufferedOutputStream bos = null ; try { fos = new FileOutputStream ( file ) ; bos = new BufferedOutputStream ( fos ) ; bos . write ( data ) ; bos . flush ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( bos != null ) { try { bos . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } | save to file | 192 | 3 |
141,605 | public static BufferedImage loadImage ( String fileName ) { File f = new File ( fileName ) ; if ( f . exists ( ) ) { return loadImage ( f ) ; } throw new ImageLoaderException ( new FileNotFoundException ( fileName ) ) ; } | Tries to load Image from specified filename . | 58 | 9 |
141,606 | public static BufferedImage loadImage ( File file ) { try { BufferedImage bimg = ImageIO . read ( file ) ; if ( bimg == null ) { throw new ImageLoaderException ( "Could not load Image! ImageIO.read() returned null." ) ; } return bimg ; } catch ( IOException e ) { throw new ImageLoaderException ( e ) ; } } | Tries to load image from specified file . | 82 | 9 |
141,607 | MessageToClient _createMessageToClient ( MessageFromClient message , T session ) { MessageToClient messageToClient = new MessageToClient ( ) ; messageToClient . setId ( message . getId ( ) ) ; try { Class cls = Class . forName ( message . getDataService ( ) ) ; Object dataService = this . getDataService ( session , cls ) ; logger . debug ( "Process message {}" , message ) ; List < Object > arguments = getArrayList ( ) ; Method method = methodServices . getMethodFromDataService ( cls , message , arguments ) ; injectSession ( method . getParameterTypes ( ) , arguments , session ) ; messageToClient . setResult ( method . invoke ( dataService , arguments . toArray ( ) ) ) ; if ( method . isAnnotationPresent ( JsonMarshaller . class ) ) { messageToClient . setJson ( argumentServices . getJsonResultFromSpecificMarshaller ( method . getAnnotation ( JsonMarshaller . class ) , messageToClient . getResponse ( ) ) ) ; } try { Method nonProxiedMethod = methodServices . getNonProxiedMethod ( cls , method . getName ( ) , method . getParameterTypes ( ) ) ; messageToClient . setDeadline ( cacheManager . processCacheAnnotations ( nonProxiedMethod , message . getParameters ( ) ) ) ; } catch ( NoSuchMethodException ex ) { logger . error ( "Fail to process extra annotations (JsCacheResult, JsCacheRemove) for method : " + method . getName ( ) , ex ) ; } logger . debug ( "Method {} proceed messageToClient : {}." , method . getName ( ) , messageToClient ) ; } catch ( InvocationTargetException ex ) { Throwable cause = ex . getCause ( ) ; if ( ConstraintViolationException . class . isInstance ( cause ) ) { messageToClient . setConstraints ( constraintServices . extractViolations ( ( ConstraintViolationException ) cause ) ) ; } else { messageToClient . setFault ( faultServices . buildFault ( cause ) ) ; } } catch ( Throwable ex ) { messageToClient . setFault ( faultServices . buildFault ( ex ) ) ; } return messageToClient ; } | Create a MessageToClient from MessageFromClient for session Only for available test use case | 500 | 17 |
141,608 | void injectSession ( Class < ? > [ ] parameterTypes , List < Object > arguments , T session ) { if ( parameterTypes != null ) { int i = 0 ; for ( Class < ? > parameterType : parameterTypes ) { if ( parameterType . isInstance ( session ) ) { arguments . set ( i , session ) ; break ; } i ++ ; } } } | Inject Session or HttpSession if necessary | 79 | 9 |
141,609 | private void loadCertificateFromFile ( File file ) { certificateFileSanityChecks ( file ) ; try { X509Certificate aaCert = CertificateUtils . loadCertificate ( new FileInputStream ( file ) , Encoding . PEM ) ; // Get certificate subject hash, using the CANL implementation for CA // files String aaCertHash = getOpensslCAHash ( aaCert . getSubjectX500Principal ( ) ) ; // Store certificate in the local map localAACertificatesByHash . put ( aaCertHash , aaCert ) ; synchronized ( listenerLock ) { listener . notifyCertificateLoadEvent ( aaCert , file ) ; } } catch ( IOException e ) { String errorMessage = String . format ( "Error parsing VOMS trusted certificate from %s. Reason: %s" , file . getAbsolutePath ( ) , e . getMessage ( ) ) ; throw new VOMSError ( errorMessage , e ) ; } } | Loads a VOMS AA certificate from a given file and stores this certificate in the local map of trusted VOMS AA certificate . | 214 | 28 |
141,610 | private void certificateFileSanityChecks ( File certFile ) { if ( ! certFile . exists ( ) ) throw new VOMSError ( "Local VOMS trusted certificate does not exist:" + certFile . getAbsolutePath ( ) ) ; if ( ! certFile . canRead ( ) ) throw new VOMSError ( "Local VOMS trusted certificate is not readable:" + certFile . getAbsolutePath ( ) ) ; } | Performs basic sanity checks performed on a file supposed to hold a VOMS AA certificate . | 98 | 19 |
141,611 | private void directorySanityChecks ( File directory ) { if ( ! directory . exists ( ) ) throw new VOMSError ( "Local trust directory does not exists:" + directory . getAbsolutePath ( ) ) ; if ( ! directory . isDirectory ( ) ) throw new VOMSError ( "Local trust directory is not a directory:" + directory . getAbsolutePath ( ) ) ; if ( ! directory . canRead ( ) ) throw new VOMSError ( "Local trust directory is not readable:" + directory . getAbsolutePath ( ) ) ; if ( ! directory . canExecute ( ) ) throw new VOMSError ( "Local trust directory is not traversable:" + directory . getAbsolutePath ( ) ) ; } | Performs basic sanity checks on a directory that is supposed to contain VOMS AA certificates and LSC files . | 163 | 23 |
141,612 | private boolean doesItemMatchAppropriateCondition ( Object item ) { Matcher < ? > matcher ; if ( item instanceof View ) { matcher = loaded ( ) ; } else if ( item instanceof Element ) { matcher = displayed ( ) ; } else { matcher = present ( ) ; } return matcher . matches ( item ) ; } | Takes an object and determines a condition for that object that should satisfy the containing view is loaded . Different conditions are made depending on the type of object . | 75 | 31 |
141,613 | String getClassnameFromProxy ( Object dataservice ) { String ds = dataservice . toString ( ) ; return getClassnameFromProxyname ( ds ) ; } | Return classname from proxy instance | 41 | 6 |
141,614 | String getClassnameFromProxyname ( String proxyname ) { Pattern pattern = Pattern . compile ( "[@$]" ) ; Matcher matcher = pattern . matcher ( proxyname ) ; matcher . find ( ) ; matcher . start ( ) ; return proxyname . substring ( 0 , matcher . start ( ) ) ; } | Return classname from proxyname | 77 | 7 |
141,615 | public static X509CertChainValidatorExt buildCertificateValidator ( ) { return buildCertificateValidator ( DefaultVOMSValidator . DEFAULT_TRUST_ANCHORS_DIR , null , null , 0L , DEFAULT_NS_CHECKS , DEFAULT_CRL_CHECKS , DEFAULT_OCSP_CHECKS ) ; } | Builds an Openssl - style certificate validator . | 78 | 12 |
141,616 | public int getIndexOfMaxValue ( int channel ) { double [ ] values = getData ( ) [ channel ] ; int index = 0 ; double val = values [ index ] ; for ( int i = 1 ; i < numValues ( ) ; i ++ ) { if ( values [ i ] > val ) { index = i ; val = values [ index ] ; } } return index ; } | Returns the index of the maximum value of the specified channel . | 83 | 12 |
141,617 | public int getIndexOfMinValue ( int channel ) { double [ ] values = getData ( ) [ channel ] ; int index = 0 ; double val = values [ index ] ; for ( int i = 1 ; i < numValues ( ) ; i ++ ) { if ( values [ i ] < val ) { index = i ; val = values [ index ] ; } } return index ; } | Returns the index of the minimum value of the specified channel . | 83 | 12 |
141,618 | public void setValue ( final int channel , final int x , final int y , final double value ) { this . data [ channel ] [ y * this . width + x ] = value ; } | Sets value at the specified position for the specified channel . No bounds checks will be performed positions outside of this images dimension can either result in a value for a different position or an ArrayIndexOutOfBoundsException . | 41 | 44 |
141,619 | boolean isMonitored ( HttpSession session ) { boolean monitor = false ; if ( null != session && session . getAttribute ( Constants . Options . OPTIONS ) != null ) { monitor = ( ( Options ) session . getAttribute ( Constants . Options . OPTIONS ) ) . isMonitor ( ) ; } return monitor ; } | determine if request is monitored | 71 | 7 |
141,620 | public void saveToCache ( String topic , Class < ? extends JsTopicMessageController > cls ) { if ( null != topic && null != cls ) { messageControllers . put ( topic , cls ) ; } } | Save messageController Factory for topic | 49 | 6 |
141,621 | public JsTopicMessageController loadFromCache ( String topic ) { if ( null == topic ) { return null ; } if ( messageControllers . containsKey ( topic ) ) { Instance < ? extends JsTopicMessageController > instances = getInstances ( messageControllers . get ( topic ) ) ; if ( ! instances . isUnsatisfied ( ) ) { return instances . get ( ) ; } } return null ; } | Get CDI instance messageController from cache | 92 | 8 |
141,622 | public static IUnitizingAnnotationUnit findNextUnit ( final Iterator < IUnitizingAnnotationUnit > units , int raterIdx ) { return findNextUnit ( units , raterIdx , null ) ; } | Utility method for moving on the cursor of the given iterator until a unit of the specified rater is returned . | 48 | 23 |
141,623 | public static IUnitizingAnnotationUnit findNextUnit ( final Iterator < IUnitizingAnnotationUnit > units , final Object category ) { return findNextUnit ( units , - 1 , category ) ; } | Utility method for moving on the cursor of the given iterator until a unit of the specified category is returned . | 44 | 22 |
141,624 | public static IUnitizingAnnotationUnit findNextUnit ( final Iterator < IUnitizingAnnotationUnit > units , int raterIdx , final Object category ) { while ( units . hasNext ( ) ) { IUnitizingAnnotationUnit result = units . next ( ) ; if ( category != null && ! category . equals ( result . getCategory ( ) ) ) { continue ; } if ( raterIdx < 0 || result . getRaterIdx ( ) == raterIdx ) { return result ; } } return null ; } | Utility method for moving on the cursor of the given iterator until a unit of the specified rater and category is returned . Both the rater index and the category may be null if those filter conditions are to be ignored . | 117 | 45 |
141,625 | public static Object deserialize ( String json , String containerType , Class cls , NestedContent nestedContent ) throws ApiException { try { if ( ( "List" . equals ( containerType ) || "Array" . equals ( containerType ) ) && nestedContent != null ) { if ( NestedContent . CONTEXT . equals ( nestedContent ) ) { JavaType typeInfo = JsonUtil . getJsonMapper ( ) . getTypeFactory ( ) . constructFromCanonical ( "java.util.List<java.util.List<io.cortical.rest.model.Context>>" ) ; Object response = ( java . lang . Object ) JsonUtil . getJsonMapper ( ) . readValue ( json , typeInfo ) ; return response ; } else if ( NestedContent . TERM . equals ( nestedContent ) ) { JavaType typeInfo = JsonUtil . getJsonMapper ( ) . getTypeFactory ( ) . constructFromCanonical ( "java.util.List<java.util.List<io.cortical.rest.model.Term>>" ) ; Object response = ( java . lang . Object ) JsonUtil . getJsonMapper ( ) . readValue ( json , typeInfo ) ; return response ; } else { return null ; } } else if ( "List" . equals ( containerType ) || "Array" . equals ( containerType ) ) { JavaType typeInfo = JsonUtil . getJsonMapper ( ) . getTypeFactory ( ) . constructCollectionType ( List . class , cls ) ; List response = ( List < ? > ) JsonUtil . getJsonMapper ( ) . readValue ( json , typeInfo ) ; return response ; } else if ( String . class . equals ( cls ) ) { if ( json != null && json . startsWith ( "\"" ) && json . endsWith ( "\"" ) && json . length ( ) > 1 ) return json . substring ( 1 , json . length ( ) - 2 ) ; else return json ; } else { return JsonUtil . getJsonMapper ( ) . readValue ( json , cls ) ; } } catch ( IOException e ) { throw new ApiException ( 500 , e . getMessage ( ) ) ; } } | Deserialize a received response String . | 506 | 8 |
141,626 | public void checkAccessTopic ( UserContext ctx , String topic ) throws IllegalAccessException { boolean tacPresent0 = checkAccessTopicGlobalAC ( ctx , topic ) ; boolean tacPresent1 = checkAccessTopicFromJsTopicControl ( ctx , topic ) ; boolean tacPresent2 = checkAccessTopicFromJsTopicControls ( ctx , topic ) ; if ( logger . isDebugEnabled ( ) && ! ( tacPresent0 | tacPresent1 | tacPresent2 ) ) { logger . debug ( "No '{}' access control found in project, add {} implementation annotated with {}({}) in your project for add subscription security." , topic , JsTopicAccessController . class , JsTopicControl . class , topic ) ; } } | Process Access Topic Controller | 157 | 4 |
141,627 | boolean checkAccessTopicGlobalAC ( UserContext ctx , String topic ) throws IllegalAccessException { logger . debug ( "Looking for accessController for topic '{}' from GlobalAccess" , topic ) ; Iterable < JsTopicAccessController > accessControls = topicAccessController . select ( DEFAULT_AT ) ; return checkAccessTopicFromControllers ( ctx , topic , accessControls ) ; } | Check if global access control is allowed | 88 | 7 |
141,628 | boolean checkAccessTopicFromJsTopicAccessControllers ( UserContext ctx , String topic , Iterable < JsTopicAccessController > controllers ) throws IllegalAccessException { logger . debug ( "Looking for accessController for topic '{}' from JsTopicAccessControllers" , topic ) ; for ( JsTopicAccessController jsTopicAccessController : controllers ) { if ( checkAccessTopicFromController ( ctx , topic , jsTopicAccessController ) ) { return true ; } } return false ; } | Check if specific access control is allowed from controllers | 107 | 9 |
141,629 | boolean checkAccessTopicFromController ( UserContext ctx , String topic , JsTopicAccessController jsTopicAccessController ) throws IllegalAccessException { logger . debug ( "Looking for accessController for topic '{}' from JsTopicAccessController {}" , topic , jsTopicAccessController ) ; JsTopicControls jsTopicControls = jsTopicControlsTools . getJsTopicControlsFromProxyClass ( jsTopicAccessController . getClass ( ) ) ; logger . debug ( "Looking for accessController for topic '{}' from jsTopicControls {}" , topic , jsTopicControls ) ; if ( null != jsTopicControls ) { logger . debug ( "Looking for accessController for topic '{}' from jsTopicControls {}, {}" , topic , jsTopicControls , jsTopicControls . value ( ) ) ; for ( JsTopicControl jsTopicControl : jsTopicControls . value ( ) ) { if ( topic . equals ( jsTopicControl . value ( ) ) ) { logger . debug ( "Found accessController for topic '{}' from JsTopicControls annotation" , topic ) ; checkAccessTopicFromControllers ( ctx , topic , Arrays . asList ( jsTopicAccessController ) ) ; return true ; } } } return false ; } | Check if specific access control is allowed from controller | 279 | 9 |
141,630 | boolean checkAccessTopicFromControllers ( UserContext ctx , String topic , Iterable < JsTopicAccessController > accessControls ) throws IllegalAccessException { logger . debug ( "Looking for accessController for topic '{}' : '{}'" , topic , accessControls ) ; boolean tacPresent = false ; if ( null != accessControls ) { for ( JsTopicAccessController accessControl : accessControls ) { accessControl . checkAccess ( ctx , topic ) ; tacPresent = true ; } } return tacPresent ; } | Check if access topic is granted by accessControls | 117 | 10 |
141,631 | boolean isJsonPayload ( Method method ) { if ( null == method || ! method . isAnnotationPresent ( JsTopic . class ) ) { return false ; } JsTopic jsTopic = method . getAnnotation ( JsTopic . class ) ; return jsTopic . jsonPayload ( ) ; } | The topic receive directly payload in json | 68 | 7 |
141,632 | JsTopicName getJsTopicNameAnnotation ( Annotation [ ] parameterAnnotations ) { for ( Annotation parameterAnnotation : parameterAnnotations ) { if ( parameterAnnotation . annotationType ( ) . equals ( JsTopicName . class ) ) { return ( JsTopicName ) parameterAnnotation ; } } return null ; } | Get JsTopicName annotation | 71 | 6 |
141,633 | String computeTopic ( JsTopicName jsTopicName , String topic ) { StringBuilder result = new StringBuilder ( ) ; if ( ! jsTopicName . prefix ( ) . isEmpty ( ) ) { result . append ( jsTopicName . prefix ( ) ) . append ( Constants . Topic . COLON ) ; } result . append ( topic ) ; if ( ! jsTopicName . postfix ( ) . isEmpty ( ) ) { result . append ( Constants . Topic . COLON ) . append ( jsTopicName . postfix ( ) ) ; } return result . toString ( ) ; } | Compute full topicname from jsTopicName . prefix topic and jsTopicName . postfix | 128 | 19 |
141,634 | Object proceedAndSendMessage ( InvocationContext ctx , String topic , boolean jsonPayload ) throws Exception { MessageToClient messageToClient = new MessageToClient ( ) ; messageToClient . setId ( topic ) ; Object result = ctx . proceed ( ) ; if ( jsonPayload ) { if ( ! String . class . isInstance ( result ) ) { throw new UnsupportedOperationException ( "Method annotated JsTopic(jsonPayload=true) must return String type and correct Json." ) ; } messageToClient . setJson ( ( String ) result ) ; } else { messageToClient . setResponse ( result ) ; } wsEvent . fire ( messageToClient ) ; return result ; } | Proceed the method and send MessageToClient to topic | 154 | 11 |
141,635 | public ComplexPixel mult ( double r , double i ) { double thisr = real ( ) , thisi = imag ( ) ; return setComplex ( thisr * r - thisi * i , thisr * i + thisi * r ) ; } | Multiplies a complex number to this pixel . This performs a complex multiplication and stores the result in this pixel . | 54 | 23 |
141,636 | public static void savePrivateKey ( OutputStream os , PrivateKey key , PrivateKeyEncoding encoding ) throws IOException { switch ( encoding ) { case PKCS_1 : savePrivateKeyPKCS1 ( os , key ) ; break ; case PKCS_8 : savePrivateKeyPKCS8 ( os , key ) ; break ; default : throw new IllegalArgumentException ( "Unsupported private key encoding: " + encoding . name ( ) ) ; } } | Serializes a private key to an output stream according to an encoding . | 97 | 14 |
141,637 | private static void savePrivateKeyPKCS8 ( OutputStream os , PrivateKey key ) throws IllegalArgumentException , IOException { CertificateUtils . savePrivateKey ( os , key , Encoding . PEM , null , null ) ; } | Serializes a private key to an output stream following the pkcs8 encoding . | 51 | 17 |
141,638 | private static void savePrivateKeyPKCS1 ( OutputStream os , PrivateKey key ) throws IllegalArgumentException , IOException { CertificateUtils . savePrivateKey ( os , key , Encoding . PEM , null , new char [ 0 ] , true ) ; } | Serializes a private key to an output stream following the pkcs1 encoding . | 57 | 17 |
141,639 | public static void saveProxyCredentials ( String proxyFileName , X509Credential uc , PrivateKeyEncoding encoding ) throws IOException { File f = new File ( proxyFileName ) ; RandomAccessFile raf = new RandomAccessFile ( f , "rws" ) ; FileChannel channel = raf . getChannel ( ) ; FilePermissionHelper . setProxyPermissions ( proxyFileName ) ; channel . truncate ( 0 ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; saveProxyCredentials ( baos , uc , encoding ) ; baos . close ( ) ; channel . write ( ByteBuffer . wrap ( baos . toByteArray ( ) ) ) ; channel . close ( ) ; raf . close ( ) ; } | Saves proxy credentials to a file . This method ensures that the stored proxy is saved with the appropriate file permissions . | 168 | 23 |
141,640 | Collection < Session > getValidSessionsElseRemove ( String httpid , Predicate < Session > predicat ) { Collection < Session > wss = new ArrayList ( ) ; if ( httpid_wss . containsKey ( httpid ) ) { Collection < Session > befores = httpid_wss . get ( httpid ) ; for ( Session before : befores ) { if ( predicat . test ( before ) ) { wss . add ( before ) ; wsid_httpid . put ( before . getId ( ) , httpid ) ; } else { wsid_httpid . remove ( before . getId ( ) ) ; } } if ( wss . isEmpty ( ) ) { httpid_wss . remove ( httpid ) ; } else { httpid_wss . put ( httpid , wss ) ; } } return wss ; } | Return all sessions for httpid and for the predicate if some session negate the predicate its are removed | 188 | 19 |
141,641 | public static void checkPrivateKeyPermissions ( String privateKeyFile ) throws IOException { for ( PosixFilePermission p : PRIVATE_KEY_PERMS ) { try { matchesFilePermissions ( privateKeyFile , p ) ; return ; } catch ( FilePermissionError e ) { } } final String errorMessage = String . format ( "Wrong file permissions on file %s. Required permissions are: %s " , privateKeyFile , PRIVATE_KEY_PERMS_STR ) ; throw new FilePermissionError ( errorMessage ) ; } | Checks whether a private key file has the right permissions | 120 | 11 |
141,642 | public static void matchesFilePermissions ( String filename , PosixFilePermission p ) throws IOException { filenameSanityChecks ( filename ) ; if ( p == null ) throw new NullPointerException ( "null permission passed as argument" ) ; File f = new File ( filename ) ; // Don't get fooled by symlinks... String canonicalPath = f . getCanonicalPath ( ) ; String filePerms = getFilePermissions ( canonicalPath ) ; if ( ! filePerms . startsWith ( p . statForm ) ) throw new FilePermissionError ( "Wrong file permissions on file " + filename + ". Required permissions are: " + p . chmodForm ( ) ) ; } | Checks that a given file has the appropriate unix permissions . This naive implementation just fetches the output of ls - al on a given file and matches the resulting string with the permissionString passed as argument . | 150 | 42 |
141,643 | public String getMd5 ( String msg ) { MessageDigest md ; try { md = getMessageDigest ( ) ; byte [ ] hash = md . digest ( msg . getBytes ( StandardCharsets . UTF_8 ) ) ; //converting byte array to Hexadecimal String StringBuilder sb = new StringBuilder ( 2 * hash . length ) ; for ( byte b : hash ) { sb . append ( String . format ( "%02x" , b & 0xff ) ) ; } return sb . toString ( ) ; } catch ( NoSuchAlgorithmException ex ) { logger . error ( "Fail to get MD5 of String " + msg , ex ) ; } return null ; } | Create a md5 from string | 153 | 6 |
141,644 | Locale getLocale ( HandshakeRequest request ) { if ( null != request ) { Map < String , List < String > > headers = request . getHeaders ( ) ; if ( null != headers ) { List < String > accepts = headers . get ( HttpHeaders . ACCEPT_LANGUAGE ) ; logger . debug ( "Get accept-language from client headers : {}" , accepts ) ; if ( null != accepts ) { for ( String accept : accepts ) { try { return localeExtractor . extractFromAccept ( accept ) ; } catch ( LocaleNotFoundException ex ) { } } } } } return Locale . US ; } | Return locale of client | 141 | 4 |
141,645 | @ Override public void modifyHandshake ( ServerEndpointConfig sec , HandshakeRequest request , HandshakeResponse response ) { sec . getUserProperties ( ) . put ( Constants . HANDSHAKEREQUEST , request ) ; super . modifyHandshake ( sec , request , response ) ; } | Set user information from open websocket | 65 | 7 |
141,646 | @ Override public boolean sendMessageToClient ( MessageFromClient message , Session client ) { MessageToClient mtc = messageToClientService . createMessageToClient ( message , client ) ; if ( mtc != null ) { client . getAsyncRemote ( ) . sendObject ( mtc ) ; return true ; } return false ; } | Build and send response messages after call request | 71 | 8 |
141,647 | protected void onBlock ( ConnectionFilter filter , String remoteAddr , int connections , int requests , int bytes ) { filter . disconnect ( ) ; filter . onDisconnect ( ) ; } | Called when connections requests or bytes reach to the limit . | 39 | 12 |
141,648 | public void setParameters ( int period , int connections , int requests , int bytes ) { this . period = period ; this . connections_ = connections ; this . requests_ = requests ; this . bytes_ = bytes ; } | Reset the parameters | 46 | 4 |
141,649 | public void sendObjectToTopic ( @ Observes @ JsTopicEvent ( "" ) Object payload , EventMetadata metadata ) { MessageToClient msg = new MessageToClient ( ) ; InjectionPoint injectionPoint = metadata . getInjectionPoint ( ) ; Annotated annotated = injectionPoint . getAnnotated ( ) ; JsTopicEvent jte = annotated . getAnnotation ( JsTopicEvent . class ) ; if ( jte != null ) { String topic = jte . value ( ) ; msg . setId ( topic ) ; JsonMarshaller jm = annotated . getAnnotation ( JsonMarshaller . class ) ; try { if ( jm != null ) { msg . setJson ( argumentServices . getJsonResultFromSpecificMarshaller ( jm , payload ) ) ; } else if ( jte . jsonPayload ( ) ) { if ( ! String . class . isInstance ( payload ) ) { throw new UnsupportedOperationException ( "'" + payload + "' cannot be a json object. Field annotated JsTopicEvent(jsonPayload=true) must be Event<String> type and fire correct Json." ) ; } msg . setJson ( ( String ) payload ) ; } else { msg . setResponse ( payload ) ; } topicsMessagesBroadcaster . sendMessageToTopic ( msg , payload ) ; } catch ( JsonMarshallingException ex ) { logger . error ( "'" + payload + "' cannot be send to : '" + topic + "'. It cannot be serialized with marshaller " + jm , ex ) ; } catch ( Throwable ex ) { logger . error ( "'" + payload + "' cannot be send to : '" + topic + "'." , ex ) ; } } } | Send message to topic | 382 | 4 |
141,650 | public void processJsCacheRemoveAll ( ) { logger . debug ( "Process JsCacheRemoveAll annotation" ) ; MessageToClient messageToClient = new MessageToClient ( ) ; messageToClient . setId ( Constants . Cache . CLEANCACHE_TOPIC ) ; messageToClient . setResponse ( Constants . Cache . ALL ) ; wsEvent . fire ( messageToClient ) ; } | Process annotation JsCacheRemoveAll and send message for suppress all the cache | 87 | 15 |
141,651 | public void processJsCacheRemove ( JsCacheRemove jcr , List < String > paramNames , List < String > jsonArgs ) { logger . debug ( "Process JsCacheRemove annotation : {}" , jcr ) ; MessageToClient messageToClient = new MessageToClient ( ) ; messageToClient . setId ( Constants . Cache . CLEANCACHE_TOPIC ) ; String argpart = cacheArgumentServices . computeArgPart ( jcr . keys ( ) , jsonArgs , paramNames ) ; String cachekey = computeCacheKey ( jcr . cls ( ) , jcr . methodName ( ) , argpart ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "JsonArgs from Call : {}" , Arrays . toString ( jsonArgs . toArray ( new String [ jsonArgs . size ( ) ] ) ) ) ; logger . debug ( "ParamName from considerated method : {}" , Arrays . toString ( paramNames . toArray ( new String [ paramNames . size ( ) ] ) ) ) ; logger . debug ( "Computed key : {}" , cachekey ) ; } messageToClient . setResponse ( cachekey ) ; if ( jcr . userScope ( ) ) { wsUserEvent . fire ( messageToClient ) ; } else { wsEvent . fire ( messageToClient ) ; cacheEvent . fire ( cachekey ) ; } } | Process an annotation JsCacheRemove and send a removeCache message to all clients connected | 306 | 17 |
141,652 | String computeCacheKey ( Class cls , String methodName , String argpart ) { String cachekey = keyMaker . getMd5 ( cls . getName ( ) + "." + methodName ) ; if ( ! argpart . isEmpty ( ) ) { cachekey += "_" + keyMaker . getMd5 ( argpart ) ; } logger . debug ( "CACHEID : {}.{}_{} = {}" , cls . getName ( ) , methodName , argpart , cachekey ) ; return cachekey ; } | Compute the cache key from classname methodname and args | 119 | 12 |
141,653 | public long processCacheAnnotations ( Method nonProxiedMethod , List < String > parameters ) { if ( isJsCached ( nonProxiedMethod ) ) { return jsCacheAnnotationServices . getJsCacheResultDeadline ( nonProxiedMethod . getAnnotation ( JsCacheResult . class ) ) ; } return 0L ; } | Process annotations JsCacheResult JsCacheRemove and JsCacheRemoves | 75 | 16 |
141,654 | boolean isJsCached ( Method nonProxiedMethod ) { boolean cached = nonProxiedMethod . isAnnotationPresent ( JsCacheResult . class ) ; logger . debug ( "The result of the method {} should be cached on client side {}." , nonProxiedMethod . getName ( ) , cached ) ; return cached ; } | Check if result should be cached in front - end | 75 | 10 |
141,655 | public void readDashboardRolesConfig ( @ Observes @ Initialized ( ApplicationScoped . class ) ServletContext sc ) { readFromConfigurationRoles ( ) ; readFromInitParameter ( sc ) ; logger . debug ( "'{}' value : '{}'." , Constants . Options . DASHBOARD_ROLES , roles ) ; } | Read in web . xml and differents producers the optional DASHBOARD_ROLES config and set it in OcelotConfiguration | 77 | 28 |
141,656 | public Fault buildFault ( Throwable ex ) { Fault fault ; int stacktracelength = configuration . getStacktracelength ( ) ; if ( stacktracelength == 0 || logger . isDebugEnabled ( ) ) { logger . error ( "Invocation failed" , ex ) ; } fault = new Fault ( ex , stacktracelength ) ; return fault ; } | Build an fault Object from exception with stacktrace length from configuration | 83 | 12 |
141,657 | public void print ( final PrintStream out , final ICodingAnnotationStudy study , final ICodingAnnotationItem item ) { Map < Object , Map < Object , Double > > coincidence = CodingAnnotationStudy . countCategoryCoincidence ( item ) ; doPrint ( out , study , coincidence ) ; } | Print the coincidence matrix for the given annotation item . | 65 | 10 |
141,658 | public void print ( final PrintStream out , final Iterable < Object > categories , final IDistanceFunction distanceFunction ) { doPrint ( out , categories , null , distanceFunction ) ; } | Print a matrix of the distances between each pair of categories . | 39 | 12 |
141,659 | public void print ( final PrintStream out , final ICodingAnnotationStudy study , final IDistanceFunction distanceFunction ) { doPrint ( out , study . getCategories ( ) , study , distanceFunction ) ; } | Print a matrix representation of the distances between each pair of categories of the given study . | 45 | 17 |
141,660 | private boolean isViewElementFindableOrList ( Field field ) { Class < ? > fieldType = field . getType ( ) ; return View . class . isAssignableFrom ( fieldType ) || Element . class . isAssignableFrom ( fieldType ) || Findable . class . isAssignableFrom ( fieldType ) || List . class . isAssignableFrom ( fieldType ) ; } | Those are only supported types which make sense to look at . | 87 | 12 |
141,661 | private boolean isRequired ( Field field ) { return field . getAnnotation ( Require . class ) != null // Use the field's declaring class for RequireAll; may be a super class || ( field . getDeclaringClass ( ) . getAnnotation ( RequireAll . class ) != null && field . getAnnotation ( NotRequired . class ) == null ) ; } | Determines whether a field is required or not based on combination of Require RequireAll and NotRequired annotations . | 80 | 24 |
141,662 | public String getLiteralType ( Type type ) { String result = "" ; if ( type != null ) { if ( ParameterizedType . class . isAssignableFrom ( type . getClass ( ) ) ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; result = parameterizedType . toString ( ) ; } else { result = ( ( Class ) type ) . getCanonicalName ( ) ; } } return result ; } | Return human reading of type | 101 | 5 |
141,663 | public IJsonMarshaller getJsonMarshaller ( Annotation [ ] annotations ) throws JsonMarshallerException { if ( annotations != null ) { for ( Annotation annotation : annotations ) { if ( JsonUnmarshaller . class . isAssignableFrom ( annotation . annotationType ( ) ) ) { return getJsonMarshallerFromAnnotation ( ( JsonUnmarshaller ) annotation ) ; } } } return null ; } | Return JsonUnmarshaller instance if annotation JsonUnmarshaller is present | 101 | 20 |
141,664 | public IJsonMarshaller getJsonMarshallerFromAnnotation ( JsonUnmarshaller jua ) throws JsonMarshallerException { if ( jua != null ) { return argumentServices . getIJsonMarshallerInstance ( jua . value ( ) ) ; } return null ; } | Return JsonUnmarshaller instance from annotation JsonUnmarshaller | 68 | 18 |
141,665 | public String getInstanceNameFromDataservice ( Class cls ) { DataService dataService = ( DataService ) cls . getAnnotation ( DataService . class ) ; String clsName = dataService . name ( ) ; if ( clsName . isEmpty ( ) ) { clsName = cls . getSimpleName ( ) ; } return getInstanceName ( clsName ) ; } | Get instancename from Dataservice Class | 87 | 10 |
141,666 | public boolean isConsiderateMethod ( Method method ) { if ( method . isAnnotationPresent ( TransientDataService . class ) || method . isAnnotationPresent ( WsDataService . class ) || method . getDeclaringClass ( ) . isAssignableFrom ( Object . class ) ) { return false ; } int modifiers = method . getModifiers ( ) ; return Modifier . isPublic ( modifiers ) && ! Modifier . isStatic ( modifiers ) ; } | Method is expose to frontend ? | 100 | 7 |
141,667 | Object getInstanceOfClass ( Class cls ) { if ( Boolean . class . isAssignableFrom ( cls ) || Boolean . TYPE . isAssignableFrom ( cls ) ) { return Boolean . FALSE ; } else if ( Integer . TYPE . isAssignableFrom ( cls ) || Short . TYPE . isAssignableFrom ( cls ) || Integer . class . isAssignableFrom ( cls ) || Short . class . isAssignableFrom ( cls ) ) { return 0 ; } else if ( Long . TYPE . isAssignableFrom ( cls ) || Long . class . isAssignableFrom ( cls ) ) { return 0L ; } else if ( Float . TYPE . isAssignableFrom ( cls ) || Float . class . isAssignableFrom ( cls ) ) { return 0.1F ; } else if ( Double . TYPE . isAssignableFrom ( cls ) || Double . class . isAssignableFrom ( cls ) ) { return 0.1D ; } else if ( cls . isArray ( ) ) { Class < ? > comp = cls . getComponentType ( ) ; Object instance = getInstanceOfClass ( comp ) ; return new Object [ ] { instance , instance } ; } else { try { return cls . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException ex ) { return getObjectFromConstantFields ( cls ) ; } } } | Get instance for classic class | 319 | 5 |
141,668 | Object getObjectFromConstantFields ( Class cls ) { Field [ ] fields = cls . getFields ( ) ; Object instance = null ; for ( Field field : fields ) { instance = getObjectFromConstantField ( cls , field ) ; if ( instance != null ) { break ; } } return instance ; } | If the class has not empty constructor look static field if it return instance | 71 | 14 |
141,669 | String getTemplateOfParameterizedType ( ParameterizedType parameterizedType , IJsonMarshaller jsonMarshaller ) { Class cls = ( Class ) parameterizedType . getRawType ( ) ; Type [ ] actualTypeArguments = parameterizedType . getActualTypeArguments ( ) ; String res ; if ( Iterable . class . isAssignableFrom ( cls ) ) { res = getTemplateOfIterable ( actualTypeArguments , jsonMarshaller ) ; } else if ( Map . class . isAssignableFrom ( cls ) ) { res = getTemplateOfMap ( actualTypeArguments , jsonMarshaller ) ; } else { res = cls . getSimpleName ( ) . toLowerCase ( Locale . ENGLISH ) ; } return res ; } | Get template from parameterizedType | 174 | 6 |
141,670 | String getTemplateOfIterable ( Type [ ] actualTypeArguments , IJsonMarshaller jsonMarshaller ) { String res = "[" ; for ( Type actualTypeArgument : actualTypeArguments ) { String template = _getTemplateOfType ( actualTypeArgument , jsonMarshaller ) ; res += template + "," + template ; break ; } return res + "]" ; } | Get template of iterable class from generic type | 86 | 9 |
141,671 | String getTemplateOfMap ( Type [ ] actualTypeArguments , IJsonMarshaller jsonMarshaller ) { StringBuilder res = new StringBuilder ( "{" ) ; boolean first = true ; for ( Type actualTypeArgument : actualTypeArguments ) { if ( ! first ) { res . append ( ":" ) ; } res . append ( _getTemplateOfType ( actualTypeArgument , jsonMarshaller ) ) ; first = false ; } res . append ( "}" ) ; return res . toString ( ) ; } | Get template of map class from generic type | 116 | 8 |
141,672 | String getInstanceName ( String clsName ) { return clsName . substring ( 0 , 1 ) . toLowerCase ( Locale . ENGLISH ) + clsName . substring ( 1 ) ; } | Get instancename from clasname | 47 | 8 |
141,673 | public static < T > Builder < T , ItemListBox < T > > builder ( ) { return new Builder < T , ItemListBox < T > > ( new ItemListBox < T > ( ) ) ; } | Creates a new builder for an ItemListBox . | 46 | 11 |
141,674 | public boolean removeItem ( T item ) { int index = _items . indexOf ( item ) ; if ( index == - 1 ) { return false ; } _items . remove ( index ) ; removeItem ( index ) ; return true ; } | Removes the supplied item from this list box returning true if the item was found . | 51 | 17 |
141,675 | protected static boolean addRow ( SmartTable table , List < Widget > widgets ) { if ( widgets == null ) { return false ; } int row = table . getRowCount ( ) ; for ( int col = 0 ; col < widgets . size ( ) ; ++ col ) { table . setWidget ( row , col , widgets . get ( col ) ) ; table . getFlexCellFormatter ( ) . setStyleName ( row , col , "col" + col ) ; } return true ; } | Convenience function to append a list of widgets to a table as a new row . | 107 | 18 |
141,676 | protected Field findField ( ) throws FinderFieldNotFoundException { try { if ( fieldName != null ) { return beanType . getField ( fieldName ) ; } try { return beanType . getField ( "find" ) ; } catch ( NoSuchFieldException e ) { return beanType . getField ( "FIND" ) ; } } catch ( NoSuchFieldException e ) { throw new FinderFieldNotFoundException ( e ) ; } } | Find and return the find field . | 96 | 7 |
141,677 | public void setCellAlignment ( HasAlignment . HorizontalAlignmentConstant horiz , HasAlignment . VerticalAlignmentConstant vert ) { _cellHorizAlign = horiz ; _cellVertAlign = vert ; } | Configures the horizontal and vertical alignment of cells . This must be called before the grid is displayed . | 51 | 20 |
141,678 | protected void formatCell ( HTMLTable . CellFormatter formatter , int row , int col , int limit ) { formatter . setHorizontalAlignment ( row , col , _cellHorizAlign ) ; formatter . setVerticalAlignment ( row , col , _cellVertAlign ) ; formatter . setStyleName ( row , col , "Cell" ) ; if ( row == ( limit - 1 ) / _cols ) { formatter . addStyleName ( row , col , "BottomCell" ) ; } else if ( row == 0 ) { formatter . addStyleName ( row , col , "TopCell" ) ; } else { formatter . addStyleName ( row , col , "MiddleCell" ) ; } } | Configures the formatting for a particular cell based on its location in the grid . | 161 | 16 |
141,679 | @ SuppressWarnings ( "unchecked" ) < C , T > Stage < T > doCollectEmpty ( final Function < ? super Collection < C > , ? extends T > collector ) { try { return this . completed ( collector . apply ( ( Collection < C > ) EMPTY_RESULTS ) ) ; } catch ( Exception e ) { return failed ( e ) ; } } | Shortcut for when the list of stages is empty . | 81 | 11 |
141,680 | < T , U > Stage < U > doStreamCollectEmpty ( final Consumer < ? super T > consumer , final Supplier < ? extends U > supplier ) { try { return this . completed ( supplier . get ( ) ) ; } catch ( Exception e ) { return failed ( e ) ; } } | Shortcut for when the list of stages is empty with stream collector . | 63 | 14 |
141,681 | < T , U > Stage < U > doStreamCollect ( final Collection < ? extends Stage < ? extends T > > stages , final Consumer < ? super T > consumer , final Supplier < ? extends U > supplier ) { final Completable < U > target = completable ( ) ; final StreamCollectHelper < ? super T , ? extends U > done = new StreamCollectHelper <> ( caller , stages . size ( ) , consumer , supplier , target ) ; for ( final Stage < ? extends T > q : stages ) { q . handle ( done ) ; } bindSignals ( target , stages ) ; return target ; } | Perform collection for stream collector . | 133 | 7 |
141,682 | < T , U > Stage < U > doEventuallyCollect ( final Collection < ? extends Callable < ? extends Stage < ? extends T > > > tasks , final Consumer < ? super T > consumer , Supplier < ? extends U > supplier , int parallelism ) { final ExecutorService executor = executor ( ) ; final Completable < U > stage = completable ( ) ; executor . execute ( new DelayedCollectCoordinator <> ( caller , tasks , consumer , supplier , stage , parallelism ) ) ; return stage ; } | Perform an eventual collection . | 116 | 6 |
141,683 | Stage < Void > doCollectAndDiscard ( Collection < ? extends Stage < ? > > stages ) { final Completable < Void > target = completable ( ) ; final CollectAndDiscardHelper done = new CollectAndDiscardHelper ( stages . size ( ) , target ) ; for ( final Stage < ? > q : stages ) { q . handle ( done ) ; } bindSignals ( target , stages ) ; return target ; } | Perform a collect and discard . | 93 | 7 |
141,684 | void bindSignals ( final Stage < ? > target , final Collection < ? extends Stage < ? > > stages ) { target . whenCancelled ( ( ) -> { for ( final Stage < ? > f : stages ) { f . cancel ( ) ; } } ) ; } | Bind the given collection of stages to the target completable which if cancelled or failed will do the corresponding to their collection of stages . | 59 | 26 |
141,685 | public void onFailure ( Throwable cause ) { Console . log ( "Callback failure" , "for" , _trigger , cause ) ; setEnabled ( true ) ; reportFailure ( cause ) ; } | from interface AsyncCallback | 42 | 5 |
141,686 | public ClickCallback < T > setConfirmChoices ( String confirm , String abort ) { _confirmChoices = new String [ ] { confirm , abort } ; return this ; } | Configures the choices to be shown in the confirmation dialog . | 39 | 12 |
141,687 | protected void showError ( Throwable cause , Widget near ) { if ( near == null ) { Popups . error ( formatError ( cause ) ) ; } else { Popups . errorBelow ( formatError ( cause ) , near ) ; } } | Displays a popup reporting the specified error near the specified widget if it is non - null . | 53 | 19 |
141,688 | protected int addConfirmPopupMessage ( SmartTable contents , int row ) { if ( _confirmHTML ) { contents . setHTML ( row , 0 , _confirmMessage , 2 , "Message" ) ; } else { contents . setText ( row , 0 , _confirmMessage , 2 , "Message" ) ; } return row + 1 ; } | Adds the message area for the confirmation popup to the given row and returns the row to insert next . | 77 | 20 |
141,689 | private void createEnhancingMethods ( final Class < ? > resourceClass , final Object resourceInstance , final List < ModelProcessorUtil . Method > newMethods ) { final Template template = resourceClass . getAnnotation ( Template . class ) ; if ( template != null ) { final Class < ? > annotatedResourceClass = ModelHelper . getAnnotatedResourceClass ( resourceClass ) ; final List < MediaType > produces = MediaTypes . createQualitySourceMediaTypes ( annotatedResourceClass . getAnnotation ( Produces . class ) ) ; final List < MediaType > consumes = MediaTypes . createFrom ( annotatedResourceClass . getAnnotation ( Consumes . class ) ) ; final TemplateInflectorImpl inflector = new TemplateInflectorImpl ( template . name ( ) , resourceClass , resourceInstance ) ; newMethods . add ( new ModelProcessorUtil . Method ( HttpMethod . GET , consumes , produces , inflector ) ) ; newMethods . add ( new ModelProcessorUtil . Method ( IMPLICIT_VIEW_PATH_PARAMETER_TEMPLATE , HttpMethod . GET , consumes , produces , inflector ) ) ; } } | Creates enhancing methods for given resource . | 255 | 8 |
141,690 | public void setHref ( String href ) { if ( _forceProtocol ) { // This will correct URLs that don't have http:// as well // as provide protection against JS injection if ( ! href . matches ( "^\\s*\\w+://.*" ) ) { href = "http://" + href ; } } else { // Always do some sort of JS protection if ( href . trim ( ) . toLowerCase ( ) . startsWith ( "javascript:" ) ) { // He's been a naughty boy href = "#" ; } } DOM . setElementProperty ( getElement ( ) , "href" , href ) ; } | Set the href location . | 136 | 5 |
141,691 | public static Document prepareForCloning ( Document domainXml ) { XPathFactory xpf = XPathFactory . instance ( ) ; // remove uuid so it will be generated domainXml . getRootElement ( ) . removeChild ( "uuid" ) ; // remove mac address, so it will be generated XPathExpression < Element > macExpr = xpf . compile ( "/domain/devices/interface/mac" , Filters . element ( ) ) ; for ( Element mac : macExpr . evaluate ( domainXml ) ) { mac . getParentElement ( ) . removeChild ( "mac" ) ; } return domainXml ; } | remove elements that need to be unique per clone . | 140 | 10 |
141,692 | public static void join ( Object strand , long timeout , TimeUnit unit ) throws ExecutionException , InterruptedException , TimeoutException { Strand . join ( strand , timeout , unit ) ; } | Awaits the termination of a given strand at most for the timeout duration specified . This method blocks until this strand terminates or the timeout elapses . | 40 | 31 |
141,693 | static void log ( Object targetObj , String msg ) { if ( EventsParams . isDebug ( ) ) { Log . d ( TAG , toLogStr ( targetObj , msg ) ) ; } } | Logs target object | 43 | 4 |
141,694 | static void logE ( Object targetObj , String msg ) { Log . e ( TAG , toLogStr ( targetObj , msg ) ) ; } | Logs target object error | 31 | 5 |
141,695 | static void logE ( String eventKey , String msg ) { Log . e ( TAG , toLogStr ( eventKey , msg ) ) ; } | Logs event error | 31 | 4 |
141,696 | private static JFreeChart createChart ( String title , String xAxis , String yAxis1 , XYDataset dataset1 , String yAxis2 , XYDataset dataset2 ) { JFreeChart chart = ChartFactory . createXYLineChart ( title , xAxis , yAxis1 , dataset1 , PlotOrientation . VERTICAL , true , true , false ) ; final XYPlot plot = ( XYPlot ) chart . getPlot ( ) ; plot . setBackgroundPaint ( Color . lightGray ) ; plot . setDomainGridlinePaint ( Color . white ) ; plot . setRangeGridlinePaint ( Color . white ) ; plot . setAxisOffset ( new RectangleInsets ( 5.0 , 5.0 , 5.0 , 5.0 ) ) ; plot . setDomainCrosshairVisible ( true ) ; plot . setRangeCrosshairVisible ( true ) ; final XYItemRenderer r = plot . getRenderer ( ) ; int count = Math . min ( dataset1 . getSeriesCount ( ) , dataset2 . getSeriesCount ( ) ) ; if ( r instanceof XYLineAndShapeRenderer ) { XYLineAndShapeRenderer renderer = ( XYLineAndShapeRenderer ) r ; renderer . setBaseStroke ( LINE ) ; renderer . setAutoPopulateSeriesPaint ( false ) ; renderer . setBaseShapesVisible ( false ) ; renderer . setBaseShapesFilled ( false ) ; renderer . setDrawSeriesLineAsPath ( true ) ; for ( int i = 0 ; i < count ; i ++ ) { renderer . setSeriesPaint ( i , COLORS . get ( i % COLORS . size ( ) ) ) ; } } chart . setBackgroundPaint ( Color . white ) ; // chart two { final NumberAxis axis2 = new NumberAxis ( yAxis2 ) ; axis2 . setAutoRangeIncludesZero ( false ) ; plot . setRangeAxis ( 1 , axis2 ) ; plot . setDataset ( 1 , dataset2 ) ; plot . mapDatasetToRangeAxis ( 1 , 1 ) ; final StandardXYItemRenderer renderer = new StandardXYItemRenderer ( ) ; renderer . setAutoPopulateSeriesPaint ( false ) ; renderer . setAutoPopulateSeriesStroke ( false ) ; renderer . setBaseShapesVisible ( false ) ; renderer . setBaseShapesFilled ( false ) ; renderer . setDrawSeriesLineAsPath ( true ) ; renderer . setBaseStroke ( DASHED ) ; for ( int i = 0 ; i < count ; i ++ ) { renderer . setSeriesPaint ( i , COLORS . get ( i % COLORS . size ( ) ) ) ; } plot . setRenderer ( 1 , renderer ) ; } return chart ; } | Creates a chart . | 634 | 5 |
141,697 | public static void showChart ( String name , String xAxis , String yAxis1 , XYDataset dataset1 , String yAxis2 , XYDataset dataset2 ) { final JFreeChart chart = createChart ( name , xAxis , yAxis1 , dataset1 , yAxis2 , dataset2 ) ; final ChartPanel chartPanel = createPanel ( chart ) ; final ApplicationFrame app = new ApplicationFrame ( name ) ; chartPanel . setPreferredSize ( new java . awt . Dimension ( 500 , 270 ) ) ; app . setContentPane ( chartPanel ) ; app . pack ( ) ; RefineryUtilities . centerFrameOnScreen ( app ) ; app . setVisible ( true ) ; } | Starting point for the demonstration application . | 159 | 7 |
141,698 | public void submit ( final Metric metric ) { if ( metric != null ) { LOGGER . debug ( "Collecting metric: {}" , metric ) ; queue . offer ( metric ) ; } } | Submits a metric to the queue | 42 | 7 |
141,699 | public int flush ( final MetricSender sender ) throws IOException , HttpException { Preconditions . checkNotNull ( sender ) ; // aggregate metrics that were enqueued before the current minute long currentMinute = ( System . currentTimeMillis ( ) / MS_IN_MIN ) * MS_IN_MIN ; LOGGER . debug ( "Flushing metrics < {}" , currentMinute ) ; LOGGER . debug ( "Metrics queue size {}" , queue . size ( ) ) ; MetricAggregator aggregator = new MetricAggregator ( currentMinute , lastValues ) ; while ( ( ! queue . isEmpty ( ) ) && ( queue . peek ( ) . getOccurredMillis ( ) < currentMinute ) ) { aggregator . add ( queue . remove ( ) ) ; } // handle the auto reports if ( lastFlush < currentMinute ) { aggregator . autoReportZero ( autoReportZeroMetrics ) ; aggregator . autoReportLast ( autoReportLastMetrics ) ; } lastFlush = currentMinute ; // get the aggregates List < MetricAggregate > aggregates = aggregator . getAggregates ( ) ; // Save the values of gauge and average metrics for the next iteration // Gauge last value = aggregate last value // Average last value = aggregate last value / aggregate count if ( ( aggregates != null ) && ( ! aggregates . isEmpty ( ) ) ) { for ( MetricAggregate aggregate : aggregates ) { if ( aggregate . getIdentity ( ) . getType ( ) . equals ( MetricMonitorType . GAUGE ) ) { lastValues . put ( aggregate . getIdentity ( ) , aggregate . getValue ( ) ) ; } else if ( aggregate . getIdentity ( ) . getType ( ) . equals ( MetricMonitorType . AVERAGE ) ) { lastValues . put ( aggregate . getIdentity ( ) , aggregate . getValue ( ) / aggregate . getCount ( ) ) ; } } } // send the aggregates to Stackify int numSent = 0 ; if ( ( aggregates != null ) && ( ! aggregates . isEmpty ( ) ) ) { LOGGER . debug ( "Sending aggregate metrics: {}" , aggregates ) ; sender . send ( aggregates ) ; numSent = aggregates . size ( ) ; } return numSent ; } | Flushes all queued metrics to Stackify | 507 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.