idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
14,100
public static String applyUriReplace ( String uriSource , Configuration conf ) { if ( uriSource == null ) return null ; String [ ] uriReplace = conf . getStrings ( OUTPUT_URI_REPLACE ) ; if ( uriReplace == null ) return uriSource ; for ( int i = 0 ; i < uriReplace . length - 1 ; i += 2 ) { String replacement = uriReplace [ i + 1 ] . trim ( ) ; replacement = replacement . substring ( 1 , replacement . length ( ) - 1 ) ; uriSource = uriSource . replaceAll ( uriReplace [ i ] , replacement ) ; } return uriSource ; }
Apply URI replacement configuration option to a URI source string . The configuration option is a list of comma separated pairs of regex patterns and replacements . Validation of the configuration is done at command parsing time .
14,101
public static String applyPrefixSuffix ( String uriSource , Configuration conf ) { if ( uriSource == null ) return null ; String prefix = conf . get ( OUTPUT_URI_PREFIX ) ; String suffix = conf . get ( OUTPUT_URI_SUFFIX ) ; if ( prefix == null && suffix == null ) { return uriSource ; } int len = uriSource . length ( ) + ( prefix != null ? prefix . length ( ) : 0 ) + ( suffix != null ? suffix . length ( ) : 0 ) ; StringBuilder uriBuf = new StringBuilder ( len ) ; if ( prefix != null ) { uriBuf . append ( prefix ) ; } uriBuf . append ( uriSource ) ; if ( suffix != null ) { uriBuf . append ( suffix ) ; } return uriBuf . toString ( ) ; }
Apply URI prefix and suffix configuration option to a URI source string .
14,102
public static String [ ] expandArguments ( String [ ] args ) throws Exception { List < String > options = new ArrayList < String > ( ) ; for ( int i = 0 ; i < args . length ; i ++ ) { if ( args [ i ] . equals ( OPTIONS_FILE ) ) { if ( i == args . length - 1 ) { throw new Exception ( "Missing options file" ) ; } String fileName = args [ ++ i ] ; File optionsFile = new File ( fileName ) ; BufferedReader reader = null ; StringBuilder buffer = new StringBuilder ( ) ; try { reader = new BufferedReader ( new FileReader ( optionsFile ) ) ; String nextLine = null ; while ( ( nextLine = reader . readLine ( ) ) != null ) { nextLine = nextLine . trim ( ) ; if ( nextLine . length ( ) == 0 || nextLine . startsWith ( "#" ) ) { continue ; } buffer . append ( nextLine ) ; if ( nextLine . endsWith ( "\\" ) ) { if ( buffer . charAt ( 0 ) == '\'' || buffer . charAt ( 0 ) == '"' ) { throw new Exception ( "Multiline quoted strings not supported in file(" + fileName + "): " + buffer . toString ( ) ) ; } buffer . deleteCharAt ( buffer . length ( ) - 1 ) ; } else { options . add ( removeQuotesEncolosingOption ( fileName , buffer . toString ( ) ) ) ; buffer . delete ( 0 , buffer . length ( ) ) ; } } if ( buffer . length ( ) != 0 ) { throw new Exception ( "Malformed option in options file(" + fileName + "): " + buffer . toString ( ) ) ; } } catch ( IOException ex ) { throw new Exception ( "Unable to read options file: " + fileName , ex ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException ex ) { LOG . info ( "Exception while closing reader" , ex ) ; } } } } else { options . add ( args [ i ] ) ; } } return options . toArray ( new String [ options . size ( ) ] ) ; }
Expands any options file that may be present in the given set of arguments .
14,103
private static String removeQuotesEncolosingOption ( String fileName , String option ) throws Exception { String option1 = removeQuoteCharactersIfNecessary ( fileName , option , '"' ) ; if ( ! option1 . equals ( option ) ) { return option1 ; } return removeQuoteCharactersIfNecessary ( fileName , option , '\'' ) ; }
Removes the surrounding quote characters as needed . It first attempts to remove surrounding double quotes . If successful the resultant string is returned . If no surrounding double quotes are found it attempts to remove surrounding single quote characters . If successful the resultant string is returned . If not the original string is returnred .
14,104
private static String removeQuoteCharactersIfNecessary ( String fileName , String option , char quote ) throws Exception { boolean startingQuote = ( option . charAt ( 0 ) == quote ) ; boolean endingQuote = ( option . charAt ( option . length ( ) - 1 ) == quote ) ; if ( startingQuote && endingQuote ) { if ( option . length ( ) == 1 ) { throw new Exception ( "Malformed option in options file(" + fileName + "): " + option ) ; } return option . substring ( 1 , option . length ( ) - 1 ) ; } if ( startingQuote || endingQuote ) { throw new Exception ( "Malformed option in options file(" + fileName + "): " + option ) ; } return option ; }
Removes the surrounding quote characters from the given string . The quotes are identified by the quote parameter the given string by option . The fileName parameter is used for raising exceptions with relevant message .
14,105
private int assignThreads ( int splitIndex , int splitCount ) { if ( threadsPerSplit > 0 ) { return threadsPerSplit ; } if ( splitCount == 1 ) { return threadCount ; } if ( splitCount * minThreads > threadCount ) { return minThreads ; } if ( splitIndex % threadCount < threadCount % splitCount ) { return threadCount / splitCount + 1 ; } else { return threadCount / splitCount ; } }
Assign thread count for a given split
14,106
public void configFields ( Configuration conf , String [ ] fields ) throws IllegalArgumentException , IOException { for ( int i = 0 ; i < fields . length ; i ++ ) { fields [ i ] = fields [ i ] . trim ( ) ; if ( "" . equals ( fields [ i ] ) ) { LOG . warn ( "Column " + ( i + 1 ) + " has no header and will be skipped" ) ; } } }
Check document header fields .
14,107
public void setClient ( AerospikeClient client ) { this . client = client ; this . updatePolicy = new WritePolicy ( this . client . writePolicyDefault ) ; this . updatePolicy . recordExistsAction = RecordExistsAction . UPDATE_ONLY ; this . insertPolicy = new WritePolicy ( this . client . writePolicyDefault ) ; this . insertPolicy . recordExistsAction = RecordExistsAction . CREATE_ONLY ; this . queryPolicy = client . queryPolicyDefault ; refreshCluster ( ) ; registerUDF ( ) ; }
Sets the AerospikeClient
14,108
public KeyRecordIterator select ( String namespace , String set , Filter filter , Qualifier ... qualifiers ) { Statement stmt = new Statement ( ) ; stmt . setNamespace ( namespace ) ; stmt . setSetName ( set ) ; if ( filter != null ) stmt . setFilters ( filter ) ; return select ( stmt , qualifiers ) ; }
Select records filtered by a Filter and Qualifiers
14,109
public void insert ( String namespace , String set , Key key , List < Bin > bins ) { insert ( namespace , set , key , bins , 0 ) ; }
inserts a record . If the record exists and exception will be thrown .
14,110
public void insert ( String namespace , String set , Key key , List < Bin > bins , int ttl ) { this . client . put ( this . insertPolicy , key , bins . toArray ( new Bin [ 0 ] ) ) ; }
inserts a record with a time to live . If the record exists and exception will be thrown .
14,111
public void insert ( Statement stmt , KeyQualifier keyQualifier , List < Bin > bins ) { insert ( stmt , keyQualifier , bins , 0 ) ; }
inserts a record using a Statement and KeyQualifier . If the record exists and exception will be thrown .
14,112
public void insert ( Statement stmt , KeyQualifier keyQualifier , List < Bin > bins , int ttl ) { Key key = keyQualifier . makeKey ( stmt . getNamespace ( ) , stmt . getSetName ( ) ) ; this . client . put ( this . insertPolicy , key , bins . toArray ( new Bin [ 0 ] ) ) ; }
inserts a record with a time to live using a Statement and KeyQualifier . If the record exists and exception will be thrown .
14,113
public Map < String , Long > update ( Statement stmt , List < Bin > bins , Qualifier ... qualifiers ) { if ( qualifiers != null && qualifiers . length == 1 && qualifiers [ 0 ] instanceof KeyQualifier ) { KeyQualifier keyQualifier = ( KeyQualifier ) qualifiers [ 0 ] ; Key key = keyQualifier . makeKey ( stmt . getNamespace ( ) , stmt . getSetName ( ) ) ; this . client . put ( this . updatePolicy , key , bins . toArray ( new Bin [ 0 ] ) ) ; Map < String , Long > result = new HashMap < String , Long > ( ) ; result . put ( "read" , 1L ) ; result . put ( "write" , 1L ) ; return result ; } else { KeyRecordIterator results = select ( stmt , true , null , qualifiers ) ; return update ( results , bins ) ; } }
The list of Bins will update each record that match the Qualifiers supplied .
14,114
public Map < String , Long > delete ( Statement stmt , Qualifier ... qualifiers ) { if ( qualifiers == null || qualifiers . length == 0 ) { ExecuteTask task = client . execute ( null , stmt , QUERY_MODULE , "delete_record" ) ; task . waitTillComplete ( ) ; return null ; } if ( qualifiers . length == 1 && qualifiers [ 0 ] instanceof KeyQualifier ) { KeyQualifier keyQualifier = ( KeyQualifier ) qualifiers [ 0 ] ; Key key = keyQualifier . makeKey ( stmt . getNamespace ( ) , stmt . getSetName ( ) ) ; this . client . delete ( null , key ) ; Map < String , Long > map = new HashMap < String , Long > ( ) ; map . put ( "read" , 1L ) ; map . put ( "write" , 1L ) ; return map ; } KeyRecordIterator results = select ( stmt , true , null , qualifiers ) ; return delete ( results ) ; }
Deletes the records specified by the Statement and Qualifiers
14,115
public synchronized void refreshNamespaces ( ) { if ( this . namespaceCache == null ) { this . namespaceCache = new TreeMap < String , Namespace > ( ) ; Node [ ] nodes = client . getNodes ( ) ; for ( Node node : nodes ) { try { String namespaceString = Info . request ( getInfoPolicy ( ) , node , "namespaces" ) ; if ( ! namespaceString . isEmpty ( ) ) { String [ ] namespaceList = namespaceString . split ( ";" ) ; for ( String namespace : namespaceList ) { Namespace ns = this . namespaceCache . get ( namespace ) ; if ( ns == null ) { ns = new Namespace ( namespace ) ; this . namespaceCache . put ( namespace , ns ) ; } refreshNamespaceData ( node , ns ) ; } } } catch ( AerospikeException e ) { log . error ( "Error geting Namespaces " , e ) ; } } } }
refreshes the cached Namespace information
14,116
public synchronized void refreshIndexes ( ) { if ( this . indexCache == null ) this . indexCache = new TreeMap < String , Index > ( ) ; Node [ ] nodes = client . getNodes ( ) ; for ( Node node : nodes ) { if ( node . isActive ( ) ) { try { String indexString = Info . request ( getInfoPolicy ( ) , node , "sindex" ) ; if ( ! indexString . isEmpty ( ) ) { String [ ] indexList = indexString . split ( ";" ) ; for ( String oneIndexString : indexList ) { Index index = new Index ( oneIndexString ) ; this . indexCache . put ( index . toKeyString ( ) , index ) ; } } break ; } catch ( AerospikeException e ) { log . error ( "Error geting Index informaton" , e ) ; } } } }
refreshes the Index cache from the Cluster
14,117
public synchronized void refreshModules ( ) { if ( this . moduleCache == null ) this . moduleCache = new TreeMap < String , Module > ( ) ; boolean loadedModules = false ; Node [ ] nodes = client . getNodes ( ) ; for ( Node node : nodes ) { try { String packagesString = Info . request ( infoPolicy , node , "udf-list" ) ; if ( ! packagesString . isEmpty ( ) ) { String [ ] packagesList = packagesString . split ( ";" ) ; for ( String pkgString : packagesList ) { Module module = new Module ( pkgString ) ; String udfString = Info . request ( infoPolicy , node , "udf-get:filename=" + module . getName ( ) ) ; module . setDetailInfo ( udfString ) ; this . moduleCache . put ( module . getName ( ) , module ) ; } } loadedModules = true ; break ; } catch ( AerospikeException e ) { } } if ( ! loadedModules ) { throw new ClusterRefreshError ( "Cannot find UDF modules" ) ; } }
refreshes the Module cache from the cluster . The Module cache contains a list of register UDF modules .
14,118
public void close ( ) throws IOException { if ( this . client != null ) this . client . close ( ) ; indexCache . clear ( ) ; indexCache = null ; updatePolicy = null ; insertPolicy = null ; infoPolicy = null ; queryPolicy = null ; moduleCache . clear ( ) ; moduleCache = null ; }
closes the QueryEngine clearing the cached information are closing the AerospikeClient . Once the QueryEngine is closed it cannot be used nor can the AerospikeClient .
14,119
public void setIndexInfo ( String info ) { if ( ! info . isEmpty ( ) ) { String [ ] parts = info . split ( ":" ) ; for ( String part : parts ) { kvPut ( part ) ; } } }
Populates the Index object from an info message from Aerospike
14,120
public void clear ( ) { Record record = this . client . get ( null , key , tailBin , topBin ) ; long tail = record . getLong ( tailBin ) ; long top = record . getLong ( topBin ) ; List < Key > subKeys = subrecordKeys ( tail , top ) ; for ( Key key : subKeys ) { this . client . delete ( null , key ) ; } }
clear all elements from the TimeSeries associated with a Key
14,121
public void destroy ( ) { clear ( ) ; this . client . operate ( null , key , Operation . put ( Bin . asNull ( binName ) ) ) ; }
Destroy the TimeSeries associated with a Key
14,122
List < Key > subrecordKeys ( long lowTime , long highTime ) { List < Key > keys = new ArrayList < Key > ( ) ; long lowBucketNumber = bucketNumber ( lowTime ) ; long highBucketNumber = bucketNumber ( highTime ) ; for ( long index = lowBucketNumber ; index <= highBucketNumber ; index += this . bucketSize ) { keys . add ( formSubrecordKey ( index ) ) ; } return keys ; }
creates a list of Keys in the time series
14,123
public void update ( Value value ) { if ( size ( ) == 0 ) { add ( value ) ; } else { Key subKey = makeSubKey ( value ) ; client . put ( this . policy , subKey , new Bin ( ListElementBinName , value ) ) ; } }
Update value in list if key exists . Add value to list if key does not exist . If value is a map the key is identified by key entry . Otherwise the value is the key . If large list does not exist create it .
14,124
public void remove ( Value value ) { Key subKey = makeSubKey ( value ) ; List < byte [ ] > digestList = getDigestList ( ) ; int index = digestList . indexOf ( subKey . digest ) ; client . delete ( this . policy , subKey ) ; client . operate ( this . policy , this . key , ListOperation . remove ( this . binNameString , index ) ) ; }
Delete value from list .
14,125
public void remove ( List < Value > values ) { Key [ ] keys = makeSubKeys ( values ) ; List < byte [ ] > digestList = getDigestList ( ) ; for ( Key key : keys ) { client . delete ( this . policy , key ) ; digestList . remove ( key . digest ) ; } client . put ( this . policy , this . key , new Bin ( this . binNameString , digestList ) ) ; }
Delete values from list .
14,126
@ SuppressWarnings ( "serial" ) public List < ? > find ( Value value ) throws AerospikeException { Key subKey = makeSubKey ( value ) ; Record record = client . get ( this . policy , subKey , ListElementBinName ) ; if ( record != null ) { final Object result = record . getValue ( ListElementBinName ) ; return new ArrayList < Object > ( ) { { add ( result ) ; } } ; } else { return null ; } }
Select values from list .
14,127
public void destroy ( ) { List < byte [ ] > digestList = getDigestList ( ) ; client . put ( this . policy , this . key , Bin . asNull ( this . binNameString ) ) ; for ( byte [ ] digest : digestList ) { Key subKey = new Key ( this . key . namespace , digest , null , null ) ; client . delete ( this . policy , subKey ) ; } }
Delete bin containing the list .
14,128
public int size ( ) { Record record = client . operate ( this . policy , this . key , ListOperation . size ( this . binNameString ) ) ; if ( record != null ) { return record . getInt ( this . binNameString ) ; } return 0 ; }
Return size of list .
14,129
public static void printInfo ( String title , String infoString ) { if ( infoString == null ) { System . out . println ( "Null info string" ) ; return ; } String [ ] outerParts = infoString . split ( ";" ) ; System . out . println ( title ) ; for ( String s : outerParts ) { String [ ] innerParts = s . split ( ":" ) ; for ( String parts : innerParts ) { System . out . println ( "\t" + parts ) ; } System . out . println ( ) ; } }
Prints an Info message with a title to System . out
14,130
public static String infoAll ( AerospikeClient client , String cmd ) { Node [ ] nodes = client . getNodes ( ) ; StringBuilder results = new StringBuilder ( ) ; for ( Node node : nodes ) { results . append ( Info . request ( node . getHost ( ) . name , node . getHost ( ) . port , cmd ) ) . append ( "\n" ) ; } return results . toString ( ) ; }
Sends an Info command to all nodes in the cluster
14,131
public static Map < String , String > toMap ( String source ) { HashMap < String , String > responses = new HashMap < String , String > ( ) ; String values [ ] = source . split ( ";" ) ; for ( String value : values ) { String nv [ ] = value . split ( "=" ) ; if ( nv . length >= 2 ) { responses . put ( nv [ 0 ] , nv [ 1 ] ) ; } else if ( nv . length == 1 ) { responses . put ( nv [ 0 ] , null ) ; } } return responses . size ( ) != 0 ? responses : null ; }
converts the results of an Info command to a Map
14,132
public static List < NameValuePair > toNameValuePair ( Object parent , Map < String , String > map ) { List < NameValuePair > list = new ArrayList < NameValuePair > ( ) ; for ( String key : map . keySet ( ) ) { NameValuePair nvp = new NameValuePair ( parent , key , map . get ( key ) ) ; list . add ( nvp ) ; } return list ; }
Creates a List of NameValuePair from a Map
14,133
public static MultiPoint of ( Stream < Point > points ) { return of ( points . collect ( Collectors . toList ( ) ) ) ; }
Creates a MultiPoint from the given points .
14,134
public static LinearRing of ( Iterable < Point > points ) { LinearPositions . Builder builder = LinearPositions . builder ( ) ; for ( Point point : points ) { builder . addSinglePosition ( point . positions ( ) ) ; } return new LinearRing ( builder . build ( ) ) ; }
Create a LinearRing from the given points .
14,135
public List < Point > points ( ) { return positions ( ) . children ( ) . stream ( ) . map ( Point :: new ) . collect ( Collectors . toList ( ) ) ; }
Returns the points composing this Geometry .
14,136
public static Point from ( double lon , double lat , double alt ) { return new Point ( new SinglePosition ( lon , lat , alt ) ) ; }
Create a Point from the given coordinates .
14,137
public void fireEvent ( final Event < ? > event ) { Scheduler . get ( ) . scheduleDeferred ( new Scheduler . ScheduledCommand ( ) { public void execute ( ) { bus . fireEventFromSource ( event , dialog . getInterfaceModel ( ) . getId ( ) ) ; } } ) ; }
Event delegation . Uses the dialog ID as source .
14,138
public void onInteractionEvent ( final InteractionEvent event ) { QName id = event . getId ( ) ; QName source = ( QName ) event . getSource ( ) ; final Set < Procedure > collection = procedures . get ( id ) ; Procedure execution = null ; if ( collection != null ) { for ( Procedure consumer : collection ) { Resource < ResourceType > resource = new Resource < ResourceType > ( id , ResourceType . Interaction ) ; resource . setSource ( source ) ; boolean justified = consumer . getJustification ( ) == null || source . equals ( consumer . getJustification ( ) ) ; if ( consumer . doesConsume ( resource ) && justified ) { execution = consumer ; break ; } } } if ( null == execution ) { Window . alert ( "No procedure for " + event ) ; Log . warn ( "No procedure for " + event ) ; } else if ( execution . getPrecondition ( ) . isMet ( getStatementContext ( source ) ) ) { try { execution . getCommand ( ) . execute ( InteractionCoordinator . this . dialog , event . getPayload ( ) ) ; } catch ( Throwable e ) { Log . error ( "Failed to execute procedure " + execution , e ) ; } } }
Find the corresponding procedures and execute it .
14,139
public void onSaveDatasource ( AddressTemplate template , final String dsName , final Map changeset ) { dataSourceStore . saveDatasource ( template , dsName , changeset , new SimpleCallback < ResponseWrapper < Boolean > > ( ) { public void onSuccess ( ResponseWrapper < Boolean > response ) { if ( response . getUnderlying ( ) ) { Console . info ( Console . MESSAGES . saved ( "Datasource " + dsName ) ) ; } else { Console . error ( Console . MESSAGES . saveFailed ( "Datasource " ) + dsName , response . getResponse ( ) . toString ( ) ) ; } loadXADataSource ( ) ; } } ) ; }
Saves the changes into data - source or xa - data - source using ModelNodeAdapter instead of autobean DataSource
14,140
public void onCreateProperty ( String reference , PropertyRecord prop ) { presenter . onCreateXAProperty ( reference , prop ) ; }
property management below
14,141
protected void code ( String template , String packageName , String className , Supplier < Map < String , Object > > context ) { StringBuffer code = generate ( template , context ) ; writeCode ( packageName , className , code ) ; }
Generates and writes java code in one call .
14,142
protected void resource ( String template , String packageName , String resourceName , Supplier < Map < String , Object > > context ) { StringBuffer code = generate ( template , context ) ; writeResource ( packageName , resourceName , code ) ; }
Generates and writes a resource in one call .
14,143
public void flushChildScopes ( QName unitId ) { Set < Integer > childScopes = findChildScopes ( unitId ) ; for ( Integer scopeId : childScopes ) { MutableContext mutableContext = statementContexts . get ( scopeId ) ; mutableContext . clearStatements ( ) ; } }
Flush the scope of unit and all children .
14,144
public boolean isWithinActiveScope ( final QName unitId ) { final Node < Scope > self = dialog . getScopeModel ( ) . findNode ( dialog . findUnit ( unitId ) . getScopeId ( ) ) ; final Scope scopeOfUnit = self . getData ( ) ; int parentScopeId = getParentScope ( unitId ) . getId ( ) ; Scope activeScope = activeChildMapping . get ( parentScopeId ) ; boolean selfIsActive = activeScope != null && activeScope . equals ( scopeOfUnit ) ; if ( selfIsActive ) { LinkedList < Scope > parentScopes = new LinkedList < Scope > ( ) ; getParentScopes ( self , parentScopes ) ; boolean inActiveParent = false ; for ( Scope parent : parentScopes ) { if ( ! parent . isActive ( ) ) { inActiveParent = true ; break ; } } return inActiveParent ; } return selfIsActive ; }
Is within active scope when itself and all it s parent scopes are active as well . This is necessary to ensure access to statements from parent scopes .
14,145
public ModelNode fromChangeSet ( ResourceAddress resourceAddress , Map < String , Object > changeSet ) { ModelNode define = new ModelNode ( ) ; define . get ( ADDRESS ) . set ( resourceAddress ) ; define . get ( OP ) . set ( WRITE_ATTRIBUTE_OPERATION ) ; ModelNode undefine = new ModelNode ( ) ; undefine . get ( ADDRESS ) . set ( resourceAddress ) ; undefine . get ( OP ) . set ( UNDEFINE_ATTRIBUTE ) ; ModelNode operation = new ModelNode ( ) ; operation . get ( OP ) . set ( COMPOSITE ) ; operation . get ( ADDRESS ) . setEmptyList ( ) ; List < ModelNode > steps = new ArrayList < > ( ) ; for ( String key : changeSet . keySet ( ) ) { Object value = changeSet . get ( key ) ; ModelNode step ; if ( value . equals ( FormItem . VALUE_SEMANTICS . UNDEFINED ) ) { step = undefine . clone ( ) ; step . get ( NAME ) . set ( key ) ; } else { step = define . clone ( ) ; step . get ( NAME ) . set ( key ) ; ModelNode valueNode = step . get ( VALUE ) ; setValue ( valueNode , value ) ; } steps . add ( step ) ; } operation . get ( STEPS ) . set ( steps ) ; return operation ; }
Turns a change set into a composite write attribute operation .
14,146
public List < T > apply ( Predicate < T > predicate , List < T > candidates ) { List < T > filtered = new ArrayList < T > ( candidates . size ( ) ) ; for ( T entity : candidates ) { if ( predicate . appliesTo ( entity ) ) filtered . add ( entity ) ; } return filtered ; }
Filter a list of entities through a predicate . If the the predicate applies the entity will be included .
14,147
static void parseSubsystems ( ModelNode node , List < Subsystem > subsystems ) { List < Property > properties = node . get ( "subsystem" ) . asPropertyList ( ) ; for ( Property property : properties ) { Subsystem subsystem = new Subsystem ( property . getName ( ) , property . getValue ( ) ) ; subsystems . add ( subsystem ) ; } }
Expects a subsystem child resource . Modeled as a static helper method to make it usable from both deployments and subdeployments .
14,148
private static void assignKeyFromAddressNode ( ModelNode payload , ModelNode address ) { List < Property > props = address . asPropertyList ( ) ; Property lastToken = props . get ( props . size ( ) - 1 ) ; payload . get ( "entity.key" ) . set ( lastToken . getValue ( ) . asString ( ) ) ; }
the model representations we use internally carry along the entity keys . these are derived from the resource address but will be available as synthetic resource attributes .
14,149
public void navigateHandlerView ( ) { if ( tabLayoutpanel . getSelectedIndex ( ) == 1 ) { if ( endpointHandlerPages . getPage ( ) == 0 ) endpointHandlerPages . showPage ( 1 ) ; } else if ( tabLayoutpanel . getSelectedIndex ( ) == 2 ) { if ( clientHandlerPages . getPage ( ) == 0 ) clientHandlerPages . showPage ( 1 ) ; } }
to show a specific panel accordingly to the selected tab
14,150
@ SuppressWarnings ( "unchecked" ) public < T extends ElementType > boolean positiveLookaheadBefore ( ElementType before , T ... expected ) { Character lookahead ; for ( int i = 1 ; i <= elements . length ; i ++ ) { lookahead = lookahead ( i ) ; if ( before . isMatchedBy ( lookahead ) ) { break ; } for ( ElementType type : expected ) { if ( type . isMatchedBy ( lookahead ) ) { return true ; } } } return false ; }
Checks if there exists an element in this stream of the expected types before the specified type .
14,151
private void pushState ( final S state ) { this . state = state ; header . setHTML ( TEMPLATE . header ( currentStep ( ) . getTitle ( ) ) ) ; clearError ( ) ; body . showWidget ( state ) ; footer . back . setEnabled ( state != initialState ( ) ) ; footer . next . setHTML ( lastStates ( ) . contains ( state ) ? CONSTANTS . common_label_finish ( ) : CONSTANTS . common_label_next ( ) ) ; }
Sets the current state to the specified state and updates the UI to reflect the current state .
14,152
public void showAddDialog ( final ModelNode address , boolean isSingleton , SecurityContext securityContext , ModelNode description ) { String resourceAddress = AddressUtils . asKey ( address , isSingleton ) ; if ( securityContext . getOperationPriviledge ( resourceAddress , "add" ) . isGranted ( ) ) { _showAddDialog ( address , isSingleton , securityContext , description ) ; } else { Feedback . alert ( Console . CONSTANTS . unauthorized ( ) , Console . CONSTANTS . unauthorizedAdd ( ) ) ; } }
Callback for creation of add dialogs . Will be invoked once the presenter has loaded the resource description .
14,153
public void onSaveFilter ( AddressTemplate address , String name , Map changeset ) { operationDelegate . onSaveResource ( address , name , changeset , defaultSaveOpCallbacks ) ; }
Save an existent filter .
14,154
private boolean configUpdated ( ) { try { URL url = ctx . getResource ( resourcesDir + configResource ) ; URLConnection con ; if ( url == null ) return false ; con = url . openConnection ( ) ; long lastModified = con . getLastModified ( ) ; long XHP_LAST_MODIFIEDModified = 0 ; if ( ctx . getAttribute ( XHP_LAST_MODIFIED ) != null ) { XHP_LAST_MODIFIEDModified = ( ( Long ) ctx . getAttribute ( XHP_LAST_MODIFIED ) ) . longValue ( ) ; } else { ctx . setAttribute ( XHP_LAST_MODIFIED , new Long ( lastModified ) ) ; return false ; } if ( XHP_LAST_MODIFIEDModified < lastModified ) { ctx . setAttribute ( XHP_LAST_MODIFIED , new Long ( lastModified ) ) ; return true ; } } catch ( Exception ex ) { getLogger ( ) . severe ( "XmlHttpProxyServlet error checking configuration: " + ex ) ; } return false ; }
Check to see if the configuration file has been updated so that it may be reloaded .
14,155
public < T extends Mapping > T getMapping ( MappingType type ) { return ( T ) mappings . get ( type ) ; }
Get a mapping local to this unit .
14,156
public < T extends Mapping > T findMapping ( MappingType type ) { return ( T ) this . findMapping ( type , DEFAULT_PREDICATE ) ; }
Finds the first mapping of a type within the hierarchy . Uses parent delegation if the mapping cannot be found locally .
14,157
public void transform ( InputStream xmlIS , InputStream xslIS , Map params , OutputStream result , String encoding ) { try { TransformerFactory trFac = TransformerFactory . newInstance ( ) ; Transformer transformer = trFac . newTransformer ( new StreamSource ( xslIS ) ) ; Iterator it = params . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { String key = ( String ) it . next ( ) ; transformer . setParameter ( key , ( String ) params . get ( key ) ) ; } transformer . setOutputProperty ( "encoding" , encoding ) ; transformer . transform ( new StreamSource ( xmlIS ) , new StreamResult ( result ) ) ; } catch ( Exception e ) { getLogger ( ) . severe ( "XmlHttpProxy: Exception with xslt " + e ) ; } }
Do the XSLT transformation
14,158
protected static String jsonEscape ( final String orig ) { final int length = orig . length ( ) ; final StringBuilder builder = new StringBuilder ( length + 32 ) ; builder . append ( '"' ) ; for ( int i = 0 ; i < length ; i = orig . offsetByCodePoints ( i , 1 ) ) { final char cp = orig . charAt ( i ) ; switch ( cp ) { case '"' : builder . append ( "\\\"" ) ; break ; case '\\' : builder . append ( "\\\\" ) ; break ; case '\b' : builder . append ( "\\b" ) ; break ; case '\f' : builder . append ( "\\f" ) ; break ; case '\n' : builder . append ( "\\n" ) ; break ; case '\r' : builder . append ( "\\r" ) ; break ; case '\t' : builder . append ( "\\t" ) ; break ; case '/' : builder . append ( "\\/" ) ; break ; default : if ( ( cp >= '\u0000' && cp <= '\u001F' ) || ( cp >= '\u007F' && cp <= '\u009F' ) || ( cp >= '\u2000' && cp <= '\u20FF' ) ) { final String hexString = Integer . toHexString ( cp ) ; builder . append ( "\\u" ) ; for ( int k = 0 ; k < 4 - hexString . length ( ) ; k ++ ) { builder . append ( '0' ) ; } builder . append ( hexString . toUpperCase ( ) ) ; } else { builder . append ( cp ) ; } break ; } } builder . append ( '"' ) ; return builder . toString ( ) ; }
Escapes the original string for inclusion in a JSON string .
14,159
public String toJSONString ( final boolean compact ) { final StringBuilder builder = new StringBuilder ( ) ; formatAsJSON ( builder , 0 , ! compact ) ; return builder . toString ( ) ; }
Converts this value to a JSON string representation .
14,160
public < T > void set ( String key , T value ) { data . put ( key , value ) ; }
Stores the value under the given key in the context map .
14,161
public void single ( final C context , Outcome < C > outcome , final Function < C > function ) { SingletonControl ctrl = new SingletonControl ( context , outcome ) ; progress . reset ( 1 ) ; function . execute ( ctrl ) ; }
Convenience method to executes a single function . Use this method if you have implemented your business logic across different functions but just want to execute a single function .
14,162
@ SuppressWarnings ( "unchecked" ) public void series ( final Outcome outcome , final Function ... functions ) { _series ( null , outcome , functions ) ; }
Run an array of functions in series each one running once the previous function has completed . If any functions in the series pass an error to its callback no more functions are run and outcome for the series is immediately called with the value of the error .
14,163
public final void waterfall ( final C context , final Outcome < C > outcome , final Function < C > ... functions ) { _series ( context , outcome , functions ) ; }
Runs an array of functions in series working on a shared context . However if any of the functions pass an error to the callback the next function is not executed and the outcome is immediately called with the error .
14,164
@ SuppressWarnings ( "unchecked" ) public void parallel ( C context , final Outcome < C > outcome , final Function < C > ... functions ) { final C finalContext = context != null ? context : ( C ) EMPTY_CONTEXT ; final CountingControl ctrl = new CountingControl ( finalContext , functions ) ; progress . reset ( functions . length ) ; Scheduler . get ( ) . scheduleIncremental ( new Scheduler . RepeatingCommand ( ) { public boolean execute ( ) { if ( ctrl . isAborted ( ) || ctrl . allFinished ( ) ) { Scheduler . get ( ) . scheduleDeferred ( new Scheduler . ScheduledCommand ( ) { @ SuppressWarnings ( "unchecked" ) public void execute ( ) { if ( ctrl . isAborted ( ) ) { progress . finish ( ) ; outcome . onFailure ( finalContext ) ; } else { progress . finish ( ) ; outcome . onSuccess ( finalContext ) ; } } } ) ; return false ; } else { ctrl . next ( ) ; return true ; } } } ) ; }
Run an array of functions in parallel without waiting until the previous function has completed . If any of the functions pass an error to its callback the outcome is immediately called with the value of the error .
14,165
public void whilst ( Precondition condition , final Outcome outcome , final Function function ) { whilst ( condition , outcome , function , - 1 ) ; }
Repeatedly call function while condition is met . Calls the callback when stopped or an error occurs .
14,166
private static void assertConsumer ( InteractionUnit unit , Map < QName , Set < Procedure > > behaviours , IntegrityErrors err ) { Set < Resource < ResourceType > > producedTypes = unit . getOutputs ( ) ; for ( Resource < ResourceType > resource : producedTypes ) { boolean match = false ; for ( QName id : behaviours . keySet ( ) ) { for ( Behaviour behaviour : behaviours . get ( id ) ) { if ( behaviour . doesConsume ( resource ) ) { match = true ; break ; } } } if ( ! match ) err . add ( unit . getId ( ) , "Missing consumer for <<" + resource + ">>" ) ; } }
Assertion that a consumer exists for the produced resources of an interaction unit .
14,167
private static void assertProducer ( InteractionUnit unit , Map < QName , Set < Procedure > > behaviours , IntegrityErrors err ) { Set < Resource < ResourceType > > consumedTypes = unit . getInputs ( ) ; for ( Resource < ResourceType > resource : consumedTypes ) { boolean match = false ; for ( QName id : behaviours . keySet ( ) ) { for ( Behaviour candidate : behaviours . get ( id ) ) { if ( candidate . doesProduce ( resource ) ) { match = candidate . getJustification ( ) == null || unit . getId ( ) . equals ( candidate . getJustification ( ) ) ; } if ( match ) break ; } if ( match ) break ; } if ( ! match ) err . add ( unit . getId ( ) , "Missing producer for <<" + resource + ">>" ) ; } }
Assertion that a producer exists for the consumed resources of an interaction unit .
14,168
public void setChoices ( List < String > choices ) { if ( ! limitChoices ) throw new IllegalArgumentException ( "Attempted to set choices when choices are not limited." ) ; List < String > sorted = new ArrayList < String > ( ) ; sorted . addAll ( choices ) ; Collections . sort ( sorted ) ; ( ( ComboBoxItem ) this . nameItem ) . setValueMap ( sorted ) ; }
Called before opening the dialog so that the user sees only the valid choices .
14,169
public String getResourceType ( ) { if ( ! tokens . isEmpty ( ) && tokens . getLast ( ) . hasKey ( ) ) { return tokens . getLast ( ) . getKey ( ) ; } return null ; }
Returns the resource type of the last segment for this address template
14,170
public void reset ( ) { for ( long i = 0 ; i < idCounter ; i ++ ) { localStorage . removeItem ( key ( i ) ) ; } idCounter = 0 ; localStorage . removeItem ( documentsKey ( ) ) ; localStorage . removeItem ( indexKey ( ) ) ; resetInternal ( ) ; Log . info ( "Reset index to " + indexKey ( ) ) ; }
Resets the index
14,171
public List < Property > asPropertyList ( ) throws IllegalArgumentException { if ( ModelValue . UNDEFINED == value ) return Collections . EMPTY_LIST ; else return value . asPropertyList ( ) ; }
Get the value of this node as a property list . Object values will return a list of properties representing each key - value pair in the object . List values will return all the values of the list failing if any of the values are not convertible to a property value .
14,172
public ModelNode setExpression ( final String newValue ) { if ( newValue == null ) { throw new IllegalArgumentException ( "newValue is null" ) ; } checkProtect ( ) ; value = new ExpressionValue ( newValue ) ; return this ; }
Change this node s value to the given expression value .
14,173
public ModelNode set ( final String newValue ) { if ( newValue == null ) { throw new IllegalArgumentException ( "newValue is null" ) ; } checkProtect ( ) ; value = new StringModelValue ( newValue ) ; return this ; }
Change this node s value to the given value .
14,174
public void onCreateResource ( final AddressTemplate addressTemplate , final String name , final ModelNode payload , final Callback ... callback ) { ModelNode op = payload . clone ( ) ; op . get ( ADDRESS ) . set ( addressTemplate . resolve ( statementContext , name ) ) ; op . get ( OP ) . set ( ADD ) ; dispatcher . execute ( new DMRAction ( op ) , new AsyncCallback < DMRResponse > ( ) { public void onFailure ( Throwable caught ) { for ( Callback cb : callback ) { cb . onFailure ( addressTemplate , name , caught ) ; } } public void onSuccess ( DMRResponse result ) { ModelNode response = result . get ( ) ; if ( response . isFailure ( ) ) { for ( Callback cb : callback ) { cb . onFailure ( addressTemplate , name , new RuntimeException ( "Failed to add resource " + addressTemplate . replaceWildcards ( name ) + ":" + response . getFailureDescription ( ) ) ) ; } } else { for ( Callback cb : callback ) { cb . onSuccess ( addressTemplate , name ) ; } } } } ) ; }
Creates a new resource using the given address name and payload .
14,175
public void onSaveResource ( final AddressTemplate addressTemplate , final String name , Map < String , Object > changedValues , final Callback ... callback ) { final ResourceAddress address = addressTemplate . resolve ( statementContext , name ) ; final ModelNodeAdapter adapter = new ModelNodeAdapter ( ) ; ModelNode op = adapter . fromChangeSet ( address , changedValues ) ; dispatcher . execute ( new DMRAction ( op ) , new AsyncCallback < DMRResponse > ( ) { public void onFailure ( Throwable caught ) { for ( Callback cb : callback ) { cb . onFailure ( addressTemplate , name , caught ) ; } } public void onSuccess ( DMRResponse dmrResponse ) { ModelNode response = dmrResponse . get ( ) ; if ( response . isFailure ( ) ) { Console . error ( Console . MESSAGES . saveFailed ( name ) , response . getFailureDescription ( ) ) ; for ( Callback cb : callback ) { cb . onFailure ( addressTemplate , name , new RuntimeException ( Console . MESSAGES . saveFailed ( addressTemplate . replaceWildcards ( name ) . toString ( ) ) + ":" + response . getFailureDescription ( ) ) ) ; } } else { for ( Callback cb : callback ) { cb . onSuccess ( addressTemplate , name ) ; } } } } ) ; }
Updates an existing resource using the given address name and changed values .
14,176
public void prepare ( Element anchor , T item ) { this . currentAnchor = anchor ; this . currentItem = item ; if ( ! this . timer . isRunning ( ) ) { timer . schedule ( DELAY_MS ) ; } }
prepare the displaying of the tooltip or ignore the call when it s already active
14,177
public void setWidgetMinSize ( Widget child , int minSize ) { assertIsChild ( child ) ; Splitter splitter = getAssociatedSplitter ( child ) ; if ( splitter != null ) { splitter . setMinSize ( minSize ) ; } }
Sets the minimum allowable size for the given widget .
14,178
public void setWidgetToggleDisplayAllowed ( Widget child , boolean allowed ) { assertIsChild ( child ) ; Splitter splitter = getAssociatedSplitter ( child ) ; if ( splitter != null ) { splitter . setToggleDisplayAllowed ( allowed ) ; } }
Sets whether or not double - clicking on the splitter should toggle the display of the widget .
14,179
private void onItemSelected ( TreeItem treeItem ) { treeItem . getElement ( ) . focus ( ) ; final LinkedList < String > path = resolvePath ( treeItem ) ; formView . clearDisplay ( ) ; descView . clearDisplay ( ) ; ModelNode address = toAddress ( path ) ; ModelNode displayAddress = address . clone ( ) ; boolean isPlaceHolder = ( treeItem instanceof PlaceholderItem ) ; if ( path . size ( ) % 2 == 0 ) { presenter . readResource ( address , isPlaceHolder ) ; toggleEditor ( true ) ; filter . setEnabled ( true ) ; } else { toggleEditor ( false ) ; displayAddress . add ( path . getLast ( ) , WILDCARD ) ; loadChildren ( ( ModelTreeItem ) treeItem , false ) ; filter . setEnabled ( false ) ; } nodeHeader . updateDescription ( displayAddress ) ; }
When a tree item is clicked we load the resource .
14,180
public void updateRootTypes ( ModelNode address , List < ModelNode > modelNodes ) { deck . showWidget ( CHILD_VIEW ) ; tree . clear ( ) ; descView . clearDisplay ( ) ; formView . clearDisplay ( ) ; offsetDisplay . clear ( ) ; addressOffset = address ; nodeHeader . updateDescription ( address ) ; List < Property > offset = addressOffset . asPropertyList ( ) ; if ( offset . size ( ) > 0 ) { String parentName = offset . get ( offset . size ( ) - 1 ) . getName ( ) ; HTML parentTag = new HTML ( "<div class='gwt-ToggleButton gwt-ToggleButton-down' title='Remove Filter'>&nbsp;" + parentName + "&nbsp;<i class='icon-remove'></i></div>" ) ; parentTag . addClickHandler ( new ClickHandler ( ) { public void onClick ( ClickEvent event ) { presenter . onPinTreeSelection ( null ) ; } } ) ; offsetDisplay . add ( parentTag ) ; } TreeItem rootItem = null ; String rootTitle = null ; String key = null ; if ( address . asList ( ) . isEmpty ( ) ) { rootTitle = DEFAULT_ROOT ; key = DEFAULT_ROOT ; } else { List < ModelNode > tuples = address . asList ( ) ; rootTitle = tuples . get ( tuples . size ( ) - 1 ) . asProperty ( ) . getValue ( ) . asString ( ) ; key = rootTitle ; } SafeHtmlBuilder html = new SafeHtmlBuilder ( ) . appendEscaped ( rootTitle ) ; rootItem = new ModelTreeItem ( html . toSafeHtml ( ) , key , address , false ) ; tree . addItem ( rootItem ) ; deck . showWidget ( RESOURCE_VIEW ) ; rootItem . setSelected ( true ) ; currentRootKey = key ; addChildrenTypes ( ( ModelTreeItem ) rootItem , modelNodes ) ; }
Update root node . Basicaly a refresh of the tree .
14,181
public void updateChildrenTypes ( ModelNode address , List < ModelNode > modelNodes ) { TreeItem rootItem = findTreeItem ( tree , address ) ; addChildrenTypes ( ( ModelTreeItem ) rootItem , modelNodes ) ; }
Update sub parts of the tree
14,182
private ServerGroupRecord model2ServerGroup ( String groupName , ModelNode model ) { ServerGroupRecord record = factory . serverGroup ( ) . as ( ) ; record . setName ( groupName ) ; record . setProfileName ( model . get ( "profile" ) . asString ( ) ) ; record . setSocketBinding ( model . get ( "socket-binding-group" ) . asString ( ) ) ; Jvm jvm = ModelAdapter . model2JVM ( factory , model ) ; if ( jvm != null ) jvm . setInherited ( false ) ; record . setJvm ( jvm ) ; List < PropertyRecord > propertyRecords = ModelAdapter . model2Property ( factory , model ) ; record . setProperties ( propertyRecords ) ; return record ; }
Turns a server group DMR model into a strongly typed entity
14,183
public AuthorisationDecision getReadPriviledge ( ) { return checkPriviledge ( new Priviledge ( ) { public boolean isGranted ( Constraints c ) { boolean readable = c . isReadResource ( ) ; if ( ! readable ) Log . info ( "read privilege denied for: " + c . getResourceAddress ( ) ) ; return readable ; } } , false ) ; }
If any of the required resources is not accessible overall access will be rejected
14,184
public static void setValue ( ModelNode target , ModelType type , Object propValue ) { if ( type . equals ( ModelType . STRING ) ) { target . set ( ( String ) propValue ) ; } else if ( type . equals ( ModelType . INT ) ) { target . set ( ( Integer ) propValue ) ; } else if ( type . equals ( ModelType . DOUBLE ) ) { target . set ( ( Double ) propValue ) ; } else if ( type . equals ( ModelType . LONG ) ) { try { target . set ( ( Long ) propValue ) ; } catch ( Throwable e ) { target . set ( Integer . valueOf ( ( Integer ) propValue ) ) ; } } else if ( type . equals ( ModelType . BIG_DECIMAL ) ) { try { target . set ( ( BigDecimal ) propValue ) ; } catch ( Throwable e ) { target . set ( Double . valueOf ( ( Double ) propValue ) ) ; } } else if ( type . equals ( ModelType . BOOLEAN ) ) { target . set ( ( Boolean ) propValue ) ; } else if ( type . equals ( ModelType . LIST ) ) { target . setEmptyList ( ) ; List list = ( List ) propValue ; for ( Object item : list ) { target . add ( String . valueOf ( item ) ) ; } } else { Log . warn ( "Type conversionnot supported for " + type ) ; target . setEmptyObject ( ) ; } }
a more lenient way to update values by type
14,185
private void doGroupCheck ( ) { if ( ! hasTabs ( ) ) return ; for ( String groupName : getGroupNames ( ) ) { String tabName = getGroupedAttribtes ( groupName ) . get ( 0 ) . getTabName ( ) ; for ( PropertyBinding propBinding : getGroupedAttribtes ( groupName ) ) { if ( ! tabName . equals ( propBinding . getTabName ( ) ) ) { throw new RuntimeException ( "FormItem " + propBinding . getJavaName ( ) + " must be on the same tab with all members of its subgroup." ) ; } } } }
make sure all grouped attributes are on the same tab
14,186
public void onRemoveChildResource ( final ModelNode address , final ModelNode selection ) { final ModelNode fqAddress = AddressUtils . toFqAddress ( address , selection . asString ( ) ) ; _loadMetaData ( fqAddress , new ResourceData ( true ) , new Outcome < ResourceData > ( ) { public void onFailure ( ResourceData context ) { Console . error ( "Failed to load metadata for " + address . asString ( ) ) ; } public void onSuccess ( ResourceData context ) { String resourceAddress = AddressUtils . asKey ( fqAddress , true ) ; if ( context . securityContext . getWritePrivilege ( resourceAddress ) . isGranted ( ) ) { _onRemoveChildResource ( address , selection ) ; } else { Feedback . alert ( Console . CONSTANTS . unauthorized ( ) , Console . CONSTANTS . unauthorizedRemove ( ) ) ; } } } ) ; }
Checks permissions and removes a child resource
14,187
private void _onRemoveChildResource ( final ModelNode address , final ModelNode selection ) { final ModelNode fqAddress = AddressUtils . toFqAddress ( address , selection . asString ( ) ) ; final ModelNode operation = new ModelNode ( ) ; operation . get ( OP ) . set ( REMOVE ) ; operation . get ( ADDRESS ) . set ( fqAddress ) ; Feedback . confirm ( "Remove Resource" , "Do you really want to remove resource " + fqAddress . toString ( ) , new Feedback . ConfirmationHandler ( ) { public void onConfirmation ( boolean isConfirmed ) { if ( isConfirmed ) { dispatcher . execute ( new DMRAction ( operation ) , new SimpleCallback < DMRResponse > ( ) { public void onSuccess ( DMRResponse dmrResponse ) { ModelNode response = dmrResponse . get ( ) ; if ( response . isFailure ( ) ) { Console . error ( "Failed to remove resource " + fqAddress . asString ( ) , response . getFailureDescription ( ) ) ; } else { Console . info ( "Successfully removed resource " + fqAddress . asString ( ) ) ; readChildrenNames ( address ) ; } } } ) ; } } } ) ; }
Remove a child resource
14,188
public void onPrepareAddChildResource ( final ModelNode address , final boolean isSingleton ) { _loadMetaData ( address , new ResourceData ( true ) , new Outcome < ResourceData > ( ) { public void onFailure ( ResourceData context ) { Console . error ( "Failed to load metadata for " + address . asString ( ) ) ; } public void onSuccess ( ResourceData context ) { if ( isSingleton && context . description . get ( ATTRIBUTES ) . asList ( ) . isEmpty ( ) && context . description . get ( OPERATIONS ) . get ( ADD ) . get ( REQUEST_PROPERTIES ) . asList ( ) . isEmpty ( ) ) { onAddChildResource ( address , new ModelNode ( ) ) ; } else { view . showAddDialog ( address , isSingleton , context . securityContext , context . description ) ; } } } ) ; }
Add a child resource
14,189
private void populateRepackagedToCredentialReference ( ModelNode payload , String repackagedPropName , String propertyName ) { ModelNode value = payload . get ( repackagedPropName ) ; if ( payload . hasDefined ( repackagedPropName ) && value . asString ( ) . trim ( ) . length ( ) > 0 ) { payload . get ( CREDENTIAL_REFERENCE ) . get ( propertyName ) . set ( value ) ; } payload . remove ( repackagedPropName ) ; }
create a flat node copying the credential - reference complex attribute as regular attributes of the payload
14,190
public Map < String , Integer > getRequiredStatements ( ) { Map < String , Integer > required = new HashMap < String , Integer > ( ) ; for ( Token token : address ) { if ( ! token . hasKey ( ) ) { continue ; } else { String value_ref = token . getValue ( ) ; if ( value_ref . startsWith ( "{" ) ) { value_ref = value_ref . substring ( 1 , value_ref . length ( ) - 1 ) ; if ( ! required . containsKey ( value_ref ) ) { required . put ( value_ref , 1 ) ; } else { Integer count = required . get ( value_ref ) ; ++ count ; required . put ( value_ref , count ) ; } } } } return required ; }
Parses the address declaration for tokens that need to be resolved against the statement context .
14,191
private HttpURLConnection getURLConnection ( String str ) throws MalformedURLException { try { if ( isHttps ) { Security . addProvider ( new com . sun . net . ssl . internal . ssl . Provider ( ) ) ; System . setProperty ( "java.protocol.handler.pkgs" , "com.sun.net.ssl.internal.www.protocol" ) ; if ( isProxy ) { System . setProperty ( "https.proxyHost" , proxyHost ) ; System . setProperty ( "https.proxyPort" , proxyPort + "" ) ; } } else { if ( isProxy ) { System . setProperty ( "http.proxyHost" , proxyHost ) ; System . setProperty ( "http.proxyPort" , proxyPort + "" ) ; } } URL url = new URL ( str ) ; HttpURLConnection uc = ( HttpURLConnection ) url . openConnection ( ) ; if ( headers == null || ( headers != null && headers . get ( "user-agent" ) == null ) ) { String ua = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)" ; uc . setRequestProperty ( "user-agent" , ua ) ; } uc . setInstanceFollowRedirects ( false ) ; return uc ; } catch ( MalformedURLException me ) { throw new MalformedURLException ( str + " is not a valid URL" ) ; } catch ( Exception e ) { throw new RuntimeException ( "Unknown error creating UrlConnection: " + e ) ; } }
private method to get the URLConnection
14,192
public InputStream getInputStream ( ) { try { int responseCode = this . urlConnection . getResponseCode ( ) ; try { if ( responseCode == 302 ) { HttpClient redirectClient = new HttpClient ( proxyHost , proxyPort , urlConnection . getHeaderField ( "Location" ) , headers , urlConnection . getRequestMethod ( ) , callback , authHeader ) ; redirectClient . getInputStream ( ) . close ( ) ; } } catch ( Throwable e ) { System . out . println ( "Following redirect failed" ) ; } setCookieHeader = this . urlConnection . getHeaderField ( "Set-Cookie" ) ; InputStream in = responseCode != HttpURLConnection . HTTP_OK ? this . urlConnection . getErrorStream ( ) : this . urlConnection . getInputStream ( ) ; return in ; } catch ( Exception e ) { return null ; } }
returns the inputstream from URLConnection
14,193
public InputStream doPost ( byte [ ] postData , String contentType ) { this . urlConnection . setDoOutput ( true ) ; if ( contentType != null ) this . urlConnection . setRequestProperty ( "Content-type" , contentType ) ; OutputStream out = null ; try { out = this . getOutputStream ( ) ; if ( out != null ) { out . write ( postData ) ; out . flush ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( out != null ) try { out . close ( ) ; } catch ( IOException e ) { } } return ( this . getInputStream ( ) ) ; }
posts data to the inputstream and returns the InputStream .
14,194
public void toggle ( ) { Command cmd = state . isPrimary ( ) ? command1 : command2 ; setState ( state . other ( ) ) ; cmd . execute ( ) ; }
Toggles the link executing the command . All state is changed before the command is executed and it is therefore safe to call this from within the commands .
14,195
public void setState ( State state ) { this . state = state ; setText ( state . isPrimary ( ) ? text1 : text2 ) ; }
Changes the state without executing the command .
14,196
public String getNormalizedLocalPart ( ) { int i = localPart . indexOf ( "#" ) ; if ( i != - 1 ) return localPart . substring ( 0 , i ) ; else return localPart ; }
return the local part without suffix
14,197
private boolean createChild ( Property sibling , String parentURI ) { boolean skipped = sibling . getName ( ) . equals ( "children" ) ; if ( ! skipped ) { String dataType = null ; String uri = "" ; if ( sibling . getValue ( ) . hasDefined ( "class-name" ) ) { dataType = sibling . getValue ( ) . get ( "class-name" ) . asString ( ) ; uri = parentURI + "/" + sibling . getName ( ) ; int idx = uri . indexOf ( ':' ) ; if ( idx > 0 ) { int idx2 = uri . lastIndexOf ( '/' , idx ) ; if ( idx2 >= 0 && ( idx2 + 1 ) < uri . length ( ) ) uri = uri . substring ( idx2 + 1 ) ; } } JndiEntry next = new JndiEntry ( sibling . getName ( ) , uri , dataType ) ; if ( sibling . getValue ( ) . hasDefined ( "value" ) ) next . setValue ( sibling . getValue ( ) . get ( "value" ) . asString ( ) ) ; stack . peek ( ) . getChildren ( ) . add ( next ) ; stack . push ( next ) ; } return skipped ; }
create actual children
14,198
public void selectTab ( final String text ) { for ( int i = 0 ; i < tabs . size ( ) ; i ++ ) { if ( text . equals ( tabs . get ( i ) . getText ( ) ) ) { selectTab ( i ) ; return ; } } for ( OffPageText opt : offPageContainer . getTexts ( ) ) { if ( text . equals ( opt . getText ( ) ) ) { if ( opt . getIndex ( ) == 0 ) { offPageContainer . selectDeck ( opt . getIndex ( ) ) ; if ( getSelectedIndex ( ) == PAGE_LIMIT - 1 ) { SelectionEvent . fire ( this , PAGE_LIMIT - 1 ) ; } tabs . lastTab ( ) . setText ( opt . getText ( ) ) ; selectTab ( PAGE_LIMIT - 1 ) ; } else { selectTab ( PAGE_LIMIT - 1 + opt . getIndex ( ) ) ; } } } }
Selects the tab with the specified text . If there s no tab with the specified text the selected tab remains unchanged . If there s more than one tab with the specified text the first one will be selected .
14,199
private void parseResponse ( ModelNode response , AsyncCallback < Map < String , String > > callback ) { Map < String , String > serverValues = new HashMap < String , String > ( ) ; if ( isStandalone ) { serverValues . put ( "Standalone Server" , response . get ( RESULT ) . asString ( ) ) ; } else if ( response . hasDefined ( "server-groups" ) ) { List < Property > groups = response . get ( "server-groups" ) . asPropertyList ( ) ; for ( Property serverGroup : groups ) { List < Property > hosts = serverGroup . getValue ( ) . get ( "host" ) . asPropertyList ( ) ; for ( Property host : hosts ) { List < Property > servers = host . getValue ( ) . asPropertyList ( ) ; for ( Property server : servers ) { serverValues . put ( server . getName ( ) , server . getValue ( ) . get ( "response" ) . get ( "result" ) . asString ( ) ) ; } } } } callback . onSuccess ( serverValues ) ; }
Distinguish domain and standalone response values