idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
18,200 | 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 . |
18,201 | 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 . |
18,202 | 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 |
18,203 | public void saveToCache ( String topic , Class < ? extends JsTopicMessageController > cls ) { if ( null != topic && null != cls ) { messageControllers . put ( topic , cls ) ; } } | Save messageController Factory for topic |
18,204 | 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 |
18,205 | 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 . |
18,206 | 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 . |
18,207 | 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 . |
18,208 | 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 . |
18,209 | 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 |
18,210 | 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 |
18,211 | 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 |
18,212 | 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 |
18,213 | 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 |
18,214 | 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 |
18,215 | JsTopicName getJsTopicNameAnnotation ( Annotation [ ] parameterAnnotations ) { for ( Annotation parameterAnnotation : parameterAnnotations ) { if ( parameterAnnotation . annotationType ( ) . equals ( JsTopicName . class ) ) { return ( JsTopicName ) parameterAnnotation ; } } return null ; } | Get JsTopicName annotation |
18,216 | 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 |
18,217 | 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 |
18,218 | 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 . |
18,219 | 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 . |
18,220 | 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 . |
18,221 | 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 . |
18,222 | 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 . |
18,223 | 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 |
18,224 | 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 |
18,225 | 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 ) ; 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 . |
18,226 | public String getMd5 ( String msg ) { MessageDigest md ; try { md = getMessageDigest ( ) ; byte [ ] hash = md . digest ( msg . getBytes ( StandardCharsets . UTF_8 ) ) ; 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 |
18,227 | 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 |
18,228 | 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 |
18,229 | 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 |
18,230 | 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 . |
18,231 | 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 |
18,232 | public void sendObjectToTopic ( @ 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 |
18,233 | 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 |
18,234 | 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 |
18,235 | 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 |
18,236 | 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 |
18,237 | 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 |
18,238 | public void readDashboardRolesConfig ( @ 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 |
18,239 | 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 |
18,240 | 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 . |
18,241 | 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 . |
18,242 | 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 . |
18,243 | 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 . |
18,244 | private boolean isRequired ( Field field ) { return field . getAnnotation ( Require . class ) != null || ( 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 . |
18,245 | 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 |
18,246 | 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 |
18,247 | public IJsonMarshaller getJsonMarshallerFromAnnotation ( JsonUnmarshaller jua ) throws JsonMarshallerException { if ( jua != null ) { return argumentServices . getIJsonMarshallerInstance ( jua . value ( ) ) ; } return null ; } | Return JsonUnmarshaller instance from annotation JsonUnmarshaller |
18,248 | 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 |
18,249 | 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 ? |
18,250 | 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 |
18,251 | 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 |
18,252 | 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 |
18,253 | 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 |
18,254 | 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 |
18,255 | String getInstanceName ( String clsName ) { return clsName . substring ( 0 , 1 ) . toLowerCase ( Locale . ENGLISH ) + clsName . substring ( 1 ) ; } | Get instancename from clasname |
18,256 | public static < T > Builder < T , ItemListBox < T > > builder ( ) { return new Builder < T , ItemListBox < T > > ( new ItemListBox < T > ( ) ) ; } | Creates a new builder for an ItemListBox . |
18,257 | 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 . |
18,258 | 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 . |
18,259 | 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 . |
18,260 | 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 . |
18,261 | 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 . |
18,262 | @ 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 . |
18,263 | < 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 . |
18,264 | < 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 . |
18,265 | < 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 . |
18,266 | 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 . |
18,267 | 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 . |
18,268 | public void onFailure ( Throwable cause ) { Console . log ( "Callback failure" , "for" , _trigger , cause ) ; setEnabled ( true ) ; reportFailure ( cause ) ; } | from interface AsyncCallback |
18,269 | 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 . |
18,270 | 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 . |
18,271 | 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 . |
18,272 | 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 . |
18,273 | public void setHref ( String href ) { if ( _forceProtocol ) { if ( ! href . matches ( "^\\s*\\w+://.*" ) ) { href = "http://" + href ; } } else { if ( href . trim ( ) . toLowerCase ( ) . startsWith ( "javascript:" ) ) { href = "#" ; } } DOM . setElementProperty ( getElement ( ) , "href" , href ) ; } | Set the href location . |
18,274 | public static Document prepareForCloning ( Document domainXml ) { XPathFactory xpf = XPathFactory . instance ( ) ; domainXml . getRootElement ( ) . removeChild ( "uuid" ) ; 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 . |
18,275 | 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 . |
18,276 | static void log ( Object targetObj , String msg ) { if ( EventsParams . isDebug ( ) ) { Log . d ( TAG , toLogStr ( targetObj , msg ) ) ; } } | Logs target object |
18,277 | static void logE ( Object targetObj , String msg ) { Log . e ( TAG , toLogStr ( targetObj , msg ) ) ; } | Logs target object error |
18,278 | static void logE ( String eventKey , String msg ) { Log . e ( TAG , toLogStr ( eventKey , msg ) ) ; } | Logs event error |
18,279 | 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 ) ; { 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 . |
18,280 | 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 . |
18,281 | public void submit ( final Metric metric ) { if ( metric != null ) { LOGGER . debug ( "Collecting metric: {}" , metric ) ; queue . offer ( metric ) ; } } | Submits a metric to the queue |
18,282 | public int flush ( final MetricSender sender ) throws IOException , HttpException { Preconditions . checkNotNull ( sender ) ; 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 ( ) ) ; } if ( lastFlush < currentMinute ) { aggregator . autoReportZero ( autoReportZeroMetrics ) ; aggregator . autoReportLast ( autoReportLastMetrics ) ; } lastFlush = currentMinute ; List < MetricAggregate > aggregates = aggregator . getAggregates ( ) ; 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 ( ) ) ; } } } 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 |
18,283 | public static InfoPopup infoOn ( String message , Widget target ) { return centerOn ( new InfoPopup ( message ) , target ) ; } | Displays an info message centered horizontally on the page and centered vertically on the specified target widget . |
18,284 | public static < T extends PopupPanel > T show ( T popup , Position pos , Widget target ) { popup . setVisible ( false ) ; popup . show ( ) ; int left , top ; switch ( pos ) { case RIGHT : left = target . getAbsoluteLeft ( ) + target . getOffsetWidth ( ) + NEAR_GAP ; break ; default : left = target . getAbsoluteLeft ( ) ; break ; } if ( left + popup . getOffsetWidth ( ) > Window . getClientWidth ( ) ) { left = Math . max ( 0 , Window . getClientWidth ( ) - popup . getOffsetWidth ( ) ) ; } switch ( pos ) { case ABOVE : top = target . getAbsoluteTop ( ) - popup . getOffsetHeight ( ) - NEAR_GAP ; break ; case OVER : top = target . getAbsoluteTop ( ) ; break ; case RIGHT : top = target . getAbsoluteTop ( ) + ( target . getOffsetHeight ( ) - popup . getOffsetHeight ( ) ) / 2 ; break ; default : case BELOW : top = target . getAbsoluteTop ( ) + target . getOffsetHeight ( ) + NEAR_GAP ; break ; } popup . setPopupPosition ( left , top ) ; popup . setVisible ( true ) ; return popup ; } | Shows the supplied popup in the specified position relative to the specified target widget . |
18,285 | public static < T extends PopupPanel > T showAbove ( T popup , Widget target ) { return show ( popup , Position . ABOVE , target ) ; } | Shows the supplied popup panel near the specified target . |
18,286 | public static < T extends PopupPanel > T showOver ( T popup , Widget target ) { return show ( popup , Position . OVER , target ) ; } | Shows the supplied popup panel over the specified target . |
18,287 | public static < T extends PopupPanel > T showBelow ( T popup , Widget target ) { return show ( popup , Position . BELOW , target ) ; } | Shows the supplied popup panel below the specified target . |
18,288 | public static PopupPanel newPopup ( String styleName , Widget contents ) { PopupPanel panel = new PopupPanel ( ) ; panel . setStyleName ( styleName ) ; panel . setWidget ( contents ) ; return panel ; } | Creates and returns a new popup with the specified style name and contents . |
18,289 | public static PopupPanel newPopup ( String styleName , Widget contents , Position pos , Widget target ) { PopupPanel panel = newPopup ( styleName , contents ) ; show ( panel , pos , target ) ; return panel ; } | Creates a new popup with the specified style name and contents and shows it near the specified target widget . Returns the newly created popup . |
18,290 | public static ClickHandler createHider ( final PopupPanel popup ) { return new ClickHandler ( ) { public void onClick ( ClickEvent event ) { popup . hide ( ) ; } } ; } | Creates a click handler that hides the specified popup . Useful when creating popups that behave like menus . |
18,291 | public static void makeDraggable ( HasAllMouseHandlers dragHandle , PopupPanel target ) { DragHandler dragger = new DragHandler ( target ) ; dragHandle . addMouseDownHandler ( dragger ) ; dragHandle . addMouseUpHandler ( dragger ) ; dragHandle . addMouseMoveHandler ( dragger ) ; } | Adds mouse handlers to the specified drag handle that cause the supplied target popup to be dragged around the display . The drag handle is assumed to be a child of the popup . |
18,292 | public void setHTML ( int row , int column , String text , int colSpan , String ... styles ) { setHTML ( row , column , text ) ; if ( colSpan > 0 ) { getFlexCellFormatter ( ) . setColSpan ( row , column , colSpan ) ; } setStyleNames ( row , column , styles ) ; } | Sets the HTML in the specified cell with the specified style and column span . |
18,293 | public int addText ( Object text , int colSpan , String ... styles ) { int row = getRowCount ( ) ; setText ( row , 0 , text , colSpan , styles ) ; return row ; } | Adds text to the bottom row of this table in column zero with the specified column span and style . |
18,294 | public int addWidget ( Widget widget , int colSpan , String ... styles ) { int row = getRowCount ( ) ; setWidget ( row , 0 , widget , colSpan , styles ) ; return row ; } | Adds a widget to the bottom row of this table in column zero with the specified column span and style . |
18,295 | public void setStyleNames ( int row , int column , String ... styles ) { int idx = 0 ; for ( String style : styles ) { if ( idx ++ == 0 ) { getFlexCellFormatter ( ) . setStyleName ( row , column , style ) ; } else { getFlexCellFormatter ( ) . addStyleName ( row , column , style ) ; } } } | Configures the specified style names on the specified row and column . The first style is set as the primary style and additional styles are added onto that . |
18,296 | public void setColumnCellStyles ( int column , String ... styles ) { int rowCount = getRowCount ( ) ; for ( int row = 0 ; row < rowCount ; ++ row ) { setStyleNames ( row , column , styles ) ; } } | Sets the style of all cells in the given column to the given values . The first style is set as the primary style and additional styles are added onto that . |
18,297 | public void removeStyleNames ( int row , int column , String ... styles ) { for ( String style : styles ) { getFlexCellFormatter ( ) . removeStyleName ( row , column , style ) ; } } | Removes the specified style names on the specified row and column . |
18,298 | public MethodCall with ( String name1 , Object arg1 ) { return with ( name1 , arg1 , null , null , null , null ) ; } | Add the single argument . |
18,299 | public MethodCall with ( String name1 , Object arg1 , String name2 , Object arg2 ) { return with ( name1 , arg1 , name2 , arg2 , null , null ) ; } | Add the two arguments . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.