idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
8,700 | public static void export ( String name , Function f ) { export ( GQuery . window , name , f ) ; } | Assign a function to a property of the window object . |
8,701 | public static void export ( JavaScriptObject o , String name , Function f ) { prop ( o , name , ( Object ) ( f != null ? wrapFunction ( f ) : null ) ) ; } | Export a function as a property of a javascript object . |
8,702 | public static NodeList < Element > copyNodeList ( NodeList < Element > oldNodes , NodeList < Element > newNodes , boolean create ) { NodeList < Element > ret = oldNodes == null || create ? JsNodeArray . create ( ) : oldNodes ; JsCache idlist = JsCache . create ( ) ; for ( int i = 0 ; oldNodes != null && i < oldNodes . getLength ( ) ; i ++ ) { Element e = oldNodes . getItem ( i ) ; idlist . put ( e . hashCode ( ) , 1 ) ; if ( create ) { ret . < JsNodeArray > cast ( ) . addNode ( e , i ) ; } } for ( int i = 0 , l = newNodes . getLength ( ) , j = ret . getLength ( ) ; i < l ; i ++ ) { Element e = newNodes . getItem ( i ) ; if ( ! idlist . exists ( e . hashCode ( ) ) ) { ret . < JsNodeArray > cast ( ) . addNode ( newNodes . getItem ( i ) , j ++ ) ; } } return ret ; } | Merge the oldNodes list into the newNodes one . If oldNodes is null a new list will be created and returned . If oldNodes is not null a new list will be created depending on the create flag . |
8,703 | public static Document getOwnerDocument ( Node n ) { return n == null || ! isElement ( n ) ? null : n . getNodeType ( ) == Node . DOCUMENT_NODE ? n . < Document > cast ( ) : n . getOwnerDocument ( ) ; } | Returns the owner document element of an element . |
8,704 | public static boolean isDetached ( Node n ) { assert n != null ; if ( "html" . equalsIgnoreCase ( n . getNodeName ( ) ) ) { return false ; } return ! getOwnerDocument ( n ) . getBody ( ) . isOrHasChild ( n ) ; } | Return whether a node is detached to the DOM . |
8,705 | public static boolean isXML ( Node o ) { return o == null ? false : ! "HTML" . equals ( getOwnerDocument ( o ) . getDocumentElement ( ) . getNodeName ( ) ) ; } | Check if an element is a DOM or a XML node . |
8,706 | public static Properties parseJSON ( String json ) { try { return utilsImpl . parseJSON ( json ) ; } catch ( Exception e ) { if ( ! GWT . isProdMode ( ) ) { System . err . println ( "Error while parsing json: " + e . getMessage ( ) + ".\n" + json ) ; } return Properties . create ( ) ; } } | Parses a json string returning a Object with useful method to get the content . |
8,707 | public static < T > T jsni ( JavaScriptObject jso , String meth , Object ... args ) { return runJavascriptFunction ( jso , meth , args ) ; } | Call any arbitrary function present in a Javascript object . It checks the existence of the function and object hierarchy before executing it . It s very useful in order to avoid writing jsni blocks for very simple snippets . |
8,708 | public static < T > T jsni ( String meth , Object ... args ) { return runJavascriptFunction ( null , meth , args ) ; } | Run any arbitrary function in javascript scope using the window as the base object . It checks the existence of the function and object hierarchy before executing it . It s very useful in order to avoid writing jsni blocks for very simple snippets . |
8,709 | public static < T > T runJavascriptFunction ( JavaScriptObject o , String meth , Object ... args ) { return runJavascriptFunctionImpl ( o , meth , JsObjectArray . create ( ) . add ( args ) . < JsArrayMixed > cast ( ) ) ; } | Call via jsni any arbitrary function present in a Javascript object . |
8,710 | public static String param ( JavaScriptObject js ) { Properties prop = js . cast ( ) ; String ret = "" ; for ( String k : prop . keys ( ) ) { ret += ret . isEmpty ( ) ? "" : "&" ; JsCache o = prop . getArray ( k ) . cast ( ) ; if ( o != null ) { for ( int i = 0 , l = o . length ( ) ; i < l ; i ++ ) { ret += i > 0 ? "&" : "" ; Properties p = o . < JsCache > cast ( ) . getJavaScriptObject ( i ) ; if ( p != null ) { ret += k + "[]=" + p . toJsonString ( ) ; } else { ret += k + "[]=" + o . getString ( i ) ; } } } else { Properties p = prop . getJavaScriptObject ( k ) ; if ( p != null ) { ret += k + "=" + p . tostring ( ) ; } else { String v = prop . getStr ( k ) ; if ( v != null && ! v . isEmpty ( ) && ! "null" . equalsIgnoreCase ( v ) ) { ret += k + "=" + v ; } } } } return ret ; } | Returns a QueryString representation of a JavascriptObject . |
8,711 | public void setStyleProperty ( Element e , String prop , String val ) { if ( "opacity" . equals ( prop ) ) { setOpacity ( e , val ) ; } else { super . setStyleProperty ( e , prop , val ) ; } } | Set the value of a style property of an element . IE needs a special workaround to handle opacity |
8,712 | public static IsProperties create ( String s , boolean fixJson ) { return getFactory ( ) . create ( fixJson ? Properties . wrapPropertiesString ( s ) : s ) ; } | Create an instance of IsProperties a Properties JavaScriptObject in the client side and a proxy object in the JVM . |
8,713 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private < T > T getCustomMarshalledValue ( T toReturn , Method getter , AttributeValue value ) { DynamoDBMarshalling annotation = getter . getAnnotation ( DynamoDBMarshalling . class ) ; Class < ? extends DynamoDBMarshaller < ? extends Object > > marshallerClass = annotation . marshallerClass ( ) ; DynamoDBMarshaller marshaller ; try { marshaller = marshallerClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new DynamoDBMappingException ( "Couldn't instantiate marshaller of class " + marshallerClass , e ) ; } catch ( IllegalAccessException e ) { throw new DynamoDBMappingException ( "Couldn't instantiate marshaller of class " + marshallerClass , e ) ; } return ( T ) marshaller . unmarshall ( getter . getReturnType ( ) , value . getS ( ) ) ; } | Marshalls the custom value given into the proper return type . |
8,714 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private AttributeValue getCustomerMarshallerAttributeValue ( Method getter , Object getterReturnResult ) { DynamoDBMarshalling annotation = getter . getAnnotation ( DynamoDBMarshalling . class ) ; Class < ? extends DynamoDBMarshaller < ? extends Object > > marshallerClass = annotation . marshallerClass ( ) ; DynamoDBMarshaller marshaller ; try { marshaller = marshallerClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new DynamoDBMappingException ( "Failed to instantiate custom marshaller for class " + marshallerClass , e ) ; } catch ( IllegalAccessException e ) { throw new DynamoDBMappingException ( "Failed to instantiate custom marshaller for class " + marshallerClass , e ) ; } String stringValue = marshaller . marshall ( getterReturnResult ) ; return new AttributeValue ( ) . withS ( stringValue ) ; } | Returns an attribute value for the getter method with a custom marshaller |
8,715 | private boolean parseBoolean ( String s ) { if ( "1" . equals ( s ) ) { return true ; } else if ( "0" . equals ( s ) ) { return false ; } else { throw new IllegalArgumentException ( "Expected 1 or 0 for boolean value, was " + s ) ; } } | Attempts to parse the string given as a boolean and return its value . Throws an exception if the value is anything other than 0 or 1 . |
8,716 | ArgumentMarshaller getVersionedArgumentMarshaller ( final Method getter , Object getterReturnResult ) { synchronized ( versionArgumentMarshallerCache ) { if ( ! versionArgumentMarshallerCache . containsKey ( getter ) ) { ArgumentMarshaller marshaller = null ; final Class < ? > returnType = getter . getReturnType ( ) ; if ( BigInteger . class . isAssignableFrom ( returnType ) ) { marshaller = new ArgumentMarshaller ( ) { public AttributeValue marshall ( Object obj ) { if ( obj == null ) obj = BigInteger . ZERO ; Object newValue = ( ( BigInteger ) obj ) . add ( BigInteger . ONE ) ; return getArgumentMarshaller ( getter ) . marshall ( newValue ) ; } } ; } else if ( Integer . class . isAssignableFrom ( returnType ) ) { marshaller = new ArgumentMarshaller ( ) { public AttributeValue marshall ( Object obj ) { if ( obj == null ) obj = new Integer ( 0 ) ; Object newValue = ( ( Integer ) obj ) . intValue ( ) + 1 ; return getArgumentMarshaller ( getter ) . marshall ( newValue ) ; } } ; } else if ( Byte . class . isAssignableFrom ( returnType ) ) { marshaller = new ArgumentMarshaller ( ) { public AttributeValue marshall ( Object obj ) { if ( obj == null ) obj = new Byte ( ( byte ) 0 ) ; Object newValue = ( byte ) ( ( ( ( Byte ) obj ) . byteValue ( ) + 1 ) % Byte . MAX_VALUE ) ; return getArgumentMarshaller ( getter ) . marshall ( newValue ) ; } } ; } else if ( Long . class . isAssignableFrom ( returnType ) ) { marshaller = new ArgumentMarshaller ( ) { public AttributeValue marshall ( Object obj ) { if ( obj == null ) obj = new Long ( 0 ) ; Object newValue = ( ( Long ) obj ) . longValue ( ) + 1L ; return getArgumentMarshaller ( getter ) . marshall ( newValue ) ; } } ; } else { throw new DynamoDBMappingException ( "Unsupported parameter type for " + DynamoDBVersionAttribute . class + ": " + returnType + ". Must be a whole-number type." ) ; } versionArgumentMarshallerCache . put ( getter , marshaller ) ; } } return versionArgumentMarshallerCache . get ( getter ) ; } | Returns a marshaller that knows how to provide an AttributeValue for the getter method given . Also increments the value of the getterReturnResult given . |
8,717 | ArgumentMarshaller getAutoGeneratedKeyArgumentMarshaller ( final Method getter ) { synchronized ( keyArgumentMarshallerCache ) { if ( ! keyArgumentMarshallerCache . containsKey ( getter ) ) { ArgumentMarshaller marshaller = null ; Class < ? > returnType = getter . getReturnType ( ) ; if ( String . class . isAssignableFrom ( returnType ) ) { marshaller = new ArgumentMarshaller ( ) { public AttributeValue marshall ( Object obj ) { String newValue = UUID . randomUUID ( ) . toString ( ) ; return getArgumentMarshaller ( getter ) . marshall ( newValue ) ; } } ; } else { throw new DynamoDBMappingException ( "Unsupported type for " + getter + ": " + returnType + ". Only Strings are supported when auto-generating keys." ) ; } keyArgumentMarshallerCache . put ( getter , marshaller ) ; } } return keyArgumentMarshallerCache . get ( getter ) ; } | Returns a marshaller for the auto - generated key returned by the getter given . |
8,718 | protected boolean mouseDown ( Element element , GqEvent event ) { if ( isEventAlreadyHandled ( event ) ) { return false ; } if ( started ) { mouseUp ( element , event ) ; } reset ( event ) ; if ( notHandleMouseDown ( element , event ) ) { return true ; } if ( delayConditionMet ( ) && distanceConditionMet ( event ) ) { started = mouseStart ( element , event ) ; if ( ! started ) { event . getOriginalEvent ( ) . preventDefault ( ) ; return true ; } } bindOtherEvents ( element ) ; if ( ! touchSupported ) { event . getOriginalEvent ( ) . preventDefault ( ) ; } markEventAsHandled ( event ) ; return true ; } | Method called when mouse down occur on the element . |
8,719 | protected boolean mouseMove ( Element element , GqEvent event ) { if ( started ) { event . getOriginalEvent ( ) . preventDefault ( ) ; return mouseDrag ( element , event ) ; } if ( delayConditionMet ( ) && distanceConditionMet ( event ) ) { started = mouseStart ( element , startEvent ) ; if ( started ) { mouseDrag ( element , event ) ; } else { mouseUp ( element , event ) ; } } return ! started ; } | Method called on MouseMove event . |
8,720 | protected boolean mouseUp ( Element element , GqEvent event ) { unbindOtherEvents ( ) ; if ( started ) { started = false ; preventClickEvent = event . getCurrentEventTarget ( ) == startEvent . getCurrentEventTarget ( ) ; mouseStop ( element , event ) ; } return true ; } | Method called when mouse is released .. |
8,721 | private String getContent ( TreeLogger logger , String path , String src ) throws UnableToCompleteException { HttpURLConnection connection = null ; InputStream in = null ; try { if ( ! src . matches ( "(?i)https?://.*" ) ) { String file = path + "/" + src ; in = this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( file ) ; if ( in == null ) { file = src ; in = this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( file ) ; } if ( in != null ) { logger . log ( TreeLogger . INFO , getClass ( ) . getSimpleName ( ) + " - importing external javascript: " + file ) ; } else { logger . log ( TreeLogger . ERROR , "Unable to read javascript file: " + file ) ; } } else { logger . log ( TreeLogger . INFO , getClass ( ) . getSimpleName ( ) + " - downloading external javascript: " + src ) ; URL url = new URL ( src ) ; connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . setRequestProperty ( "Accept-Encoding" , "gzip, deflate" ) ; connection . setRequestProperty ( "Host" , url . getHost ( ) ) ; connection . setConnectTimeout ( 3000 ) ; connection . setReadTimeout ( 3000 ) ; int status = connection . getResponseCode ( ) ; if ( status != HttpURLConnection . HTTP_OK ) { logger . log ( TreeLogger . ERROR , "Server Error: " + status + " " + connection . getResponseMessage ( ) ) ; throw new UnableToCompleteException ( ) ; } String encoding = connection . getContentEncoding ( ) ; in = connection . getInputStream ( ) ; if ( "gzip" . equalsIgnoreCase ( encoding ) ) { in = new GZIPInputStream ( in ) ; } else if ( "deflate" . equalsIgnoreCase ( encoding ) ) { in = new InflaterInputStream ( in ) ; } } return inputStreamToString ( in ) ; } catch ( IOException e ) { logger . log ( TreeLogger . ERROR , "Error: " + e . getMessage ( ) ) ; throw new UnableToCompleteException ( ) ; } finally { if ( connection != null ) { connection . disconnect ( ) ; } } } | Get the content of a javascript source . It supports remote sources hosted in CDN s . |
8,722 | public < T extends Object > T load ( Class < T > clazz , Object hashKey , DynamoDBMapperConfig config ) { return load ( clazz , hashKey , null , config ) ; } | Loads an object with the hash key given and a configuration override . This configuration overrides the default provided at object construction . |
8,723 | public < T extends Object > T load ( Class < T > clazz , Object hashKey , Object rangeKey , DynamoDBMapperConfig config ) { config = mergeConfig ( config ) ; String tableName = getTableName ( clazz , config ) ; Method hashKeyGetter = reflector . getHashKeyGetter ( clazz ) ; AttributeValue hashKeyElement = getHashKeyElement ( hashKey , hashKeyGetter ) ; AttributeValue rangeKeyElement = null ; if ( rangeKey != null ) { Method rangeKeyMethod = reflector . getRangeKeyGetter ( clazz ) ; if ( rangeKeyMethod == null ) { throw new DynamoDBMappingException ( "Zero-parameter range key property must be annotated with " + DynamoDBRangeKey . class ) ; } rangeKeyElement = getRangeKeyElement ( rangeKey , rangeKeyMethod ) ; } GetItemResult item = db . getItem ( applyUserAgent ( new GetItemRequest ( ) . withTableName ( tableName ) . withKey ( new Key ( ) . withHashKeyElement ( hashKeyElement ) . withRangeKeyElement ( rangeKeyElement ) ) . withConsistentRead ( config . getConsistentReads ( ) == ConsistentReads . CONSISTENT ) ) ) ; Map < String , AttributeValue > itemAttributes = item . getItem ( ) ; if ( itemAttributes == null ) { return null ; } return marshallIntoObject ( clazz , itemAttributes ) ; } | Returns an object with the given hash key or null if no such object exists . |
8,724 | public < T > List < T > marshallIntoObjects ( Class < T > clazz , List < Map < String , AttributeValue > > itemAttributes ) { List < T > result = new ArrayList < T > ( ) ; for ( Map < String , AttributeValue > item : itemAttributes ) { result . add ( marshallIntoObject ( clazz , item ) ) ; } return result ; } | Marshalls the list of item attributes into objects of type clazz |
8,725 | private < T > void setValue ( final T toReturn , final Method getter , AttributeValue value ) { Method setter = reflector . getSetter ( getter ) ; ArgumentUnmarshaller unmarhsaller = reflector . getArgumentUnmarshaller ( toReturn , getter , setter ) ; unmarhsaller . typeCheck ( value , setter ) ; Object argument ; try { argument = unmarhsaller . unmarshall ( value ) ; } catch ( IllegalArgumentException e ) { throw new DynamoDBMappingException ( "Couldn't unmarshall value " + value + " for " + setter , e ) ; } catch ( ParseException e ) { throw new DynamoDBMappingException ( "Error attempting to parse date string " + value + " for " + setter , e ) ; } safeInvoke ( setter , toReturn , argument ) ; } | Sets the value in the return object corresponding to the service result . |
8,726 | public void delete ( Object object , DynamoDBMapperConfig config ) { config = mergeConfig ( config ) ; Class < ? > clazz = object . getClass ( ) ; String tableName = getTableName ( clazz , config ) ; Method hashKeyGetter = reflector . getHashKeyGetter ( clazz ) ; AttributeValue hashKeyElement = getHashKeyElement ( safeInvoke ( hashKeyGetter , object ) , hashKeyGetter ) ; AttributeValue rangeKeyElement = null ; Method rangeKeyGetter = reflector . getRangeKeyGetter ( clazz ) ; if ( rangeKeyGetter != null ) { rangeKeyElement = getRangeKeyElement ( safeInvoke ( rangeKeyGetter , object ) , rangeKeyGetter ) ; } Key objectKey = new Key ( ) . withHashKeyElement ( hashKeyElement ) . withRangeKeyElement ( rangeKeyElement ) ; Map < String , ExpectedAttributeValue > expectedValues = new HashMap < String , ExpectedAttributeValue > ( ) ; if ( config . getSaveBehavior ( ) != SaveBehavior . CLOBBER ) { for ( Method method : reflector . getRelevantGetters ( clazz ) ) { if ( reflector . isVersionAttributeGetter ( method ) ) { Object getterResult = safeInvoke ( method , object ) ; String attributeName = reflector . getAttributeName ( method ) ; ExpectedAttributeValue expected = new ExpectedAttributeValue ( ) ; AttributeValue currentValue = getSimpleAttributeValue ( method , getterResult ) ; expected . setExists ( currentValue != null ) ; if ( currentValue != null ) expected . setValue ( currentValue ) ; expectedValues . put ( attributeName , expected ) ; break ; } } } db . deleteItem ( applyUserAgent ( new DeleteItemRequest ( ) . withKey ( objectKey ) . withTableName ( tableName ) . withExpected ( expectedValues ) ) ) ; } | Deletes the given object from its DynamoDB table . |
8,727 | private boolean validBatchGetRequest ( Map < Class < ? > , List < KeyPair > > itemsToGet ) { if ( itemsToGet == null || itemsToGet . size ( ) == 0 ) { return false ; } for ( Class < ? > clazz : itemsToGet . keySet ( ) ) { if ( itemsToGet . get ( clazz ) != null && itemsToGet . get ( clazz ) . size ( ) > 0 ) { return true ; } } return false ; } | Check whether the batchGetRequest meet all the constraints . |
8,728 | private AttributeValue getAutoGeneratedKeyAttributeValue ( Method getter , Object getterResult ) { ArgumentMarshaller marshaller = reflector . getAutoGeneratedKeyArgumentMarshaller ( getter ) ; return marshaller . marshall ( getterResult ) ; } | Returns an attribute value corresponding to the key method and value given . |
8,729 | public < T > ScanResultPage < T > scanPage ( Class < T > clazz , DynamoDBScanExpression scanExpression , DynamoDBMapperConfig config ) { config = mergeConfig ( config ) ; ScanRequest scanRequest = createScanRequestFromExpression ( clazz , scanExpression , config ) ; ScanResult scanResult = db . scan ( applyUserAgent ( scanRequest ) ) ; ScanResultPage < T > result = new ScanResultPage < T > ( ) ; result . setResults ( marshallIntoObjects ( clazz , scanResult . getItems ( ) ) ) ; result . setLastEvaluatedKey ( scanResult . getLastEvaluatedKey ( ) ) ; return result ; } | Scans through an Amazon DynamoDB table and returns a single page of matching results . The table to scan is determined by looking at the annotations on the specified class which declares where to store the object data in AWS DynamoDB and the scan expression parameter allows the caller to filter results and control how the scan is executed . |
8,730 | public < T > PaginatedQueryList < T > query ( Class < T > clazz , DynamoDBQueryExpression queryExpression ) { return query ( clazz , queryExpression , config ) ; } | Queries an Amazon DynamoDB table and returns the matching results as an unmodifiable list of instantiated objects using the default configuration . |
8,731 | public int count ( Class < ? > clazz , DynamoDBQueryExpression queryExpression , DynamoDBMapperConfig config ) { config = mergeConfig ( config ) ; QueryRequest queryRequest = createQueryRequestFromExpression ( clazz , queryExpression , config ) ; queryRequest . setCount ( true ) ; int count = 0 ; QueryResult queryResult = null ; do { queryResult = db . query ( applyUserAgent ( queryRequest ) ) ; count += queryResult . getCount ( ) ; queryRequest . setExclusiveStartKey ( queryResult . getLastEvaluatedKey ( ) ) ; } while ( queryResult . getLastEvaluatedKey ( ) != null ) ; return count ; } | Evaluates the specified query expression and returns the count of matching items without returning any of the actual item data . |
8,732 | private DynamoDBMapperConfig mergeConfig ( DynamoDBMapperConfig config ) { if ( config != this . config ) config = new DynamoDBMapperConfig ( this . config , config ) ; return config ; } | Merges the config object given with the one specified at construction and returns the result . |
8,733 | private Map < String , AttributeValueUpdate > transformAttributeUpdates ( Class < ? > clazz , Key objectKey , Map < String , AttributeValueUpdate > updateValues ) { Map < String , AttributeValue > item = convertToItem ( updateValues ) ; boolean hashKeyAdded = false ; boolean rangeKeyAdded = false ; String hashKey = reflector . getAttributeName ( reflector . getHashKeyGetter ( clazz ) ) ; if ( ! item . containsKey ( hashKey ) ) { item . put ( hashKey , objectKey . getHashKeyElement ( ) ) ; hashKeyAdded = true ; } String rangeKey = null ; Method rangeKeyGetter = reflector . getRangeKeyGetter ( clazz ) ; if ( rangeKeyGetter != null ) { rangeKey = reflector . getAttributeName ( rangeKeyGetter ) ; if ( ! item . containsKey ( rangeKey ) ) { item . put ( rangeKey , objectKey . getRangeKeyElement ( ) ) ; rangeKeyAdded = true ; } } item = transformAttributes ( clazz , item ) ; if ( hashKeyAdded ) { item . remove ( hashKey ) ; } if ( rangeKeyAdded ) { item . remove ( rangeKey ) ; } for ( String key : item . keySet ( ) ) { if ( updateValues . containsKey ( key ) ) { updateValues . get ( key ) . getValue ( ) . withB ( item . get ( key ) . getB ( ) ) . withBS ( item . get ( key ) . getBS ( ) ) . withN ( item . get ( key ) . getN ( ) ) . withNS ( item . get ( key ) . getNS ( ) ) . withS ( item . get ( key ) . getS ( ) ) . withSS ( item . get ( key ) . getSS ( ) ) ; } else { updateValues . put ( key , new AttributeValueUpdate ( item . get ( key ) , "PUT" ) ) ; } } return updateValues ; } | A transformation expects to see all values including keys when determining the transformation therefore we must insert them if they are not already present . However we must remove the keys prior to actual storage as this method is called when updating DynamoDB which does not permit the modification of key attributes as part of an update call . |
8,734 | public static void rebind ( Element e ) { EventsListener ret = getGQueryEventListener ( e ) ; if ( ret != null ) { DOM . setEventListener ( ( com . google . gwt . user . client . Element ) e , ret ) ; } } | We have to set the gQuery event listener to the element again when the element is a widget because when GWT detaches a widget it removes the event listener . |
8,735 | public boolean hasHandlers ( int eventBits , String eventName , Function handler ) { for ( int i = 0 , j = elementEvents . length ( ) ; i < j ; i ++ ) { BindFunction function = elementEvents . get ( i ) ; if ( ( function . hasEventType ( eventBits ) || function . isTypeOf ( eventName ) ) && ( handler == null || function . isEquals ( handler ) ) ) { return true ; } } return false ; } | Return true if the element is listening for the given eventBit or eventName and the handler matches . |
8,736 | public void storeCookies ( URLConnection conn ) throws IOException { String domain = getDomainFromHost ( conn . getURL ( ) . getHost ( ) ) ; Map < String , Map < String , String > > domainStore ; if ( store . containsKey ( domain ) ) { domainStore = store . get ( domain ) ; } else { domainStore = new HashMap < > ( ) ; store . put ( domain , domainStore ) ; } String headerName = null ; for ( int i = 1 ; ( headerName = conn . getHeaderFieldKey ( i ) ) != null ; i ++ ) { if ( headerName . equalsIgnoreCase ( SET_COOKIE ) ) { Map < String , String > cookie = new HashMap < > ( ) ; StringTokenizer st = new StringTokenizer ( conn . getHeaderField ( i ) , COOKIE_VALUE_DELIMITER ) ; if ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) ; String name = token . substring ( 0 , token . indexOf ( NAME_VALUE_SEPARATOR ) ) ; String value = token . substring ( token . indexOf ( NAME_VALUE_SEPARATOR ) + 1 , token . length ( ) ) ; domainStore . put ( name , cookie ) ; cookie . put ( name , value ) ; } while ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) . toLowerCase ( ) ; int idx = token . indexOf ( NAME_VALUE_SEPARATOR ) ; if ( idx > 0 && idx < token . length ( ) - 1 ) { cookie . put ( token . substring ( 0 , idx ) . toLowerCase ( ) , token . substring ( idx + 1 , token . length ( ) ) ) ; } } } } } | Retrieves and stores cookies returned by the host on the other side of the the open java . net . URLConnection . |
8,737 | public void setCookies ( URLConnection conn ) throws IOException { URL url = conn . getURL ( ) ; String domain = getDomainFromHost ( url . getHost ( ) ) ; if ( domain . equals ( "localhost" ) ) { domain = "linkedin.com" ; } String path = url . getPath ( ) ; Map < String , Map < String , String > > domainStore = store . get ( domain ) ; if ( domainStore == null ) return ; StringBuilder cookieStringBuffer = new StringBuilder ( ) ; Iterator < String > cookieNames = domainStore . keySet ( ) . iterator ( ) ; while ( cookieNames . hasNext ( ) ) { String cookieName = cookieNames . next ( ) ; Map < String , String > cookie = domainStore . get ( cookieName ) ; if ( comparePaths ( ( String ) cookie . get ( PATH ) , path ) && isNotExpired ( cookie . get ( EXPIRES ) ) ) { cookieStringBuffer . append ( cookieName ) ; cookieStringBuffer . append ( "=" ) ; cookieStringBuffer . append ( cookie . get ( cookieName ) ) ; if ( cookieNames . hasNext ( ) ) cookieStringBuffer . append ( SET_COOKIE_SEPARATOR ) ; } } try { conn . setRequestProperty ( COOKIE , cookieStringBuffer . toString ( ) ) ; } catch ( java . lang . IllegalStateException ise ) { IOException ioe = new IOException ( "Illegal State! Cookies cannot be set on a URLConnection that is already connected. " + "Only call setCookies(java.net.URLConnection) AFTER calling java.net.URLConnection.connect()." ) ; throw ioe ; } } | Prior to opening a URLConnection calling this method will set all unexpired cookies that match the path or subpaths for thi underlying URL |
8,738 | public static boolean matchesTags ( Element e , String ... tagNames ) { assert e != null : "Element cannot be null" ; StringBuilder regExp = new StringBuilder ( "^(" ) ; int tagNameLenght = tagNames != null ? tagNames . length : 0 ; for ( int i = 0 ; i < tagNameLenght ; i ++ ) { regExp . append ( tagNames [ i ] . toUpperCase ( ) ) ; if ( i < tagNameLenght - 1 ) { regExp . append ( "|" ) ; } } regExp . append ( ")$" ) ; return e . getTagName ( ) . toUpperCase ( ) . matches ( regExp . toString ( ) ) ; } | Test if the tag name of the element is one of tag names given in parameter . |
8,739 | public static void attachWidget ( Widget widget , Widget firstParentWidget ) { if ( widget != null && widget . getParent ( ) == null ) { if ( firstParentWidget == null ) { firstParentWidget = getFirstParentWidget ( widget ) ; if ( firstParentWidget == null ) { RootPanel . detachOnWindowClose ( widget ) ; widgetOnAttach ( widget ) ; } else { attachWidget ( widget , firstParentWidget ) ; } } else if ( firstParentWidget instanceof HTMLPanel ) { HTMLPanel h = ( HTMLPanel ) firstParentWidget ; Element p = widget . getElement ( ) . getParentElement ( ) ; if ( p != null ) { h . add ( widget , p ) ; } else { h . add ( widget ) ; } } else if ( firstParentWidget instanceof HasOneWidget ) { ( ( HasOneWidget ) firstParentWidget ) . setWidget ( widget ) ; } else if ( firstParentWidget instanceof HasWidgets ) { try { ( ( HasWidgets ) firstParentWidget ) . add ( widget ) ; } catch ( UnsupportedOperationException e ) { widgetSetParent ( widget , firstParentWidget ) ; } } else { widgetSetParent ( widget , firstParentWidget ) ; } } } | Attach a widget to the GWT widget list . Normally used when GQuery creates widgets wrapping existing dom elements . It does nothing if the widget is already attached to another widget . |
8,740 | public static Iterator < Widget > getChildren ( Widget w ) { if ( w instanceof Panel ) { return ( ( Panel ) w ) . iterator ( ) ; } if ( w instanceof Composite ) { return getChildren ( compositeGetWidget ( ( Composite ) w ) ) ; } return null ; } | Return children of the first widget s panel . |
8,741 | public final int pageX ( ) { if ( getTouches ( ) != null && getTouches ( ) . length ( ) > 0 ) { return getTouches ( ) . get ( 0 ) . getPageX ( ) ; } else { return getClientX ( ) + GQuery . document . getScrollLeft ( ) ; } } | The mouse position relative to the left edge of the document . |
8,742 | public final int pageY ( ) { if ( getTouches ( ) != null && getTouches ( ) . length ( ) > 0 ) { return getTouches ( ) . get ( 0 ) . getPageY ( ) ; } else { return getClientY ( ) + GQuery . document . getScrollTop ( ) ; } } | The mouse position relative to the top edge of the document . |
8,743 | public void setTableNames ( java . util . Collection < String > tableNames ) { if ( tableNames == null ) { this . tableNames = null ; return ; } java . util . List < String > tableNamesCopy = new java . util . ArrayList < String > ( tableNames . size ( ) ) ; tableNamesCopy . addAll ( tableNames ) ; this . tableNames = tableNamesCopy ; } | Sets the value of the TableNames property for this object . |
8,744 | public Object getContext ( Class < ? > key ) { if ( key == null ) { throw new NullPointerException ( "key is null" ) ; } if ( context == null ) { return null ; } return context . get ( key ) ; } | Returns the context object associated with the given key . The ELContext maintains a collection of context objects relevant to the evaluation of an expression . These context objects are used by ELResolvers . This method is used to retrieve the context with the given key from the collection . By convention the object returned will be of the type specified by the key . However this is not required and the key is used strictly as a unique identifier . |
8,745 | public void putContext ( Class < ? > key , Object contextObject ) { if ( key == null ) { throw new NullPointerException ( "key is null" ) ; } if ( context == null ) { context = new HashMap < Class < ? > , Object > ( ) ; } context . put ( key , contextObject ) ; } | Associates a context object with this ELContext . The ELContext maintains a collection of context objects relevant to the evaluation of an expression . These context objects are used by ELResolvers . This method is used to add a context object to that collection . By convention the contextObject will be of the type specified by the key . However this is not required and the key is used strictly as a unique identifier . |
8,746 | public static void main ( String [ ] args ) throws SAXException , IOException { ELContext context = new SimpleContext ( ) ; context . getELResolver ( ) . setValue ( context , null , "home" , "/foo/bar" ) ; XMLReader reader = new XMELFilter ( XMLReaderFactory . createXMLReader ( ) , context ) ; reader . setContentHandler ( new DefaultHandler ( ) { public void startElement ( String uri , String localName , String qName , Attributes attributes ) { System . out . println ( "start " + localName ) ; for ( int i = 0 ; i < attributes . getLength ( ) ; i ++ ) { System . out . println ( " @" + attributes . getLocalName ( i ) + " = " + attributes . getValue ( i ) ) ; } } public void endElement ( String uri , String localName , String qName ) { System . out . println ( "end " + localName ) ; } public void characters ( char [ ] ch , int start , int length ) throws SAXException { System . out . println ( "text: " + new String ( ch , start , length ) ) ; } } ) ; String xml = "<test>foo<math>1+2=${1+2}</math><config file='${home}/config.xml'/>bar</test>" ; reader . parse ( new InputSource ( new StringReader ( xml ) ) ) ; } | Usage example . |
8,747 | public < T > T convert ( Object value , Class < T > type ) { return converter . convert ( value , type ) ; } | Apply type conversion . |
8,748 | public static String getStorageDir ( DataSegment segment ) { return JOINER . join ( segment . getDataSource ( ) , String . format ( "%s_%s" , segment . getInterval ( ) . getStart ( ) , segment . getInterval ( ) . getEnd ( ) ) , segment . getVersion ( ) , segment . getShardSpec ( ) . getPartitionNum ( ) ) ; } | on segment deletion if segment being deleted was the only segment |
8,749 | void update ( JsonObject dp ) { for ( int i = 0 ; i < dp . names ( ) . size ( ) ; i ++ ) { datapoint . put ( dp . names ( ) . get ( i ) , dp . get ( dp . names ( ) . get ( i ) ) ) ; } } | Updates the data point data |
8,750 | public String [ ] getFieldsArray ( ) { Object [ ] obj = datapoint . keySet ( ) . toArray ( ) ; String [ ] out = new String [ obj . length ] ; for ( int i = 0 ; i < obj . length ; i ++ ) out [ i ] = String . valueOf ( obj [ i ] ) ; return out ; } | Returns a String array with all the Forecast . io fields available in this data point . It can be usefull to iterate over all available fields in a data point . |
8,751 | public String getByKey ( String key ) { String out = "" ; if ( key . equals ( "time" ) ) return time ( ) ; if ( key . contains ( "Time" ) ) { DateFormat dfm = new SimpleDateFormat ( "HH:mm:ss" ) ; dfm . setTimeZone ( TimeZone . getTimeZone ( timezone ) ) ; out = dfm . format ( Long . parseLong ( String . valueOf ( this . datapoint . get ( key ) ) ) * 1000 ) ; } else out = String . valueOf ( datapoint . get ( key ) ) ; return out ; } | Return the data point field with the corresponding key |
8,752 | public void setHTTPProxy ( String PROXYNAME , int PROXYPORT ) { if ( PROXYNAME == null ) { this . proxy_to_use = null ; } else { this . proxy_to_use = new Proxy ( Proxy . Type . HTTP , new InetSocketAddress ( PROXYNAME , PROXYPORT ) ) ; } } | Sets the http - proxy to use . |
8,753 | public boolean update ( ) { boolean b = getForecast ( String . valueOf ( getLatitude ( ) ) , String . valueOf ( getLongitude ( ) ) ) ; return b ; } | Does another query to the API and updates the data This only updates the data in ForecastIO class |
8,754 | public boolean getForecast ( String LATITUDE , String LONGITUDE ) { try { String reply = httpGET ( urlBuilder ( LATITUDE , LONGITUDE ) ) ; if ( reply == null ) return false ; this . forecast = Json . parse ( reply ) . asObject ( ) ; } catch ( NullPointerException e ) { System . err . println ( "Unable to connect to the API: " + e . getMessage ( ) ) ; return false ; } return getForecast ( this . forecast ) ; } | Gets the forecast reports for the given coordinates with the set options |
8,755 | public boolean getForecast ( String http_response ) { this . forecast = Json . parse ( http_response ) . asObject ( ) ; return getForecast ( this . forecast ) ; } | Parses the forecast reports for the given coordinates with the set options Useful to use with an external http library |
8,756 | protected void listen ( ) { if ( ! connectedFlag . get ( ) || releaseNeeded . get ( ) ) { return ; } releaseNeeded . set ( true ) ; try { send ( pushListener , new OnFinishedHandler ( ) { public void onFinished ( ) { releaseNeeded . set ( false ) ; listen ( ) ; } } ) ; } catch ( Exception e ) { LOG . error ( "Error in sending long poll" , e ) ; } } | listens for the pushListener to return . The pushListener must be set and pushEnabled must be true . |
8,757 | protected void release ( ) { if ( ! releaseNeeded . get ( ) ) { return ; } releaseNeeded . set ( false ) ; backgroundExecutor . execute ( new Runnable ( ) { public void run ( ) { try { List < Command > releaseCommandList = new ArrayList < Command > ( Collections . singletonList ( releaseCommand ) ) ; transmit ( releaseCommandList ) ; } catch ( DolphinRemotingException e ) { handleError ( e ) ; } } } ) ; } | Release the current push listener which blocks the sending queue . Does nothing in case that the push listener is not active . |
8,758 | public List < Command > receive ( final Command command ) { Assert . requireNonNull ( command , "command" ) ; LOG . trace ( "Received command of type {}" , command . getClass ( ) . getSimpleName ( ) ) ; List < Command > response = new LinkedList ( ) ; if ( ! ( command instanceof InterruptLongPollCommand ) ) { for ( DolphinServerAction it : dolphinServerActions ) { it . setDolphinResponse ( response ) ; } serverModelStore . setCurrentResponse ( response ) ; } List < CommandHandler > actions = registry . getActionsFor ( command . getClass ( ) ) ; if ( actions . isEmpty ( ) ) { LOG . warn ( "There is no server action registered for received command type {}, known commands types are {}" , command . getClass ( ) . getSimpleName ( ) , registry . getActions ( ) . keySet ( ) ) ; return response ; } List < CommandHandler > actionsCopy = new ArrayList < CommandHandler > ( ) ; actionsCopy . addAll ( actions ) ; try { for ( CommandHandler action : actionsCopy ) { action . handleCommand ( command , response ) ; } } catch ( Exception exception ) { throw exception ; } return response ; } | doesn t fail on missing commands |
8,759 | public static < S extends Styleable , V > DefaultPropertyBasedCssMetaData < S , V > createMetaData ( String property , StyleConverter < ? , V > converter , String propertyName , V defaultValue ) { return new DefaultPropertyBasedCssMetaData < S , V > ( property , converter , propertyName , defaultValue ) ; } | Creates a CssMetaData instance that can be used in a Styleable class . |
8,760 | public static < S extends Control , V > SkinPropertyBasedCssMetaData < S , V > createSkinMetaData ( String property , StyleConverter < ? , V > converter , String propertyName , V defaultValue ) { return new SkinPropertyBasedCssMetaData < S , V > ( property , converter , propertyName , defaultValue ) ; } | Creates a CssMetaData instance that can be used in the Skin of a Control . |
8,761 | public Subscription registerDolphinContext ( ClientSession session , GarbageCollector garbageCollector ) { Assert . requireNonNull ( session , "session" ) ; Assert . requireNonNull ( garbageCollector , "garbageCollector" ) ; DolphinSessionInfoMBean mBean = new DolphinSessionInfo ( session , garbageCollector ) ; return MBeanRegistry . getInstance ( ) . register ( mBean , new MBeanDescription ( "com.canoo.dolphin" , "DolphinSession" , "session" ) ) ; } | Register a new dolphin session as a MBean |
8,762 | public Subscription registerController ( Class < ? > controllerClass , String controllerId , ModelProvider modelProvider ) { Assert . requireNonNull ( controllerClass , "controllerClass" ) ; Assert . requireNonBlank ( controllerId , "controllerId" ) ; Assert . requireNonNull ( modelProvider , "modelProvider" ) ; DolphinControllerInfoMBean mBean = new DolphinControllerInfo ( dolphinContextId , controllerClass , controllerId , modelProvider ) ; return MBeanRegistry . getInstance ( ) . register ( mBean , new MBeanDescription ( "com.canoo.dolphin" , controllerClass . getSimpleName ( ) , "controller" ) ) ; } | Register a new Dolphin Platform controller as a MBean |
8,763 | public final void init ( ) throws Exception { FxToolkit . init ( ) ; applicationInit ( ) ; PlatformClient . getClientConfiguration ( ) . setUncaughtExceptionHandler ( ( Thread thread , Throwable exception ) -> { PlatformClient . getClientConfiguration ( ) . getUiExecutor ( ) . execute ( ( ) -> { Assert . requireNonNull ( thread , "thread" ) ; Assert . requireNonNull ( exception , "exception" ) ; if ( connectInProgress . get ( ) ) { runtimeExceptionsAtInitialization . add ( new DolphinRuntimeException ( thread , "Unhandled error in Dolphin Platform background thread" , exception ) ) ; } else { onRuntimeError ( primaryStage , new DolphinRuntimeException ( thread , "Unhandled error in Dolphin Platform background thread" , exception ) ) ; } } ) ; } ) ; try { clientContext = createClientContext ( ) ; Assert . requireNonNull ( clientContext , "clientContext" ) ; connectInProgress . set ( true ) ; clientContext . connect ( ) . get ( 30_000 , TimeUnit . MILLISECONDS ) ; } catch ( ClientInitializationException e ) { initializationException = e ; } catch ( Exception e ) { initializationException = new ClientInitializationException ( "Can not initialize Dolphin Platform Context" , e ) ; } finally { connectInProgress . set ( false ) ; } } | Creates the connection to the Dolphin Platform server . If this method will be overridden always call the super method . |
8,764 | protected void onRuntimeError ( final Stage primaryStage , final DolphinRuntimeException runtimeException ) { Assert . requireNonNull ( runtimeException , "runtimeException" ) ; LOG . error ( "Dolphin Platform runtime error in thread " + runtimeException . getThread ( ) . getName ( ) , runtimeException ) ; Platform . exit ( ) ; } | This method is called if the connection to the Dolphin Platform server throws an exception at runtime . This can for example happen if the server is shut down while the client is still running or if the server responses with an error code . |
8,765 | public boolean isReferencedByRoot ( ) { if ( rootBean ) { return true ; } for ( Reference reference : references ) { Instance parent = reference . getParent ( ) ; if ( parent . isReferencedByRoot ( ) ) { return true ; } } return false ; } | Return true if the dolphin bean instance is a root bean or is referenced by a root bean |
8,766 | public static < T , R > SwitchBuilder < T , R > switchBinding ( ObservableValue < T > observable , Class < R > bindingType ) { return new SwitchBuilder < > ( observable ) ; } | Creates builder for a binding that works like a switch - case in java . |
8,767 | public CompletableFuture < Void > destroy ( ) { CompletableFuture < Void > ret ; if ( controllerProxy != null ) { ret = controllerProxy . destroy ( ) ; controllerProxy = null ; } else { ret = new CompletableFuture < > ( ) ; ret . complete ( null ) ; } return ret ; } | By calling this method the MVC group will be destroyed . This means that the controller instance on the server will be removed and the model that is managed and synchronized between client and server will be detached . After this method is called the view should not be used anymore . It s important to call this method to removePresentationModel all the unneeded references on the server . |
8,768 | protected CompletableFuture < Void > invoke ( String actionName , Param ... params ) { Assert . requireNonBlank ( actionName , "actionName" ) ; actionInProcess . set ( true ) ; return controllerProxy . invoke ( actionName , params ) . whenComplete ( ( v , e ) -> { try { if ( e != null ) { onInvocationException ( e ) ; } } finally { actionInProcess . set ( false ) ; } } ) ; } | This invokes a action on the server side controller . For more information how an action can be defined in the controller have a look at the RemotingAction annotation in the server module . This method don t block and can be called from the Platform thread . To check if an server |
8,769 | public void silently ( final Runnable applyChange ) { boolean temp = notifyClient ; notifyClient = false ; try { applyChange . run ( ) ; } finally { notifyClient = temp ; } } | Do the applyChange without creating commands that are sent to the client |
8,770 | protected void verbosely ( final Runnable applyChange ) { boolean temp = notifyClient ; notifyClient = true ; try { applyChange . run ( ) ; } finally { notifyClient = temp ; } } | Do the applyChange with enforced creation of commands that are sent to the client |
8,771 | public static BooleanBinding and ( ObservableValue < Boolean > ... values ) { return Bindings . createBooleanBinding ( ( ) -> ! Arrays . stream ( values ) . filter ( observable -> ! observable . getValue ( ) ) . findAny ( ) . isPresent ( ) , values ) ; } | A boolean binding that is true only when all dependent observable boolean values are true . |
8,772 | public static NumberBinding sum ( final ObservableList < ? extends Number > numbers ) { return Bindings . createDoubleBinding ( ( ) -> numbers . stream ( ) . mapToDouble ( Number :: doubleValue ) . sum ( ) , numbers ) ; } | Creates a number binding that contains the sum of the numbers of the given observable list of numbers . |
8,773 | public static StringBinding join ( final ObservableList < ? > items , final ObservableValue < String > delimiter ) { return Bindings . createStringBinding ( ( ) -> items . stream ( ) . map ( String :: valueOf ) . collect ( Collectors . joining ( delimiter . getValue ( ) ) ) , items , delimiter ) ; } | Creates a string binding that constructs a sequence of characters separated by a delimiter . |
8,774 | public static < T > ObservableList < T > concat ( ObservableList < T > ... lists ) { ObservableList < T > result = FXCollections . observableArrayList ( ) ; for ( ObservableList < T > list : lists ) { list . addListener ( ( Observable observable ) -> { result . clear ( ) ; for ( ObservableList < T > ts : lists ) { result . addAll ( ts ) ; } } ) ; } return result ; } | Creates an observable list that represents the concatenated source lists . All elements from the all source lists will be contained in the new list . If there is a change in any of the source lists this change will also be done in the concatenated list . |
8,775 | public static BooleanBinding matches ( final ObservableValue < String > text , final String pattern ) { return Bindings . createBooleanBinding ( ( ) -> { final String textToVerify = text . getValue ( ) ; return textToVerify != null && textToVerify . matches ( pattern ) ; } , text ) ; } | Creates a boolean binding that is true when the given observable string matches the given RegExp pattern . |
8,776 | public static StringBinding transforming ( ObservableValue < String > text , Function < String , String > transformer ) { return Bindings . createStringBinding ( ( ) -> { Function < String , String > func = transformer == null ? Function . identity ( ) : transformer ; return text . getValue ( ) == null ? "" : func . apply ( text . getValue ( ) ) ; } , text ) ; } | Creates a string binding that contains the value of the given observable string transformed using the supplied function . |
8,777 | public boolean remove ( final ServerPresentationModel pm ) { boolean deleted = super . remove ( pm ) ; if ( ! deleted ) { throw new IllegalStateException ( "Model " + pm + " not found on the server!" ) ; } deleteCommand ( getCurrentResponse ( ) , pm . getId ( ) ) ; return deleted ; } | Convenience method to let Dolphin removePresentationModel a presentation model directly on the server and notify the client . |
8,778 | public static void deleteCommand ( final List < Command > response , final String pmId ) { if ( response == null || Assert . isBlank ( pmId ) ) { return ; } response . add ( new DeletePresentationModelCommand ( pmId ) ) ; } | Convenience method to let Dolphin delete a presentation model on the client side |
8,779 | public static void changeValueCommand ( final List < Command > response , final ServerAttribute attribute , final Object value ) { if ( response == null ) { return ; } if ( attribute == null ) { LOG . error ( "Cannot change value on a null attribute to '{}'" , value ) ; return ; } forceChangeValue ( value , response , attribute ) ; } | Convenience method to change an attribute value on the server side . |
8,780 | public ServerPresentationModel presentationModel ( final String id , final String presentationModelType , final DTO dto ) { List < ServerAttribute > attributes = new ArrayList < ServerAttribute > ( ) ; for ( final Slot slot : dto . getSlots ( ) ) { final ServerAttribute result = new ServerAttribute ( slot . getPropertyName ( ) , slot . getValue ( ) , slot . getQualifier ( ) ) ; result . silently ( new Runnable ( ) { public void run ( ) { result . setValue ( slot . getValue ( ) ) ; } } ) ; attributes . add ( result ) ; } ServerPresentationModel model = new ServerPresentationModel ( id , attributes , this ) ; model . setPresentationModelType ( presentationModelType ) ; add ( model ) ; return model ; } | Create a presentation model on the server side add it to the model store and withContent a command to the client advising him to do the same . |
8,781 | public Subscription register ( final Object mBean , final MBeanDescription description ) { Assert . requireNonNull ( description , "description" ) ; return register ( mBean , description . getMBeanName ( getNextId ( ) ) ) ; } | Register the given MBean based on the given description |
8,782 | public Subscription register ( final Object mBean , final String name ) { try { if ( mbeanSupport . get ( ) ) { final ObjectName objectName = new ObjectName ( name ) ; server . registerMBean ( mBean , objectName ) ; return new Subscription ( ) { public void unsubscribe ( ) { try { server . unregisterMBean ( objectName ) ; } catch ( JMException e ) { throw new RuntimeException ( "Can not unsubscribe!" , e ) ; } } } ; } else { return new Subscription ( ) { public void unsubscribe ( ) { } } ; } } catch ( Exception e ) { throw new RuntimeException ( "Can not register MBean!" , e ) ; } } | Register the given MBean based on the given name |
8,783 | public void sync ( final Runnable runnable ) { clientConnector . send ( new EmptyCommand ( ) , new OnFinishedHandler ( ) { public void onFinished ( ) { runnable . run ( ) ; } } ) ; } | both java - and groovy - friendly convenience method to withContent an empty command which will have no presentation models nor data in the callback |
8,784 | public synchronized Set < Class < ? > > getTypesAnnotatedWith ( final Class < ? extends Annotation > annotation ) { Assert . requireNonNull ( annotation , "annotation" ) ; return reflections . getTypesAnnotatedWith ( annotation ) ; } | Returns a set that contains all classes in the classpath that are annotated with the given annotation |
8,785 | private int combineFlags ( final Pattern . Flag [ ] flags ) { int combined = 0 ; for ( Pattern . Flag f : flags ) { combined |= f . getValue ( ) ; } return combined ; } | Combines a given set of javax . validation . constraints . Pattern . Flag instances into one bitmask suitable for java . util . regex . Pattern consumption . |
8,786 | public static < S , R > ObjectBinding < R > map ( ObservableValue < S > source , Function < ? super S , ? extends R > function ) { return map ( source , function , null ) ; } | A Binding that holds a value that is determined by the given function applied to the value of the observable source . |
8,787 | public static < S , R > ObjectBinding < R > map ( ObservableValue < S > source , Function < ? super S , ? extends R > function , R defaultValue ) { return Bindings . createObjectBinding ( ( ) -> { S sourceValue = source . getValue ( ) ; if ( sourceValue == null ) { return defaultValue ; } else { return function . apply ( sourceValue ) ; } } , source ) ; } | A null safe binding that holds the return value of the given function when applied to the value of the given observable . |
8,788 | public static < T , S extends T > ObjectBinding < T > cast ( final ObservableValue < S > source ) { return Bindings . createObjectBinding ( source :: getValue , source ) ; } | Creates a binding that contains the same value as the source observable but casted to a type that is higher in class hierarchy . |
8,789 | private static String createAnnotationCollectionId ( Collection < Annotation > annotations ) { if ( annotations . isEmpty ( ) ) return "" ; return annotations . stream ( ) . sorted ( comparing ( a -> a . annotationType ( ) . getName ( ) ) ) . map ( CdiSpiHelper :: createAnnotationId ) . collect ( joining ( "," , "[" , "]" ) ) ; } | Generates a unique signature for a collection of annotations . |
8,790 | public static Object getValue ( Object exp , Object root ) { return getValue ( exp , root , null , 0 ) ; } | Returns the value using the OGNL expression and the root object . |
8,791 | public static Object getValue ( Object exp , Map ctx , Object root ) { return getValue ( exp , ctx , root , null , 0 ) ; } | Returns the value using the OGNL expression the root object and a context map . |
8,792 | public static Object getValue ( Object exp , Map ctx , Object root , String path , int lineNumber ) { try { OgnlContext context = new OgnlContext ( null , null , new DefaultMemberAccess ( true ) ) ; return Ognl . getValue ( exp , context , root ) ; } catch ( OgnlException ex ) { throw new OgnlRuntimeException ( ex . getReason ( ) == null ? ex : ex . getReason ( ) , path , lineNumber ) ; } catch ( Exception ex ) { throw new OgnlRuntimeException ( ex , path , lineNumber ) ; } } | Returns the value using the OGNL expression the root object a context mpa a path and a line number . |
8,793 | public static Object parseExpression ( String expression , String path , int lineNumber ) { try { return Ognl . parseExpression ( expression ) ; } catch ( Exception ex ) { throw new OgnlRuntimeException ( ex , path , lineNumber ) ; } } | Parses an OGNL expression . |
8,794 | public < T > T getSingleResult ( Class < T > clazz , String sql , Object [ ] params ) { PreparedStatement stmt = null ; ResultSet rs = null ; try { stmt = connectionProvider . getConnection ( ) . prepareStatement ( sql ) ; setParameters ( stmt , params ) ; if ( logger . isDebugEnabled ( ) ) { printSql ( sql ) ; printParameters ( params ) ; } rs = stmt . executeQuery ( ) ; ResultSetMetaData meta = rs . getMetaData ( ) ; int columnCount = meta . getColumnCount ( ) ; BeanDesc beanDesc = beanDescFactory . getBeanDesc ( clazz ) ; if ( rs . next ( ) ) { T entity = entityOperator . createEntity ( clazz , rs , meta , columnCount , beanDesc , dialect , valueTypes , nameConverter ) ; return entity ; } return null ; } catch ( SQLException ex ) { throw new SQLRuntimeException ( ex ) ; } finally { JdbcUtil . close ( rs ) ; JdbcUtil . close ( stmt ) ; } } | Returns a single entity from the first row of an SQL . |
8,795 | public int executeUpdateSql ( String sql , PropertyDesc [ ] propDescs , Object entity ) { PreparedStatement stmt = null ; ResultSet rs = null ; try { Connection conn = connectionProvider . getConnection ( ) ; if ( logger . isDebugEnabled ( ) ) { printSql ( sql ) ; printParameters ( propDescs ) ; } if ( entity != null && dialect . supportsGenerationType ( GenerationType . IDENTITY ) ) { stmt = conn . prepareStatement ( sql , PreparedStatement . RETURN_GENERATED_KEYS ) ; } else { stmt = conn . prepareStatement ( sql ) ; } setParameters ( stmt , propDescs , entity ) ; int result = stmt . executeUpdate ( ) ; if ( entity != null && dialect . supportsGenerationType ( GenerationType . IDENTITY ) ) { rs = stmt . getGeneratedKeys ( ) ; fillIdentityPrimaryKeys ( entity , rs ) ; } return result ; } catch ( SQLException ex ) { throw new SQLRuntimeException ( ex ) ; } finally { JdbcUtil . close ( rs ) ; JdbcUtil . close ( stmt ) ; } } | Executes an update SQL . |
8,796 | public int executeBatchUpdateSql ( String sql , List < PropertyDesc [ ] > propDescsList , Object [ ] entities ) { PreparedStatement stmt = null ; ResultSet rs = null ; try { Connection conn = connectionProvider . getConnection ( ) ; if ( logger . isDebugEnabled ( ) ) { printSql ( sql ) ; for ( int i = 0 ; i < propDescsList . size ( ) ; i ++ ) { PropertyDesc [ ] propDescs = propDescsList . get ( i ) ; logger . debug ( "[" + i + "]" ) ; printParameters ( propDescs , entities [ i ] ) ; } } if ( entities != null && dialect . supportsGenerationType ( GenerationType . IDENTITY ) ) { stmt = conn . prepareStatement ( sql , PreparedStatement . RETURN_GENERATED_KEYS ) ; } else { stmt = conn . prepareStatement ( sql ) ; } if ( entities != null ) { for ( int i = 0 ; i < propDescsList . size ( ) ; i ++ ) { PropertyDesc [ ] propDescs = propDescsList . get ( i ) ; setParameters ( stmt , propDescs , entities [ i ] ) ; stmt . addBatch ( ) ; } } else { for ( PropertyDesc [ ] propDescs : propDescsList ) { setParameters ( stmt , propDescs , null ) ; stmt . addBatch ( ) ; } } int [ ] results = stmt . executeBatch ( ) ; int updateRows = 0 ; for ( int result : results ) { updateRows += result ; } if ( entities != null && dialect . supportsGenerationType ( GenerationType . IDENTITY ) ) { rs = stmt . getGeneratedKeys ( ) ; for ( Object entity : entities ) { fillIdentityPrimaryKeys ( entity , rs ) ; } } return updateRows ; } catch ( SQLException ex ) { throw new SQLRuntimeException ( ex ) ; } finally { JdbcUtil . close ( rs ) ; JdbcUtil . close ( stmt ) ; } } | Executes the update SQL . |
8,797 | @ SuppressWarnings ( "unchecked" ) protected void fillIdentityPrimaryKeys ( Object entity , ResultSet rs ) throws SQLException { BeanDesc beanDesc = beanDescFactory . getBeanDesc ( entity . getClass ( ) ) ; int size = beanDesc . getPropertyDescSize ( ) ; for ( int i = 0 ; i < size ; i ++ ) { PropertyDesc propertyDesc = beanDesc . getPropertyDesc ( i ) ; PrimaryKey primaryKey = propertyDesc . getAnnotation ( PrimaryKey . class ) ; if ( primaryKey != null && primaryKey . generationType ( ) == GenerationType . IDENTITY ) { if ( rs . next ( ) ) { Class < ? > propertyType = propertyDesc . getPropertyType ( ) ; @ SuppressWarnings ( "rawtypes" ) ValueType valueType = MirageUtil . getValueType ( propertyType , propertyDesc , dialect , valueTypes ) ; if ( valueType != null ) { propertyDesc . setValue ( entity , valueType . get ( propertyType , rs , 1 ) ) ; } } } } } | Sets GenerationType . IDENTITY properties value . |
8,798 | public static String buildDeleteSql ( BeanDescFactory beanDescFactory , EntityOperator entityOperator , Class < ? > entityType , NameConverter nameConverter , List < PropertyDesc > propDescs ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "DELETE FROM " ) . append ( getTableName ( entityType , nameConverter ) ) ; sb . append ( " WHERE " ) ; boolean hasPrimaryKey = false ; BeanDesc beanDesc = beanDescFactory . getBeanDesc ( entityType ) ; for ( int i = 0 ; i < beanDesc . getPropertyDescSize ( ) ; i ++ ) { PropertyDesc pd = beanDesc . getPropertyDesc ( i ) ; PrimaryKeyInfo primaryKey = entityOperator . getPrimaryKeyInfo ( entityType , pd , nameConverter ) ; if ( primaryKey != null && pd . isReadable ( ) ) { if ( ! propDescs . isEmpty ( ) ) { sb . append ( " AND " ) ; } sb . append ( getColumnName ( entityOperator , entityType , pd , nameConverter ) ) . append ( " = ?" ) ; propDescs . add ( pd ) ; hasPrimaryKey = true ; } } if ( hasPrimaryKey == false ) { throw new RuntimeException ( "Primary key is not found: " + entityType . getName ( ) ) ; } return sb . toString ( ) ; } | Builds delete SQL and correct parameters from the entity . |
8,799 | private void fillPrimaryKeysBySequence ( Object entity ) { if ( ! dialect . supportsGenerationType ( GenerationType . SEQUENCE ) ) { return ; } BeanDesc beanDesc = beanDescFactory . getBeanDesc ( entity . getClass ( ) ) ; int size = beanDesc . getPropertyDescSize ( ) ; for ( int i = 0 ; i < size ; i ++ ) { PropertyDesc propertyDesc = beanDesc . getPropertyDesc ( i ) ; PrimaryKey primaryKey = propertyDesc . getAnnotation ( PrimaryKey . class ) ; if ( primaryKey != null && primaryKey . generationType ( ) == GenerationType . SEQUENCE ) { String sql = dialect . getSequenceSql ( primaryKey . generator ( ) ) ; Object value = sqlExecutor . getSingleResult ( propertyDesc . getPropertyType ( ) , sql , new Object [ 0 ] ) ; propertyDesc . setValue ( entity , value ) ; } } } | Sets GenerationType . SEQUENCE properties value . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.