idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
14,100 | 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 . | 90 | 5 |
14,101 | public void remove ( List < Value > values ) { Key [ ] keys = makeSubKeys ( values ) ; List < byte [ ] > digestList = getDigestList ( ) ; // int startIndex = digestList.IndexOf (subKey.digest); // int count = values.Count; // foreach (Key key in keys){ // // client.Delete (this.policy, key); // } // client.Operate(this.policy, this.key, ListOperation.Remove(this.binNameString, startIndex, count)); 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 . | 174 | 5 |
14,102 | @ 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 . | 109 | 5 |
14,103 | 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 . | 92 | 6 |
14,104 | 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 . | 59 | 5 |
14,105 | 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 | 118 | 12 |
14,106 | 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 | 94 | 11 |
14,107 | 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 | 138 | 11 |
14,108 | 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 | 99 | 12 |
14,109 | public static MultiPoint of ( Stream < Point > points ) { return of ( points . collect ( Collectors . toList ( ) ) ) ; } | Creates a MultiPoint from the given points . | 31 | 10 |
14,110 | 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 . | 64 | 9 |
14,111 | public List < Point > points ( ) { return positions ( ) . children ( ) . stream ( ) . map ( Point :: new ) . collect ( Collectors . toList ( ) ) ; } | Returns the points composing this Geometry . | 41 | 8 |
14,112 | 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 . | 34 | 8 |
14,113 | public void fireEvent ( final Event < ? > event ) { Scheduler . get ( ) . scheduleDeferred ( new Scheduler . ScheduledCommand ( ) { @ Override public void execute ( ) { bus . fireEventFromSource ( event , dialog . getInterfaceModel ( ) . getId ( ) ) ; } } ) ; } | Event delegation . Uses the dialog ID as source . | 71 | 10 |
14,114 | @ Override 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 ) { // TODO: This isn't optimal (creation of new resource with every comparison) 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 ) ) ) // guarded { 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 . | 291 | 8 |
14,115 | public void onSaveDatasource ( AddressTemplate template , final String dsName , final Map changeset ) { dataSourceStore . saveDatasource ( template , dsName , changeset , new SimpleCallback < ResponseWrapper < Boolean > > ( ) { @ Override 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 | 165 | 26 |
14,116 | @ Override public void onCreateProperty ( String reference , PropertyRecord prop ) { presenter . onCreateXAProperty ( reference , prop ) ; } | property management below | 31 | 3 |
14,117 | 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 . | 52 | 10 |
14,118 | 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 . | 52 | 10 |
14,119 | 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 . | 70 | 10 |
14,120 | 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 ) // only verify parents if necessary { 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 . | 210 | 31 |
14,121 | 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 ) ; // set value, including type conversion 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 . | 324 | 12 |
14,122 | 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 . | 71 | 20 |
14,123 | 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 . | 83 | 27 |
14,124 | 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 . | 77 | 28 |
14,125 | public void navigateHandlerView ( ) { // if endpoint tab if ( tabLayoutpanel . getSelectedIndex ( ) == 1 ) { if ( endpointHandlerPages . getPage ( ) == 0 ) endpointHandlerPages . showPage ( 1 ) ; // else the client tab } else if ( tabLayoutpanel . getSelectedIndex ( ) == 2 ) { if ( clientHandlerPages . getPage ( ) == 0 ) clientHandlerPages . showPage ( 1 ) ; } } | to show a specific panel accordingly to the selected tab | 99 | 10 |
14,126 | @ 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 . | 114 | 19 |
14,127 | private void pushState ( final S state ) { this . state = state ; header . setHTML ( TEMPLATE . header ( currentStep ( ) . getTitle ( ) ) ) ; clearError ( ) ; body . showWidget ( state ) ; // will call onShow(C) for the current step 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 . | 128 | 19 |
14,128 | 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 . | 120 | 20 |
14,129 | public void onSaveFilter ( AddressTemplate address , String name , Map changeset ) { operationDelegate . onSaveResource ( address , name , changeset , defaultSaveOpCallbacks ) ; } | Save an existent filter . | 41 | 6 |
14,130 | 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 . | 246 | 18 |
14,131 | public < T extends Mapping > T getMapping ( MappingType type ) { return ( T ) mappings . get ( type ) ; } | Get a mapping local to this unit . | 31 | 8 |
14,132 | 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 . | 40 | 23 |
14,133 | 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 | 187 | 6 |
14,134 | 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 ' ' : builder . append ( "\\b" ) ; break ; case ' ' : builder . append ( "\\f" ) ; break ; case ' ' : builder . append ( "\\n" ) ; break ; case ' ' : builder . append ( "\\r" ) ; break ; case ' ' : builder . append ( "\\t" ) ; break ; case ' ' : builder . append ( "\\/" ) ; break ; default : if ( ( cp >= ' ' && cp <= ' ' ) || ( cp >= ' ' && cp <= ' ' ) || ( cp >= ' ' && cp <= ' ' ) ) { final String hexString = Integer . toHexString ( cp ) ; builder . append ( "\\u" ) ; for ( int k = 0 ; k < 4 - hexString . length ( ) ; k ++ ) { builder . append ( ' ' ) ; } builder . append ( hexString . toUpperCase ( ) ) ; } else { builder . append ( cp ) ; } break ; } } builder . append ( ' ' ) ; return builder . toString ( ) ; } | Escapes the original string for inclusion in a JSON string . | 357 | 12 |
14,135 | 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 . | 43 | 10 |
14,136 | public < T > void set ( String key , T value ) { data . put ( key , value ) ; } | Stores the value under the given key in the context map . | 24 | 13 |
14,137 | 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 . | 55 | 32 |
14,138 | @ SuppressWarnings ( "unchecked" ) public void series ( final Outcome outcome , final Function ... functions ) { _series ( null , outcome , functions ) ; // generic signature problem, hence null } | 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 . | 45 | 49 |
14,139 | @ SafeVarargs 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 . | 41 | 42 |
14,140 | @ 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 ( ) { @ Override public boolean execute ( ) { if ( ctrl . isAborted ( ) || ctrl . allFinished ( ) ) { // schedule deferred so that 'return false' executes first! Scheduler . get ( ) . scheduleDeferred ( new Scheduler . ScheduledCommand ( ) { @ Override @ SuppressWarnings ( "unchecked" ) public void execute ( ) { if ( ctrl . isAborted ( ) ) { progress . finish ( ) ; outcome . onFailure ( finalContext ) ; } else { progress . finish ( ) ; outcome . onSuccess ( finalContext ) ; } } } ) ; return false ; } else { // one after the other until all are active 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 . | 269 | 39 |
14,141 | 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 . | 31 | 20 |
14,142 | 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 . | 146 | 16 |
14,143 | 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 . | 183 | 16 |
14,144 | 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 . | 91 | 16 |
14,145 | 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 | 49 | 12 |
14,146 | 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 | 87 | 4 |
14,147 | 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 . | 47 | 53 |
14,148 | 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 . | 56 | 11 |
14,149 | 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 . | 55 | 10 |
14,150 | 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 > ( ) { @ Override public void onFailure ( Throwable caught ) { for ( Callback cb : callback ) { cb . onFailure ( addressTemplate , name , caught ) ; } } @ Override 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 . | 259 | 13 |
14,151 | 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 > ( ) { @ Override public void onFailure ( Throwable caught ) { for ( Callback cb : callback ) { cb . onFailure ( addressTemplate , name , caught ) ; } } @ Override 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 . | 303 | 14 |
14,152 | 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 | 52 | 16 |
14,153 | public void setWidgetMinSize ( Widget child , int minSize ) { assertIsChild ( child ) ; Splitter splitter = getAssociatedSplitter ( child ) ; // The splitter is null for the center element. if ( splitter != null ) { splitter . setMinSize ( minSize ) ; } } | Sets the minimum allowable size for the given widget . | 68 | 11 |
14,154 | public void setWidgetToggleDisplayAllowed ( Widget child , boolean allowed ) { assertIsChild ( child ) ; Splitter splitter = getAssociatedSplitter ( child ) ; // The splitter is null for the center element. if ( splitter != null ) { splitter . setToggleDisplayAllowed ( allowed ) ; } } | Sets whether or not double - clicking on the splitter should toggle the display of the widget . | 72 | 20 |
14,155 | 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 ) ; //ChildInformation childInfo = findChildInfo(treeItem); if ( path . size ( ) % 2 == 0 ) { /*String denominatorType = AddressUtils.getDenominatorType(address.asPropertyList()); boolean isSingleton = denominatorType!=null ? childInfo.isSingleton(denominatorType) : false; // false==root*/ // addressable resources presenter . readResource ( address , isPlaceHolder ) ; toggleEditor ( true ) ; filter . setEnabled ( true ) ; } else { toggleEditor ( false ) ; // display tweaks displayAddress . add ( path . getLast ( ) , WILDCARD ) ; // force loading of children upon selection loadChildren ( ( ModelTreeItem ) treeItem , false ) ; filter . setEnabled ( false ) ; } nodeHeader . updateDescription ( displayAddress ) ; } | When a tree item is clicked we load the resource . | 276 | 11 |
14,156 | public void updateRootTypes ( ModelNode address , List < ModelNode > modelNodes ) { deck . showWidget ( CHILD_VIEW ) ; tree . clear ( ) ; descView . clearDisplay ( ) ; formView . clearDisplay ( ) ; offsetDisplay . clear ( ) ; // IMPORTANT: when pin down is active, we need to consider the offset to calculate the real address 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'> " + parentName + " <i class='icon-remove'></i></div>" ) ; parentTag . addClickHandler ( new ClickHandler ( ) { @ Override 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 . | 461 | 13 |
14,157 | public void updateChildrenTypes ( ModelNode address , List < ModelNode > modelNodes ) { TreeItem rootItem = findTreeItem ( tree , address ) ; addChildrenTypes ( ( ModelTreeItem ) rootItem , modelNodes ) ; } | Update sub parts of the tree | 52 | 6 |
14,158 | 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 ) ; // on this level they can't inherit from anyone 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 | 182 | 13 |
14,159 | public AuthorisationDecision getReadPriviledge ( ) { return checkPriviledge ( new Priviledge ( ) { @ Override 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 | 88 | 14 |
14,160 | 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 ) ) { // in some cases the server returns the wrong model type for numeric values // i.e the description affords a ModelType.LONG, but a ModelType.INTEGER is returned try { target . set ( ( Long ) propValue ) ; } catch ( Throwable e ) { // ClassCastException target . set ( Integer . valueOf ( ( Integer ) propValue ) ) ; } } else if ( type . equals ( ModelType . BIG_DECIMAL ) ) { // in some cases the server returns the wrong model type for numeric values // i.e the description affords a ModelType.LONG, but a ModelType.INTEGER is returned try { target . set ( ( BigDecimal ) propValue ) ; } catch ( Throwable e ) { // ClassCastException 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 | 409 | 10 |
14,161 | 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 | 140 | 10 |
14,162 | 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 > ( ) { @ Override public void onFailure ( ResourceData context ) { Console . error ( "Failed to load metadata for " + address . asString ( ) ) ; } @ Override 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 | 207 | 8 |
14,163 | 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 ( ) { @ Override public void onConfirmation ( boolean isConfirmed ) { if ( isConfirmed ) { dispatcher . execute ( new DMRAction ( operation ) , new SimpleCallback < DMRResponse > ( ) { @ Override 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 | 278 | 4 |
14,164 | public void onPrepareAddChildResource ( final ModelNode address , final boolean isSingleton ) { _loadMetaData ( address , new ResourceData ( true ) , new Outcome < ResourceData > ( ) { @ Override public void onFailure ( ResourceData context ) { Console . error ( "Failed to load metadata for " + address . asString ( ) ) ; } @ Override public void onSuccess ( ResourceData context ) { if ( isSingleton && context . description . get ( ATTRIBUTES ) . asList ( ) . isEmpty ( ) && context . description . get ( OPERATIONS ) . get ( ADD ) . get ( REQUEST_PROPERTIES ) . asList ( ) . isEmpty ( ) ) { // no attributes need to be assigned -> skip the next step onAddChildResource ( address , new ModelNode ( ) ) ; } else { view . showAddDialog ( address , isSingleton , context . securityContext , context . description ) ; } } } ) ; } | Add a child resource | 216 | 4 |
14,165 | 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 | 114 | 17 |
14,166 | public Map < String , Integer > getRequiredStatements ( ) { Map < String , Integer > required = new HashMap < String , Integer > ( ) ; for ( Token token : address ) { if ( ! token . hasKey ( ) ) { // a single token or token expression // These are currently skipped: See asResource() parsing logic continue ; } else { // a value expression. key and value of the expression might be resolved // TODO: keys are not supported: Do we actually need that? 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 . | 217 | 18 |
14,167 | private HttpURLConnection getURLConnection ( String str ) throws MalformedURLException { try { if ( isHttps ) { /* when communicating with the server which has unsigned or invalid * certificate (https), SSLException or IOException is thrown. * the following line is a hack to avoid that */ 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 this header has not been set by a request set the user agent. if ( headers == null || ( headers != null && headers . get ( "user-agent" ) == null ) ) { // set user agent to mimic a common browser 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 | 425 | 7 |
14,168 | public InputStream getInputStream ( ) { try { int responseCode = this . urlConnection . getResponseCode ( ) ; try { // HACK: manually follow redirects, for the login to work // HTTPUrlConnection auto redirect doesn't respect the provided headers 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 | 221 | 8 |
14,169 | 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 . | 152 | 12 |
14,170 | 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 . | 39 | 30 |
14,171 | public void setState ( State state ) { this . state = state ; setText ( state . isPrimary ( ) ? text1 : text2 ) ; } | Changes the state without executing the command . | 33 | 8 |
14,172 | public String getNormalizedLocalPart ( ) { int i = localPart . indexOf ( "#" ) ; if ( i != - 1 ) return localPart . substring ( 0 , i ) ; else return localPart ; } | return the local part without suffix | 48 | 6 |
14,173 | private boolean createChild ( Property sibling , String parentURI ) { boolean skipped = sibling . getName ( ) . equals ( "children" ) ; if ( ! skipped ) { //dump(sibling); 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 | 294 | 3 |
14,174 | @ Override public void selectTab ( final String text ) { for ( int i = 0 ; i < tabs . size ( ) ; i ++ ) { if ( text . equals ( tabs . get ( i ) . getText ( ) ) ) { selectTab ( i ) ; return ; } } // not found in visible tabs, should be in off-page for ( OffPageText opt : offPageContainer . getTexts ( ) ) { if ( text . equals ( opt . getText ( ) ) ) { if ( opt . getIndex ( ) == 0 ) { // the first off-page needs special treatment 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 . | 236 | 42 |
14,175 | private void parseResponse ( ModelNode response , AsyncCallback < Map < String , String > > callback ) { //System.out.println(response.toString()); 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 | 254 | 8 |
14,176 | public void add ( Widget w , String tabText , boolean asHTML ) { insert ( w , tabText , asHTML , getWidgetCount ( ) ) ; } | Adds a widget to the tab panel . If the Widget is already attached to the TabPanel it will be moved to the right - most index . | 35 | 30 |
14,177 | public static < T extends MPBase > T manage ( Topic topic , String id ) throws MPException { if ( topic == null || id == null ) { throw new MPException ( "Topic and Id can not be null in the IPN request" ) ; } T resourceObject = null ; Class clazz = null ; Method method = null ; try { clazz = Class . forName ( topic . getResourceClassName ( ) ) ; if ( ! MPBase . class . isAssignableFrom ( clazz ) ) { throw new MPException ( topic . toString ( ) + " does not extend from MPBase" ) ; } method = clazz . getMethod ( "findById" , String . class ) ; resourceObject = ( T ) method . invoke ( null , id ) ; } catch ( Exception ex ) { throw new MPException ( ex ) ; } return resourceObject ; } | It manages an IPN and returns a resource | 187 | 9 |
14,178 | public < T extends MPBase > T getByIndex ( int index ) { T resource = ( T ) _resourceArray . get ( index ) ; return resource ; } | It returns one resource using its index in the array | 35 | 10 |
14,179 | public < T extends MPBase > T getById ( String id ) throws MPException { T resource = null ; for ( int i = 0 ; i < _resourceArray . size ( ) ; i ++ ) { resource = getByIndex ( i ) ; try { Field field = resource . getClass ( ) . getDeclaredField ( "id" ) ; field . setAccessible ( true ) ; String resourceId = field . get ( resource ) . toString ( ) ; if ( resourceId . equals ( id ) ) { break ; } } catch ( Exception exception ) { throw new MPException ( exception ) ; } } return resource ; } | It returns one resource of the array using the id | 135 | 10 |
14,180 | protected < T extends MPBase > T processMethod ( String methodName , Boolean useCache ) throws MPException { HashMap < String , String > mapParams = null ; T resource = processMethod ( this . getClass ( ) , ( T ) this , methodName , mapParams , useCache ) ; fillResource ( resource , this ) ; return ( T ) this ; } | Process the method to call the api usually used for create update and delete methods | 80 | 15 |
14,181 | protected static < T extends MPBase > T processMethod ( Class clazz , String methodName , String param1 , Boolean useCache ) throws MPException { HashMap < String , String > mapParams = new HashMap < String , String > ( ) ; mapParams . put ( "param1" , param1 ) ; return processMethod ( clazz , null , methodName , mapParams , useCache ) ; } | Process the method to call the api usually used for load methods | 90 | 12 |
14,182 | private static MPApiResponse callApi ( HttpMethod httpMethod , String path , PayloadType payloadType , JsonObject payload , Collection < Header > colHeaders , int retries , int connectionTimeout , int socketTimeout , Boolean useCache ) throws MPException { String cacheKey = httpMethod . toString ( ) + "_" + path ; MPApiResponse response = null ; if ( useCache ) { response = MPCache . getFromCache ( cacheKey ) ; } if ( response == null ) { response = new MPRestClient ( ) . executeRequest ( httpMethod , path , payloadType , payload , colHeaders , retries , connectionTimeout , socketTimeout ) ; if ( useCache ) { MPCache . addToCache ( cacheKey , response ) ; } else { MPCache . removeFromCache ( cacheKey ) ; } } return response ; } | Calls the api and returns an MPApiResponse . | 186 | 12 |
14,183 | protected static < T extends MPBase > T fillResourceWithResponseData ( T resource , MPApiResponse response ) throws MPException { if ( response . getJsonElementResponse ( ) != null && response . getJsonElementResponse ( ) . isJsonObject ( ) ) { JsonObject jsonObject = ( JsonObject ) response . getJsonElementResponse ( ) ; T resourceObject = MPCoreUtils . getResourceFromJson ( resource . getClass ( ) , jsonObject ) ; resource = fillResource ( resourceObject , resource ) ; resource . _lastKnownJson = MPCoreUtils . getJsonFromResource ( resource ) ; } return resource ; } | It fills all the attributes members of the Resource obj . Used when a Get or a Put request is called | 145 | 21 |
14,184 | protected static < T extends MPBase > ArrayList < T > fillArrayWithResponseData ( Class clazz , MPApiResponse response ) throws MPException { ArrayList < T > resourceArray = new ArrayList < T > ( ) ; if ( response . getJsonElementResponse ( ) != null ) { JsonArray jsonArray = MPCoreUtils . getArrayFromJsonElement ( response . getJsonElementResponse ( ) ) ; if ( jsonArray != null ) { for ( int i = 0 ; i < jsonArray . size ( ) ; i ++ ) { T resource = MPCoreUtils . getResourceFromJson ( clazz , ( JsonObject ) jsonArray . get ( i ) ) ; resource . _lastKnownJson = MPCoreUtils . getJsonFromResource ( resource ) ; resourceArray . add ( resource ) ; } } } return resourceArray ; } | It fills an array with the resource objects from the api response | 191 | 12 |
14,185 | private static < T extends MPBase > T fillResource ( T sourceResource , T destinationResource ) throws MPException { Field [ ] declaredFields = destinationResource . getClass ( ) . getDeclaredFields ( ) ; for ( Field field : declaredFields ) { try { Field originField = sourceResource . getClass ( ) . getDeclaredField ( field . getName ( ) ) ; field . setAccessible ( true ) ; originField . setAccessible ( true ) ; field . set ( destinationResource , originField . get ( sourceResource ) ) ; } catch ( Exception ex ) { throw new MPException ( ex ) ; } } return destinationResource ; } | Copies the atributes from an obj to a destination obj | 142 | 12 |
14,186 | private static < T extends MPBase > T cleanResource ( T resource ) throws MPException { Field [ ] declaredFields = resource . getClass ( ) . getDeclaredFields ( ) ; for ( Field field : declaredFields ) { try { field . setAccessible ( true ) ; field . set ( resource , null ) ; } catch ( Exception ex ) { throw new MPException ( ex ) ; } } return resource ; } | Removes all data from the attributes members of the Resource obj . Used when a delete request is called | 92 | 20 |
14,187 | private static Collection < Header > getStandardHeaders ( ) { Collection < Header > colHeaders = new Vector < Header > ( ) ; colHeaders . add ( new BasicHeader ( HTTP . CONTENT_TYPE , "application/json" ) ) ; colHeaders . add ( new BasicHeader ( HTTP . USER_AGENT , "MercadoPago Java SDK/1.0.10" ) ) ; colHeaders . add ( new BasicHeader ( "x-product-id" , "BC32A7VTRPP001U8NHJ0" ) ) ; return colHeaders ; } | Returns standard headers for all the requests | 131 | 7 |
14,188 | private static < T extends MPBase > JsonObject generatePayload ( HttpMethod httpMethod , T resource ) { JsonObject payload = null ; if ( httpMethod . equals ( HttpMethod . POST ) || ( httpMethod . equals ( HttpMethod . PUT ) && resource . _lastKnownJson == null ) ) { payload = MPCoreUtils . getJsonFromResource ( resource ) ; } else if ( httpMethod . equals ( HttpMethod . PUT ) ) { JsonObject actualJson = MPCoreUtils . getJsonFromResource ( resource ) ; Type mapType = new TypeToken < Map < String , Object > > ( ) { } . getType ( ) ; Gson gson = new Gson ( ) ; Map < String , Object > oldMap = gson . fromJson ( resource . _lastKnownJson , mapType ) ; Map < String , Object > newMap = gson . fromJson ( actualJson , mapType ) ; MapDifference < String , Object > mapDifferences = Maps . difference ( oldMap , newMap ) ; payload = new JsonObject ( ) ; for ( Map . Entry < String , MapDifference . ValueDifference < Object > > entry : mapDifferences . entriesDiffering ( ) . entrySet ( ) ) { if ( entry . getValue ( ) . rightValue ( ) instanceof LinkedTreeMap ) { JsonElement jsonObject = gson . toJsonTree ( entry . getValue ( ) . rightValue ( ) ) . getAsJsonObject ( ) ; payload . add ( entry . getKey ( ) , jsonObject ) ; } else { if ( entry . getValue ( ) . rightValue ( ) instanceof Boolean ) { payload . addProperty ( entry . getKey ( ) , ( Boolean ) entry . getValue ( ) . rightValue ( ) ) ; } else if ( entry . getValue ( ) . rightValue ( ) instanceof Number ) { payload . addProperty ( entry . getKey ( ) , ( Number ) entry . getValue ( ) . rightValue ( ) ) ; } else { payload . addProperty ( entry . getKey ( ) , entry . getValue ( ) . rightValue ( ) . toString ( ) ) ; } } } for ( Map . Entry < String , Object > entry : mapDifferences . entriesOnlyOnRight ( ) . entrySet ( ) ) { if ( entry . getValue ( ) instanceof Boolean ) { payload . addProperty ( entry . getKey ( ) , ( Boolean ) entry . getValue ( ) ) ; } else if ( entry . getValue ( ) instanceof Number ) { payload . addProperty ( entry . getKey ( ) , ( Number ) entry . getValue ( ) ) ; } else { payload . addProperty ( entry . getKey ( ) , entry . getValue ( ) . toString ( ) ) ; } } } return payload ; } | Transforms all attributes members of the instance in a JSON String . Only for POST and PUT methods . POST gets the full object in a JSON object . PUT gets only the differences with the last known state of the object . | 626 | 46 |
14,189 | private static HashMap < String , Object > getRestInformation ( AnnotatedElement element ) throws MPException { if ( element . getAnnotations ( ) . length == 0 ) { throw new MPException ( "No rest method found" ) ; } HashMap < String , Object > hashAnnotation = new HashMap < String , Object > ( ) ; for ( Annotation annotation : element . getAnnotations ( ) ) { if ( annotation instanceof DELETE ) { DELETE delete = ( DELETE ) annotation ; if ( StringUtils . isEmpty ( delete . path ( ) ) ) { throw new MPException ( "Path not found for DELETE method" ) ; } hashAnnotation = fillHashAnnotations ( hashAnnotation , HttpMethod . DELETE , delete . path ( ) , null , delete . retries ( ) , delete . connectionTimeout ( ) , delete . socketTimeout ( ) ) ; } else if ( annotation instanceof GET ) { GET get = ( GET ) annotation ; if ( StringUtils . isEmpty ( get . path ( ) ) ) { throw new MPException ( "Path not found for GET method" ) ; } hashAnnotation = fillHashAnnotations ( hashAnnotation , HttpMethod . GET , get . path ( ) , null , get . retries ( ) , get . connectionTimeout ( ) , get . socketTimeout ( ) ) ; } else if ( annotation instanceof POST ) { POST post = ( POST ) annotation ; if ( StringUtils . isEmpty ( post . path ( ) ) ) { throw new MPException ( "Path not found for POST method" ) ; } hashAnnotation = fillHashAnnotations ( hashAnnotation , HttpMethod . POST , post . path ( ) , post . payloadType ( ) , post . retries ( ) , post . connectionTimeout ( ) , post . socketTimeout ( ) ) ; } else if ( annotation instanceof PUT ) { PUT put = ( PUT ) annotation ; if ( StringUtils . isEmpty ( put . path ( ) ) ) { throw new MPException ( "Path not found for PUT method" ) ; } hashAnnotation = fillHashAnnotations ( hashAnnotation , HttpMethod . PUT , put . path ( ) , put . payloadType ( ) , put . retries ( ) , put . connectionTimeout ( ) , put . socketTimeout ( ) ) ; } } return hashAnnotation ; } | Iterates the annotations of the entity method implementation it validates that only one method annotation is used in the entity implementation method . | 520 | 25 |
14,190 | private static AnnotatedElement getAnnotatedMethod ( Class clazz , String methodName ) throws MPException { for ( Method method : clazz . getDeclaredMethods ( ) ) { if ( method . getName ( ) . equals ( methodName ) && method . getDeclaredAnnotations ( ) . length > 0 ) { return method ; } } throw new MPException ( "No annotated method found" ) ; } | Iterates over the methods of a class and returns the one matching the method name passed | 90 | 17 |
14,191 | public static String getAccessToken ( ) throws MPException { if ( StringUtils . isEmpty ( MercadoPago . SDK . getClientId ( ) ) || StringUtils . isEmpty ( MercadoPago . SDK . getClientSecret ( ) ) ) { throw new MPException ( "\"client_id\" and \"client_secret\" can not be \"null\" when getting the \"access_token\"" ) ; } JsonObject jsonPayload = new JsonObject ( ) ; jsonPayload . addProperty ( "grant_type" , "client_credentials" ) ; jsonPayload . addProperty ( "client_id" , MercadoPago . SDK . getClientId ( ) ) ; jsonPayload . addProperty ( "client_secret" , MercadoPago . SDK . getClientSecret ( ) ) ; String access_token = null ; String baseUri = MercadoPago . SDK . getBaseUrl ( ) ; MPApiResponse response = new MPRestClient ( ) . executeRequest ( HttpMethod . POST , baseUri + "/oauth/token" , PayloadType . JSON , jsonPayload , null ) ; if ( response . getStatusCode ( ) == 200 ) { JsonElement jsonElement = response . getJsonElementResponse ( ) ; if ( jsonElement . isJsonObject ( ) ) { access_token = ( ( JsonObject ) jsonElement ) . get ( "access_token" ) . getAsString ( ) ; } } else { throw new MPException ( "Can not retrieve the \"access_token\"" ) ; } return access_token ; } | Call the oauth api to get an access token | 355 | 10 |
14,192 | private void parseRequest ( HttpMethod httpMethod , HttpRequestBase request , JsonObject payload ) throws MPException { this . method = httpMethod . toString ( ) ; this . url = request . getURI ( ) . toString ( ) ; if ( payload != null ) { this . payload = payload . toString ( ) ; } } | Parses the http request in a custom MPApiResponse object . | 74 | 15 |
14,193 | private void parseResponse ( HttpResponse response ) throws MPException { this . statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; this . reasonPhrase = response . getStatusLine ( ) . getReasonPhrase ( ) ; if ( response . getEntity ( ) != null ) { HttpEntity respEntity = response . getEntity ( ) ; try { this . stringResponse = MPCoreUtils . inputStreamToString ( respEntity . getContent ( ) ) ; } catch ( Exception ex ) { throw new MPException ( ex ) ; } // Try to parse the response to a json, and a extract the entity of the response. // When the response is not a json parseable string then the string response must be used. try { this . jsonElementResponse = new JsonParser ( ) . parse ( this . stringResponse ) ; } catch ( JsonParseException jsonParseException ) { // Do nothing } } } | Parses the http response in a custom MPApiResponse object . | 202 | 15 |
14,194 | public static < T extends MPBase > boolean validate ( T objectToValidate ) throws MPValidationException { Collection < ValidationViolation > colViolations = validate ( new Vector < ValidationViolation > ( ) , objectToValidate ) ; if ( ! colViolations . isEmpty ( ) ) { throw new MPValidationException ( colViolations ) ; } return true ; } | Evaluates every field of an obj using Validation annotations | 83 | 12 |
14,195 | static Field [ ] getAllFields ( Class < ? > type ) { List < Field > fields = new ArrayList < Field > ( ) ; for ( Class < ? > clazz = type ; clazz != null ; clazz = clazz . getSuperclass ( ) ) { if ( clazz == MPBase . class || clazz == Object . class ) { break ; } fields . addAll ( Arrays . asList ( clazz . getDeclaredFields ( ) ) ) ; } Field [ ] fieldsArray = new Field [ fields . size ( ) ] ; return fields . toArray ( fieldsArray ) ; } | Retrieves all fields from a class except the ones from MPBase abstract class and Object class | 133 | 19 |
14,196 | public static < T extends MPBase > JsonObject getJsonFromResource ( T resourceObject ) { return ( JsonObject ) gson . toJsonTree ( resourceObject ) ; } | Static method that transforms all attributes members of the instance in a JSON Object . | 41 | 15 |
14,197 | public static < T > T getResourceFromJson ( Class clazz , JsonObject jsonEntity ) { return ( T ) gson . fromJson ( jsonEntity , clazz ) ; } | Static method that transforms a Json Object in a MP Resource . | 42 | 13 |
14,198 | public static String inputStreamToString ( InputStream is ) throws MPException { String value = "" ; if ( is != null ) { try { ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ 1024 ] ; int length ; while ( ( length = is . read ( buffer ) ) != - 1 ) { result . write ( buffer , 0 , length ) ; } value = result . toString ( "UTF-8" ) ; } catch ( Exception ex ) { throw new com . mercadopago . exceptions . MPException ( ex ) ; } } return value ; } | Static method that transform an Input Stream to a String object returns an empty string if InputStream is null . | 131 | 21 |
14,199 | public static boolean validateUrl ( String url ) { String [ ] schemes = { "https" } ; UrlValidator urlValidator = new UrlValidator ( schemes ) ; return urlValidator . isValid ( url ) ; } | Validates if an url is a valid url address | 50 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.