idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
33,900
public T watch ( DeterministicKey accountKey ) { checkState ( accountPath == null , "either watch or accountPath" ) ; this . watchingKey = accountKey ; this . isFollowing = false ; return self ( ) ; }
Creates a key chain that watches the given account key .
33,901
public T watchAndFollow ( DeterministicKey accountKey ) { checkState ( accountPath == null , "either watchAndFollow or accountPath" ) ; this . watchingKey = accountKey ; this . isFollowing = true ; return self ( ) ; }
Creates a deterministic key chain with the given watch key and that follows some other keychain . In a married wallet following keychain represents spouse . Watch key has to be an account key .
33,902
public T spend ( DeterministicKey accountKey ) { checkState ( accountPath == null , "either spend or accountPath" ) ; this . spendingKey = accountKey ; this . isFollowing = false ; return self ( ) ; }
Creates a key chain that can spend from the given account key .
33,903
public static boolean isSentToCltvPaymentChannel ( Script script ) { List < ScriptChunk > chunks = script . chunks ; if ( chunks . size ( ) != 10 ) return false ; if ( ! chunks . get ( 0 ) . equalsOpCode ( OP_IF ) ) return false ; if ( ! chunks . get ( 2 ) . equalsOpCode ( OP_CHECKSIGVERIFY ) ) return false ; if ( ! chunks . get ( 3 ) . equalsOpCode ( OP_ELSE ) ) return false ; if ( ! chunks . get ( 5 ) . equalsOpCode ( OP_CHECKLOCKTIMEVERIFY ) ) return false ; if ( ! chunks . get ( 6 ) . equalsOpCode ( OP_DROP ) ) return false ; if ( ! chunks . get ( 7 ) . equalsOpCode ( OP_ENDIF ) ) return false ; if ( ! chunks . get ( 9 ) . equalsOpCode ( OP_CHECKSIG ) ) return false ; return true ; }
Returns whether this script matches the format used for LOCKTIMEVERIFY transactions .
33,904
public static boolean isOpReturn ( Script script ) { List < ScriptChunk > chunks = script . chunks ; return chunks . size ( ) > 0 && chunks . get ( 0 ) . equalsOpCode ( ScriptOpCodes . OP_RETURN ) ; }
Returns whether this script is using OP_RETURN to store arbitrary data .
33,905
public byte [ ] toASN1 ( ) { try { byte [ ] privKeyBytes = getPrivKeyBytes ( ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( 400 ) ; DERSequenceGenerator seq = new DERSequenceGenerator ( baos ) ; seq . addObject ( new ASN1Integer ( 1 ) ) ; seq . addObject ( new DEROctetString ( privKeyBytes ) ) ; seq . addObject ( new DERTaggedObject ( 0 , CURVE_PARAMS . toASN1Primitive ( ) ) ) ; seq . addObject ( new DERTaggedObject ( 1 , new DERBitString ( getPubKey ( ) ) ) ) ; seq . close ( ) ; return baos . toByteArray ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Output this ECKey as an ASN . 1 encoded private key as understood by OpenSSL or used by Bitcoin Core in its wallet storage format .
33,906
public byte findRecoveryId ( Sha256Hash hash , ECDSASignature sig ) { byte recId = - 1 ; for ( byte i = 0 ; i < 4 ; i ++ ) { ECKey k = ECKey . recoverFromSignature ( i , sig , hash , isCompressed ( ) ) ; if ( k != null && k . pub . equals ( pub ) ) { recId = i ; break ; } } if ( recId == - 1 ) throw new RuntimeException ( "Could not construct a recoverable key. This should never happen." ) ; return recId ; }
Returns the recovery ID a byte with value between 0 and 3 inclusive that specifies which of 4 possible curve points was used to sign a message . This value is also referred to as v .
33,907
public ECKey encrypt ( KeyCrypter keyCrypter , KeyParameter aesKey ) throws KeyCrypterException { checkNotNull ( keyCrypter ) ; final byte [ ] privKeyBytes = getPrivKeyBytes ( ) ; EncryptedData encryptedPrivateKey = keyCrypter . encrypt ( privKeyBytes , aesKey ) ; ECKey result = ECKey . fromEncrypted ( encryptedPrivateKey , keyCrypter , getPubKey ( ) ) ; result . setCreationTimeSeconds ( creationTimeSeconds ) ; return result ; }
Create an encrypted private key with the keyCrypter and the AES key supplied . This method returns a new encrypted key and leaves the original unchanged .
33,908
public ECKey decrypt ( KeyCrypter keyCrypter , KeyParameter aesKey ) throws KeyCrypterException { checkNotNull ( keyCrypter ) ; if ( this . keyCrypter != null && ! this . keyCrypter . equals ( keyCrypter ) ) throw new KeyCrypterException ( "The keyCrypter being used to decrypt the key is different to the one that was used to encrypt it" ) ; checkState ( encryptedPrivateKey != null , "This key is not encrypted" ) ; byte [ ] unencryptedPrivateKey = keyCrypter . decrypt ( encryptedPrivateKey , aesKey ) ; if ( unencryptedPrivateKey . length != 32 ) throw new KeyCrypterException . InvalidCipherText ( "Decrypted key must be 32 bytes long, but is " + unencryptedPrivateKey . length ) ; ECKey key = ECKey . fromPrivate ( unencryptedPrivateKey ) ; if ( ! isCompressed ( ) ) key = key . decompress ( ) ; if ( ! Arrays . equals ( key . getPubKey ( ) , getPubKey ( ) ) ) throw new KeyCrypterException ( "Provided AES key is wrong" ) ; key . setCreationTimeSeconds ( creationTimeSeconds ) ; return key ; }
Create a decrypted private key with the keyCrypter and AES key supplied . Note that if the aesKey is wrong this has some chance of throwing KeyCrypterException due to the corrupted padding that will result but it can also just yield a garbage key .
33,909
public ECKey decrypt ( KeyParameter aesKey ) throws KeyCrypterException { final KeyCrypter crypter = getKeyCrypter ( ) ; if ( crypter == null ) throw new KeyCrypterException ( "No key crypter available" ) ; return decrypt ( crypter , aesKey ) ; }
Create a decrypted private key with AES key . Note that if the AES key is wrong this has some chance of throwing KeyCrypterException due to the corrupted padding that will result but it can also just yield a garbage key .
33,910
private static void logScrape ( ObjectName mbeanName , Set < String > names , String msg ) { logScrape ( mbeanName + "_" + names , msg ) ; }
For debugging .
33,911
static String safeName ( String name ) { if ( name == null ) { return null ; } boolean prevCharIsUnderscore = false ; StringBuilder safeNameBuilder = new StringBuilder ( name . length ( ) ) ; if ( ! name . isEmpty ( ) && Character . isDigit ( name . charAt ( 0 ) ) ) { safeNameBuilder . append ( "_" ) ; } for ( char nameChar : name . toCharArray ( ) ) { boolean isUnsafeChar = ! JmxCollector . isLegalCharacter ( nameChar ) ; if ( ( isUnsafeChar || nameChar == '_' ) ) { if ( prevCharIsUnderscore ) { continue ; } else { safeNameBuilder . append ( "_" ) ; prevCharIsUnderscore = true ; } } else { safeNameBuilder . append ( nameChar ) ; prevCharIsUnderscore = false ; } } return safeNameBuilder . toString ( ) ; }
Change invalid chars to underscore and merge underscores .
33,912
public EventResultDisruptor waitForBlocking ( ) { SequenceBarrier barrier = ringBuffer . newBarrier ( ) ; try { long a = barrier . waitFor ( waitAtSequence ) ; if ( ringBuffer != null ) return ringBuffer . get ( a ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { barrier . alert ( ) ; } return null ; }
not really block the waiting time is longer than not block .
33,913
public int doStartTag ( ) throws JspException { String pageUrl = calculateURL ( ) ; StringBuilder url = new StringBuilder ( pageUrl ) ; if ( pageUrl . indexOf ( "?" ) < 0 ) url . append ( "?" ) ; else url . append ( "&" ) ; ModelListForm form = null ; try { form = ( ModelListForm ) FormBeanUtil . lookupActionForm ( ( HttpServletRequest ) pageContext . getRequest ( ) , actionFormName ) ; if ( form == null ) throw new Exception ( ) ; } catch ( Exception e ) { Debug . logError ( "[JdonFramework]not found actionFormName value: " + actionFormName , module ) ; throw new JspException ( " not found " + actionFormName ) ; } int start = form . getStart ( ) ; int allCount = form . getAllCount ( ) ; int count = form . getCount ( ) ; url . append ( "count=" ) . append ( count ) ; String nextPage = "" ; if ( ( allCount > ( start + count ) ) ) nextPage = NEXTPAGE ; pageContext . setAttribute ( URLNAME , url . toString ( ) ) ; pageContext . setAttribute ( START , Integer . toString ( start ) ) ; pageContext . setAttribute ( COUNT , Integer . toString ( count ) ) ; pageContext . setAttribute ( ALLCOUNT , Integer . toString ( allCount ) ) ; pageContext . setAttribute ( NEXTPAGE , nextPage ) ; int currentPage = 1 ; if ( count > 0 ) { currentPage = ( start / count ) + 1 ; } if ( ( currentPage == 1 ) && ( nextPage . length ( ) == 0 ) ) { pageContext . setAttribute ( DISP , "off" ) ; } else pageContext . setAttribute ( DISP , "on" ) ; return ( EVAL_BODY_INCLUDE ) ; }
Render the beginning of the hyperlink .
33,914
public EJBLocalHome getLocalHome ( String jndiHomeName ) throws ServiceLocatorException { EJBLocalHome home = null ; try { home = ( EJBLocalHome ) ic . lookup ( jndiHomeName ) ; } catch ( NamingException ne ) { throw new ServiceLocatorException ( ne ) ; } catch ( Exception e ) { throw new ServiceLocatorException ( e ) ; } return home ; }
will get the ejb Local home factory . clients need to cast to the type of EJBHome they desire
33,915
public EJBHome getRemoteHome ( String jndiHomeName , Class className ) throws ServiceLocatorException { EJBHome home = null ; try { Object objref = ic . lookup ( jndiHomeName ) ; Object obj = PortableRemoteObject . narrow ( objref , className ) ; home = ( EJBHome ) obj ; } catch ( NamingException ne ) { throw new ServiceLocatorException ( ne ) ; } catch ( Exception e ) { throw new ServiceLocatorException ( e ) ; } return home ; }
will get the ejb Remote home factory . clients need to cast to the type of EJBHome they desire
33,916
public Disruptor createDisruptor ( String topic ) { TreeSet handlers = getHandles ( topic ) ; if ( handlers == null ) return null ; Disruptor dw = createDw ( topic ) ; Disruptor disruptor = addEventMessageHandler ( dw , topic , handlers ) ; if ( disruptor == null ) return null ; disruptor . start ( ) ; return disruptor ; }
one topic one EventDisruptor
33,917
public static ActionForm lookupActionForm ( HttpServletRequest request , String formName ) { ActionForm actionForm = null ; actionForm = ( ActionForm ) request . getAttribute ( formName ) ; if ( actionForm == null && request . getSession ( false ) != null ) { HttpSession session = request . getSession ( false ) ; actionForm = ( ActionForm ) session . getAttribute ( formName ) ; } return actionForm ; }
lookup ActionForm in
33,918
public synchronized void prepareAppRoot ( String configureFileName ) throws Exception { if ( ! cb . isKernelStartup ( ) ) { cb . registerAppRoot ( configureFileName ) ; logger . info ( configureFileName + " is ready." ) ; } }
prepare the applicaition configure files
33,919
public Object getInstance ( ComponentAdapter componentAdapter ) { Object componentKey = componentAdapter . getComponentKey ( ) ; Object instance = compKeyInstances . get ( componentKey ) ; if ( instance == null ) { instance = loadSaveInstance ( componentAdapter , componentKey ) ; } return instance ; }
modify this method of old DefaultPicocontainer
33,920
public Object querySingleObject ( Collection queryParams , String sqlquery ) throws Exception { Debug . logVerbose ( "[JdonFramework] , module ) ; Connection c = null ; PreparedStatement ps = null ; ResultSet rs = null ; Object o = null ; try { c = dataSource . getConnection ( ) ; ps = c . prepareStatement ( sqlquery , ResultSet . TYPE_SCROLL_INSENSITIVE , ResultSet . CONCUR_READ_ONLY ) ; Debug . logVerbose ( sqlquery , module ) ; jdbcUtil . setQueryParams ( queryParams , ps ) ; rs = ps . executeQuery ( ) ; if ( rs . first ( ) ) { o = rs . getObject ( 1 ) ; Debug . logVerbose ( "[JdonFramework] + o . getClass ( ) . getName ( ) , module ) ; } } catch ( SQLException se ) { throw new SQLException ( "SQLException: " + se . getMessage ( ) ) ; } catch ( Exception ex ) { Debug . logError ( ex , module ) ; throw new Exception ( ex ) ; } finally { if ( rs != null ) try { rs . close ( ) ; } catch ( SQLException quiet ) { } if ( ps != null ) try { ps . close ( ) ; } catch ( SQLException quiet ) { } if ( c != null ) try { c . close ( ) ; } catch ( SQLException quiet ) { } } return o ; }
get a single object from database
33,921
public void init ( FilterConfig filterConfig ) throws ServletException { this . filterConfig = filterConfig ; this . encoding = filterConfig . getInitParameter ( "encoding" ) ; String value = filterConfig . getInitParameter ( "ignore" ) ; if ( value == null ) this . ignore = true ; else if ( value . equalsIgnoreCase ( "true" ) ) this . ignore = true ; else if ( value . equalsIgnoreCase ( "yes" ) ) this . ignore = true ; else this . ignore = false ; }
Place this filter into service .
33,922
public static String getRequestParameters ( HttpServletRequest aRequest ) { Map m = aRequest . getParameterMap ( ) ; return createQueryStringFromMap ( m , "&" ) . toString ( ) ; }
Creates query String from request body parameters
33,923
public static StringBuilder createQueryStringFromMap ( Map m , String ampersand ) { StringBuilder aReturn = new StringBuilder ( "" ) ; Set aEntryS = m . entrySet ( ) ; Iterator aEntryI = aEntryS . iterator ( ) ; while ( aEntryI . hasNext ( ) ) { Map . Entry aEntry = ( Map . Entry ) aEntryI . next ( ) ; Object o = aEntry . getValue ( ) ; if ( o == null ) { append ( aEntry . getKey ( ) , "" , aReturn , ampersand ) ; } else if ( o instanceof String ) { append ( aEntry . getKey ( ) , o , aReturn , ampersand ) ; } else if ( o instanceof String [ ] ) { String [ ] aValues = ( String [ ] ) o ; for ( int i = 0 ; i < aValues . length ; i ++ ) { append ( aEntry . getKey ( ) , aValues [ i ] , aReturn , ampersand ) ; } } else { append ( aEntry . getKey ( ) , o , aReturn , ampersand ) ; } } return aReturn ; }
Builds a query string from a given map of parameters
33,924
private static StringBuilder append ( Object key , Object value , StringBuilder queryString , String ampersand ) { if ( queryString . length ( ) > 0 ) { queryString . append ( ampersand ) ; } queryString . append ( encodeURL ( key . toString ( ) ) ) ; queryString . append ( "=" ) ; queryString . append ( encodeURL ( value . toString ( ) ) ) ; return queryString ; }
Appends new key and value pair to query string
33,925
public static void stowRequestAttributes ( HttpServletRequest aRequest ) { if ( aRequest . getSession ( ) . getAttribute ( STOWED_REQUEST_ATTRIBS ) != null ) { return ; } Enumeration e = aRequest . getAttributeNames ( ) ; Map map = new HashMap ( ) ; while ( e . hasMoreElements ( ) ) { String name = ( String ) e . nextElement ( ) ; map . put ( name , aRequest . getAttribute ( name ) ) ; } aRequest . getSession ( ) . setAttribute ( STOWED_REQUEST_ATTRIBS , map ) ; }
Stores request attributes in session
33,926
public static void reclaimRequestAttributes ( HttpServletRequest aRequest ) { Map map = ( Map ) aRequest . getSession ( ) . getAttribute ( STOWED_REQUEST_ATTRIBS ) ; if ( map == null ) { return ; } Iterator itr = map . keySet ( ) . iterator ( ) ; while ( itr . hasNext ( ) ) { String name = ( String ) itr . next ( ) ; aRequest . setAttribute ( name , map . get ( name ) ) ; } aRequest . getSession ( ) . removeAttribute ( STOWED_REQUEST_ATTRIBS ) ; }
Returns request attributes from session to request
33,927
public static void setCookie ( HttpServletResponse response , String name , String value , String path ) { Cookie cookie = new Cookie ( name , value ) ; cookie . setSecure ( false ) ; cookie . setPath ( path ) ; cookie . setMaxAge ( 3600 * 24 * 30 ) ; response . addCookie ( cookie ) ; }
Convenience method to set a cookie
33,928
public static String getAppURL ( HttpServletRequest request ) { StringBuffer url = new StringBuffer ( ) ; int port = request . getServerPort ( ) ; if ( port < 0 ) { port = 80 ; } String scheme = request . getScheme ( ) ; url . append ( scheme ) ; url . append ( "://" ) ; url . append ( request . getServerName ( ) ) ; if ( ( scheme . equals ( "http" ) && ( port != 80 ) ) || ( scheme . equals ( "https" ) && ( port != 443 ) ) ) { url . append ( ':' ) ; url . append ( port ) ; } return url . toString ( ) ; }
Convenience method to get the application s URL based on request variables .
33,929
private static String [ ] decodePasswordCookie ( String cookieVal ) { if ( cookieVal == null || cookieVal . length ( ) <= 0 ) { return null ; } char [ ] chars = cookieVal . toCharArray ( ) ; byte [ ] bytes = new byte [ chars . length / 2 ] ; int b ; for ( int n = 0 , m = 0 ; n < bytes . length ; n ++ ) { b = chars [ m ++ ] - ENCODE_CHAR_OFFSET1 ; b |= ( chars [ m ++ ] - ENCODE_CHAR_OFFSET2 ) << 4 ; bytes [ n ] = ( byte ) ( b ^ ( ENCODE_XORMASK + n ) ) ; } cookieVal = new String ( bytes ) ; int pos = cookieVal . indexOf ( ENCODE_DELIMETER ) ; String username = ( pos < 0 ) ? "" : cookieVal . substring ( 0 , pos ) ; String password = ( pos < 0 ) ? "" : cookieVal . substring ( pos + 1 ) ; return new String [ ] { username , password } ; }
Unrafels a cookie string containing a username and password .
33,930
public static Object getComponentInstance ( String name , HttpServletRequest request ) { ServletContext sc = request . getSession ( ) . getServletContext ( ) ; ContainerWrapper containerWrapper = scf . findContainer ( new ServletContextWrapper ( sc ) ) ; if ( ! containerWrapper . isStart ( ) ) { Debug . logError ( "JdonFramework not yet started, please try later " , module ) ; return null ; } return containerWrapper . lookup ( name ) ; }
get a component that registered in container . the component is not different from the service . the component instance is single instance Any intercepter will be disable
33,931
public static ContainerWrapper getContainer ( HttpServletRequest request ) throws Exception { ContainerFinderImp scf = new ContainerFinderImp ( ) ; ServletContext sc = request . getSession ( ) . getServletContext ( ) ; return scf . findContainer ( new ServletContextWrapper ( sc ) ) ; }
get this Web application s container
33,932
public Object assignAggregateRoot ( Object datamodel ) { modelProxyInjection . injectProperties ( datamodel ) ; return modelAdvisor . createProxy ( datamodel ) ; }
assign a object as a AggregateRoot role AggregateRoot can receive a command and reactive a event in CQRS .
33,933
public static TimerTask scheduleTask ( Runnable task , long delay , long period ) { TimerTask timerTask = new ScheduledTask ( task ) ; taskTimer . scheduleAtFixedRate ( timerTask , delay , period ) ; return timerTask ; }
Schedules a task to periodically run . This is useful for tasks such as updating search indexes deleting old data at periodic intervals etc .
33,934
private static Runnable nextTask ( ) { synchronized ( lock ) { while ( taskList . isEmpty ( ) ) { try { lock . wait ( ) ; } catch ( InterruptedException ie ) { } } return ( Runnable ) taskList . removeLast ( ) ; } }
Return the next task in the queue . If no task is available this method will block until a task is added to the queue .
33,935
public ContainerWrapper findContainer ( AppContextWrapper sc ) { ContainerRegistryBuilder cb = ( ContainerRegistryBuilder ) sc . getAttribute ( ContainerRegistryBuilder . APPLICATION_CONTEXT_ATTRIBUTE_NAME ) ; if ( cb == null ) cb = prepare ( sc ) ; launch ( sc , cb ) ; return cb . getContainerWrapper ( ) ; }
lazy startup container when first time the method is called it will startup the container
33,936
public Object getService ( TargetMetaDef targetMetaDef , RequestWrapper request ) { userTargetMetaDefFactory . createTargetMetaRequest ( targetMetaDef , request . getContextHolder ( ) ) ; return webServiceAccessor . getService ( request ) ; }
get a service instance the service must have a interface and implements it .
33,937
protected Parameter [ ] createDefaultParameters ( Class [ ] parameters ) { Parameter [ ] componentParameters = new Parameter [ parameters . length ] ; for ( int i = 0 ; i < parameters . length ; i ++ ) { componentParameters [ i ] = ComponentParameter . DEFAULT ; } return componentParameters ; }
Create default parameters for the given types .
33,938
protected Object newInstance ( Constructor constructor , Object [ ] parameters ) throws InstantiationException , IllegalAccessException , InvocationTargetException { if ( allowNonPublicClasses ) { constructor . setAccessible ( true ) ; } return constructor . newInstance ( parameters ) ; }
Instantiate an object with given parameters and respect the accessible flag .
33,939
public void startElement ( String uri , String localName , String qName , Attributes atts ) throws SAXException { if ( ! stateStack . empty ( ) ) { doNewline ( ) ; doIndent ( ) ; } stateStack . push ( SEEN_ELEMENT ) ; state = SEEN_NOTHING ; super . startElement ( uri , localName , qName , atts ) ; }
Add newline and indentation prior to start tag .
33,940
public void endElement ( String uri , String localName , String qName ) throws SAXException { boolean seenElement = ( state == SEEN_ELEMENT ) ; state = stateStack . pop ( ) ; if ( seenElement ) { doNewline ( ) ; doIndent ( ) ; } super . endElement ( uri , localName , qName ) ; }
Add newline and indentation prior to end tag .
33,941
private void doIndent ( ) throws SAXException { int n = indentStep * stateStack . size ( ) ; if ( n > 0 ) { char ch [ ] = new char [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { ch [ i ] = INDENT_CHAR ; } super . characters ( ch , 0 , n ) ; } }
Add indentation for the current level .
33,942
public Object getComponentInstance ( PicoContainer container ) throws PicoInitializationException , PicoIntrospectionException , AssignabilityRegistrationException , NotConcreteRegistrationException { if ( instantiationGuard == null ) { instantiationGuard = new Guard ( ) { public Object run ( ) { final Constructor constructor ; try { constructor = getGreediestSatisfiableConstructor ( guardedContainer ) ; } catch ( AmbiguousComponentResolutionException e ) { e . setComponent ( getComponentImplementation ( ) ) ; throw e ; } ComponentMonitor componentMonitor = currentMonitor ( ) ; try { Object [ ] parameters = getConstructorArguments ( guardedContainer , constructor ) ; componentMonitor . instantiating ( constructor ) ; long startTime = System . currentTimeMillis ( ) ; Object inst = newInstance ( constructor , parameters ) ; componentMonitor . instantiated ( constructor , System . currentTimeMillis ( ) - startTime ) ; return inst ; } catch ( InvocationTargetException e ) { componentMonitor . instantiationFailed ( constructor , e ) ; if ( e . getTargetException ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getTargetException ( ) ; } else if ( e . getTargetException ( ) instanceof Error ) { throw ( Error ) e . getTargetException ( ) ; } throw new PicoInvocationTargetInitializationException ( e . getTargetException ( ) ) ; } catch ( InstantiationException e ) { componentMonitor . instantiationFailed ( constructor , e ) ; throw new PicoInitializationException ( "Should never get here" ) ; } catch ( IllegalAccessException e ) { componentMonitor . instantiationFailed ( constructor , e ) ; throw new PicoInitializationException ( e ) ; } } } ; } instantiationGuard . setArguments ( container ) ; Object result = instantiationGuard . observe ( getComponentImplementation ( ) ) ; instantiationGuard . clear ( ) ; return result ; }
difference with picocontainer
33,943
protected Object newInstance ( Constructor constructor , Object [ ] parameters ) throws InstantiationException , IllegalAccessException , InvocationTargetException { if ( allowNonPublicClasses ) { constructor . setAccessible ( true ) ; } Object o = constructor . newInstance ( parameters ) ; ComponentAdvsior componentAdvsior = ( ComponentAdvsior ) configInfo . getContainerWrapper ( ) . lookup ( ComponentAdvsior . NAME ) ; Object proxy = null ; if ( componentAdvsior != null ) proxy = componentAdvsior . createProxy ( o ) ; if ( ! proxy . getClass ( ) . isInstance ( o ) ) { Map orignals = getContainerOrignals ( configInfo . getContainerWrapper ( ) ) ; orignals . put ( ( String ) this . getComponentKey ( ) , o ) ; } return proxy ; }
overide InstantiatingComponentAdapter s newInstance
33,944
public ComponentVisitor createtVisitor ( SessionWrapper session , TargetMetaDef targetMetaDef ) { if ( session != null ) return createtSessionVisitor ( session , targetMetaDef ) ; else return new NoSessionProxyComponentVisitor ( componentVisitor , targetMetaRequestsHolder ) ; }
return a ComponentVisitor with cache . the httpSession is used for optimizing the component performance
33,945
public Object querySingleObject ( Collection queryParams , String sqlquery ) throws Exception { JdbcTemp jdbcTemp = new JdbcTemp ( dataSource ) ; return jdbcTemp . querySingleObject ( queryParams , sqlquery ) ; }
query one object from database delgate to JdbCQueryTemp s querySingleObject method
33,946
public List queryMultiObject ( Collection queryParams , String sqlquery ) throws Exception { JdbcTemp jdbcTemp = new JdbcTemp ( dataSource ) ; return jdbcTemp . queryMultiObject ( queryParams , sqlquery ) ; }
query multi object from database delgate to JdbCQueryTemp s queryMultiObject method
33,947
public PageIterator getDatas ( String queryParam , String sqlqueryAllCount , String sqlquery , int start , int count ) { if ( UtilValidate . isEmpty ( sqlqueryAllCount ) ) { Debug . logError ( " the parameter sqlqueryAllCount is null" , module ) ; return new PageIterator ( ) ; } if ( UtilValidate . isEmpty ( sqlquery ) ) { Debug . logError ( " the parameter sqlquery is null" , module ) ; return new PageIterator ( ) ; } Collection queryParams = new ArrayList ( ) ; if ( ! UtilValidate . isEmpty ( queryParam ) ) queryParams . add ( queryParam ) ; return getPageIterator ( sqlqueryAllCount , sqlquery , queryParams , start , count ) ; }
create a PageIterator instance
33,948
public PageIterator getPageIterator ( String sqlqueryAllCount , String sqlquery , String queryParam , int start , int count ) { if ( UtilValidate . isEmpty ( sqlqueryAllCount ) ) { Debug . logError ( " the parameter sqlqueryAllCount is null" , module ) ; return new PageIterator ( ) ; } if ( UtilValidate . isEmpty ( sqlquery ) ) { Debug . logError ( " the parameter sqlquery is null" , module ) ; return new PageIterator ( ) ; } return getDatas ( queryParam , sqlqueryAllCount , sqlquery , start , count ) ; }
same as getDatas the parameters sort is different from the getDatas method
33,949
public PageIterator getPageIterator ( String sqlqueryAllCount , String sqlquery , Collection queryParams , int startIndex , int count ) { Debug . logVerbose ( "[JdonFramework]enter getPageIterator .. start= " + startIndex + " count=" + count , module ) ; if ( queryParams == null ) { Debug . logError ( " the parameters collection is null" , module ) ; return new PageIterator ( ) ; } if ( ( count > blockStrategy . getBlockLength ( ) ) || ( count <= 0 ) ) { count = blockStrategy . getBlockLength ( ) ; } Block currentBlock = getBlock ( sqlquery , queryParams , startIndex , count ) ; if ( currentBlock == null ) { return new PageIterator ( ) ; } startIndex = currentBlock . getStart ( ) ; int endIndex = startIndex + currentBlock . getCount ( ) ; Object [ ] keys = currentBlock . getList ( ) . toArray ( ) ; int allCount = getDatasAllCount ( queryParams , sqlqueryAllCount ) ; Debug . logVerbose ( "[JdonFramework]currentBlock: startIndex=" + startIndex + " endIndex=" + endIndex + " keys length=" + keys . length , module ) ; if ( endIndex < startIndex ) { Debug . logWarning ( "WARNNING : endIndex < startIndex" , module ) ; return new PageIterator ( ) ; } else { return new PageIterator ( allCount , keys , startIndex , endIndex , count ) ; } }
get a PageIterator
33,950
public Block locate ( String sqlquery , Collection queryParams , Object locateId ) { return blockStrategy . locate ( sqlquery , queryParams , locateId ) ; }
looking for a block in that there is a primary key is equals to the locateId . for the sql sentence .
33,951
public static Object createObject ( String className , Object [ ] params ) throws Exception { return createObject ( Class . forName ( className ) , params ) ; }
Instantaite an Object instance requires a constructor with parameters
33,952
public static Object createObject ( Class classObject , Object [ ] params ) throws Exception { Constructor [ ] constructors = classObject . getConstructors ( ) ; Object object = null ; for ( int counter = 0 ; counter < constructors . length ; counter ++ ) { try { object = constructors [ counter ] . newInstance ( params ) ; } catch ( Exception e ) { if ( e instanceof InvocationTargetException ) ( ( InvocationTargetException ) e ) . getTargetException ( ) . printStackTrace ( ) ; } } if ( object == null ) throw new InstantiationException ( ) ; return object ; }
Instantaite an Object instance requires a constractor with parameters
33,953
public void valueUnbound ( HttpSessionBindingEvent event ) { String sessionId = event . getSession ( ) . getId ( ) ; Debug . logVerbose ( "[JdonFramework] unvalueBound active, sessionId :" + sessionId , module ) ; Debug . logVerbose ( "[JdonFramework] unvalueUnbound active, componentsboxs size" + componentsboxsInSession . size ( ) , module ) ; componentsboxsInSession . clear ( ) ; if ( targetMetaRequestsHolder != null ) targetMetaRequestsHolder . clear ( ) ; targetMetaRequestsHolder = null ; componentVisitor = null ; }
session destroyed . remove all references ;
33,954
public Object visit ( ) { Object o = null ; try { TargetMetaRequest targetMetaRequest = targetMetaRequestsHolder . getTargetMetaRequest ( ) ; StringBuilder sb = new StringBuilder ( targetMetaRequest . getTargetMetaDef ( ) . getCacheKey ( ) ) ; sb . append ( targetMetaRequest . getVisitableName ( ) ) ; Debug . logVerbose ( "[JdonFramework] get the optimized instance for the key " + sb . toString ( ) , module ) ; o = componentsboxsInSession . get ( sb . toString ( ) ) ; if ( o == null ) { Debug . logVerbose ( "[JdonFramework] first time visit: " + targetMetaRequest . getTargetMetaDef ( ) . getClassName ( ) , module ) ; o = componentVisitor . visit ( ) ; if ( dynamiceProxyisCached ) componentsboxsInSession . add ( sb . toString ( ) , o ) ; } } catch ( Exception e ) { Debug . logError ( "[JdonFramework]visit error: " + e ) ; } return o ; }
the object type saved in componentsboxs is decided by the method visitableFactory . createVisitable . only ejb service need cached pojo service not need .
33,955
public void put ( Object key , Object value ) { if ( ( key == null ) || ( value == null ) ) return ; try { if ( maxSize > 0 ) { if ( cacheLineTable . containsKey ( key ) ) { keyLRUList . moveFirst ( key ) ; } else { keyLRUList . addFirst ( key ) ; } } if ( expireTime > 0 ) { cacheLineTable . put ( key , new CacheLine ( value , useSoftReference , System . currentTimeMillis ( ) ) ) ; } else { cacheLineTable . put ( key , new CacheLine ( value , useSoftReference ) ) ; } if ( maxSize > 0 && cacheLineTable . size ( ) > maxSize ) { Object lastKey = keyLRUList . getLast ( ) ; removeObject ( lastKey ) ; } } catch ( Exception e ) { Debug . logError ( e ) ; } finally { } Debug . logVerbose ( "[JdonFramework]cache now size = " + keyLRUList . size ( ) + " maxSize =" + maxSize + " this Cache id:" + this . hashCode ( ) , module ) ; }
Puts or loads the passed element into the cache
33,956
public Object get ( final Object key ) { if ( key == null ) return null ; if ( ! cacheLineTable . containsKey ( key ) ) return null ; CacheLine line = ( CacheLine ) cacheLineTable . get ( key ) ; if ( hasExpired ( line ) ) { removeObject ( key ) ; line = null ; } if ( line == null ) { missCount ++ ; return null ; } hitCount ++ ; if ( maxSize > 0 ) { keyLRUList . moveFirst ( key ) ; } return line . getValue ( ) ; }
Gets an element from the cache according to the specified key . If the requested element hasExpired it is removed before it is looked up which causes the function to return null .
33,957
public void setMaxSize ( long maxSize ) { if ( maxSize <= 0 ) { keyLRUList . clear ( ) ; } else if ( maxSize > 0 && this . maxSize <= 0 ) { Iterator keys = cacheLineTable . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { keyLRUList . add ( keys . next ( ) ) ; } } if ( maxSize > 0 && cacheLineTable . size ( ) > maxSize ) { while ( cacheLineTable . size ( ) > maxSize ) { Object lastKey = keyLRUList . getLast ( ) ; removeObject ( lastKey ) ; } } this . maxSize = maxSize ; }
Sets the maximum number of elements in the cache . If 0 there is no maximum .
33,958
public void setExpireTime ( long expireTime ) { if ( this . expireTime <= 0 && expireTime > 0 ) { long currentTime = System . currentTimeMillis ( ) ; Iterator values = cacheLineTable . values ( ) . iterator ( ) ; while ( values . hasNext ( ) ) { CacheLine line = ( CacheLine ) values . next ( ) ; line . setLoadTime ( currentTime ) ; } } else if ( this . expireTime <= 0 && expireTime > 0 ) { } this . expireTime = expireTime ; }
Sets the expire time for the cache elements . If 0 elements never expire .
33,959
public boolean containsKey ( Object key ) { CacheLine line = ( CacheLine ) cacheLineTable . get ( key ) ; if ( hasExpired ( line ) ) { removeObject ( key ) ; line = null ; } if ( line != null ) { return true ; } else { return false ; } }
Returns a boolean specifying whether or not an element with the specified key is in the cache . If the requested element hasExpired it is removed before it is looked up which causes the function to return false .
33,960
public boolean hasExpired ( Object key ) { if ( key == null ) return false ; CacheLine line = ( CacheLine ) cacheLineTable . get ( key ) ; return hasExpired ( line ) ; }
Returns a boolean specifying whether or not the element corresponding to the key has expired . Only returns true if element is in cache and has expired . Error conditions return false if no expireTable entry returns true . Always returns false if expireTime < = 0 . Also if SoftReference in the CacheLine object has been cleared by the gc return true .
33,961
public void clearExpired ( ) { Iterator keys = cacheLineTable . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { Object key = keys . next ( ) ; if ( hasExpired ( key ) ) { removeObject ( key ) ; } } }
Clears all expired cache entries ; also clear any cache entries where the SoftReference in the CacheLine object has been cleared by the gc
33,962
public static String decodeString ( String str ) { try { return new String ( Base64 . decode ( str ) ) ; } catch ( IOException io ) { throw new RuntimeException ( io . getMessage ( ) , io . getCause ( ) ) ; } }
Decode a string using Base64 encoding .
33,963
public void registerAppRoot ( ) { containerWrapper . register ( AppConfigureCollection . NAME , AppConfigureCollection . class ) ; containerWrapper . register ( StartablecomponentsRegistry . NAME , StartablecomponentsRegistry . class ) ; }
register at first before xml and annotation
33,964
public void setApplicationContext ( ApplicationContext applicationContext ) throws BeansException { this . applicationContext = applicationContext ; if ( servletContext == null ) if ( applicationContext instanceof WebApplicationContext ) { servletContext = ( ( WebApplicationContext ) applicationContext ) . getServletContext ( ) ; if ( servletContext == null ) { System . err . print ( "this class only fit for Spring Web Application" ) ; return ; } } AppContextWrapper acw = new ServletContextWrapper ( servletContext ) ; ContainerFinder containerFinder = new ContainerFinderImp ( ) ; containerWrapper = containerFinder . findContainer ( acw ) ; }
ApplicationContextAware s method
33,965
public void postProcessBeanDefinitionRegistry ( BeanDefinitionRegistry registry ) throws BeansException { for ( String beanName : registry . getBeanDefinitionNames ( ) ) { BeanDefinition beanDefinition = registry . getBeanDefinition ( beanName ) ; String beanClassName = beanDefinition . getBeanClassName ( ) ; try { Class beanClass = Class . forName ( beanClassName ) ; for ( final Field field : ClassUtil . getAllDecaredFields ( beanClass ) ) { if ( field . isAnnotationPresent ( Autowired . class ) ) { Object o = findBeanClassInJdon ( field . getType ( ) ) ; if ( o != null ) { neededJdonComponents . put ( field . getName ( ) , o ) ; } } } } catch ( ClassNotFoundException ex ) { ex . printStackTrace ( ) ; } } }
BeanDefinitionRegistryPostProcessor s method
33,966
public Disruptor createDisruptor ( String topic ) { Disruptor disruptor = createDisruptorWithEventHandler ( topic ) ; if ( disruptor != null ) disruptor . start ( ) ; return disruptor ; }
one event one EventDisruptor
33,967
public List < MethodInterceptor > create ( TargetMetaDef targetMetaDef ) throws Exception { Debug . logVerbose ( "[JdonFramework] enter create PointcutAdvisor " , module ) ; if ( targetMetaDef . isEJB ( ) ) { if ( interceptorsForEJB . isEmpty ( ) ) { createEJBAdvice ( targetMetaDef ) ; } return interceptorsForEJB ; } if ( interceptors . isEmpty ( ) ) { createPOJOAdvice ( targetMetaDef ) ; } List < MethodInterceptor > targets = targetInterceptors . get ( targetMetaDef . getName ( ) ) ; if ( targets == null ) { targets = createTargetPOJOAdvice ( targetMetaDef . getName ( ) ) ; targetInterceptors . put ( targetMetaDef . getName ( ) , targets ) ; } return interceptors ; }
create the all interceptor instances and put them into interceptorsChain ; the interceptors that prointcut is for SERVIERS are in the front and then the EJB Interceptors in the back there are POJO interceptors . you can change the orders bu replacing this class in container . xml
33,968
protected ModelForm getModelForm ( ModelHandler modelHandler , ActionForm actionForm , HttpServletRequest request ) throws Exception { if ( actionForm == null ) { throw new Exception ( " must define form-bean as 'action' name in struts-config.xml " ) ; } ModelForm strutsForm = ( ModelForm ) actionForm ; String action = strutsForm . getAction ( ) ; if ( ( action == null ) || ( action . length ( ) == 0 ) ) throw new Exception ( " Need a field : <html:hidden property=action /> in jsp's form! " ) ; return strutsForm ; }
get a ModelForm or create it .
33,969
protected Object makeModel ( ActionMapping actionMapping , ActionForm actionForm , HttpServletRequest request , ModelHandler modelHandler ) throws Exception { Object model = null ; try { String formName = actionMapping . getName ( ) ; if ( formName == null ) throw new Exception ( "no define the FormName in struts_config.xml" ) ; ModelMapping modelMapping = modelHandler . getModelMapping ( ) ; String keyName = modelMapping . getKeyName ( ) ; String keyValue = request . getParameter ( keyName ) ; if ( keyValue == null ) { Debug . logError ( "[JdonFramework]Need a model's key field : <html:hidden property=MODEL KEY /> in jsp's form! " , module ) ; } modelManager . removeCache ( keyValue ) ; Debug . logVerbose ( "[JdonFramework] no model cache, keyName is " + keyName , module ) ; model = modelManager . getModelObject ( formName ) ; } catch ( Exception e ) { Debug . logError ( "[JdonFramework] makeModel error: " + e ) ; throw new Exception ( e ) ; } return model ; }
create a Model from the jdonframework . xml
33,970
public void service ( final ServletRequest req , final ServletResponse resp ) throws ServletException , IOException { HttpServletRequest request = ( HttpServletRequest ) req ; HttpServletResponse response = ( HttpServletResponse ) resp ; final String beanName = request . getPathInfo ( ) . substring ( 1 ) ; htorp . process ( beanName , request , response ) ; }
Servlet to handle incoming Hessian requests and invoke HessianToJdonRequestProcessor .
33,971
public static java . sql . Date toSqlDate ( String date ) { java . util . Date newDate = toDate ( date , "00:00:00" ) ; if ( newDate != null ) return new java . sql . Date ( newDate . getTime ( ) ) ; else return null ; }
Converts a date String into a java . sql . Date
33,972
public static java . sql . Date toSqlDate ( String monthStr , String dayStr , String yearStr ) { java . util . Date newDate = toDate ( monthStr , dayStr , yearStr , "0" , "0" , "0" ) ; if ( newDate != null ) return new java . sql . Date ( newDate . getTime ( ) ) ; else return null ; }
Makes a java . sql . Date from separate Strings for month day year
33,973
public static java . sql . Date toSqlDate ( int month , int day , int year ) { java . util . Date newDate = toDate ( month , day , year , 0 , 0 , 0 ) ; if ( newDate != null ) return new java . sql . Date ( newDate . getTime ( ) ) ; else return null ; }
Makes a java . sql . Date from separate ints for month day year
33,974
public static java . sql . Time toSqlTime ( String time ) { java . util . Date newDate = toDate ( "1/1/1970" , time ) ; if ( newDate != null ) return new java . sql . Time ( newDate . getTime ( ) ) ; else return null ; }
Converts a time String into a java . sql . Time
33,975
public static java . sql . Time toSqlTime ( String hourStr , String minuteStr , String secondStr ) { java . util . Date newDate = toDate ( "0" , "0" , "0" , hourStr , minuteStr , secondStr ) ; if ( newDate != null ) return new java . sql . Time ( newDate . getTime ( ) ) ; else return null ; }
Makes a java . sql . Time from separate Strings for hour minute and second .
33,976
public static java . sql . Time toSqlTime ( int hour , int minute , int second ) { java . util . Date newDate = toDate ( 0 , 0 , 0 , hour , minute , second ) ; if ( newDate != null ) return new java . sql . Time ( newDate . getTime ( ) ) ; else return null ; }
Makes a java . sql . Time from separate ints for hour minute and second .
33,977
public static java . sql . Timestamp toTimestamp ( String dateTime ) { java . util . Date newDate = toDate ( dateTime ) ; if ( newDate != null ) return new java . sql . Timestamp ( newDate . getTime ( ) ) ; else return null ; }
Converts a date and time String into a Timestamp
33,978
public static java . sql . Timestamp toTimestamp ( String date , String time ) { java . util . Date newDate = toDate ( date , time ) ; if ( newDate != null ) return new java . sql . Timestamp ( newDate . getTime ( ) ) ; else return null ; }
Converts a date String and a time String into a Timestamp
33,979
public static java . sql . Timestamp toTimestamp ( String monthStr , String dayStr , String yearStr , String hourStr , String minuteStr , String secondStr ) { java . util . Date newDate = toDate ( monthStr , dayStr , yearStr , hourStr , minuteStr , secondStr ) ; if ( newDate != null ) return new java . sql . Timestamp ( newDate . getTime ( ) ) ; else return null ; }
Makes a Timestamp from separate Strings for month day year hour minute and second .
33,980
public static java . sql . Timestamp toTimestamp ( int month , int day , int year , int hour , int minute , int second ) { java . util . Date newDate = toDate ( month , day , year , hour , minute , second ) ; if ( newDate != null ) return new java . sql . Timestamp ( newDate . getTime ( ) ) ; else return null ; }
Makes a Timestamp from separate ints for month day year hour minute and second .
33,981
public static java . util . Date toDate ( String dateTime ) { String date = dateTime . substring ( 0 , dateTime . indexOf ( " " ) ) ; String time = dateTime . substring ( dateTime . indexOf ( " " ) + 1 ) ; return toDate ( date , time ) ; }
Converts a date and time String into a Date
33,982
public static java . util . Date toDate ( String date , String time ) { if ( date == null || time == null ) return null ; String month ; String day ; String year ; String hour ; String minute ; String second ; int dateSlash1 = date . indexOf ( "/" ) ; int dateSlash2 = date . lastIndexOf ( "/" ) ; if ( dateSlash1 <= 0 || dateSlash1 == dateSlash2 ) return null ; int timeColon1 = time . indexOf ( ":" ) ; int timeColon2 = time . lastIndexOf ( ":" ) ; if ( timeColon1 <= 0 ) return null ; month = date . substring ( 0 , dateSlash1 ) ; day = date . substring ( dateSlash1 + 1 , dateSlash2 ) ; year = date . substring ( dateSlash2 + 1 ) ; hour = time . substring ( 0 , timeColon1 ) ; if ( timeColon1 == timeColon2 ) { minute = time . substring ( timeColon1 + 1 ) ; second = "0" ; } else { minute = time . substring ( timeColon1 + 1 , timeColon2 ) ; second = time . substring ( timeColon2 + 1 ) ; } return toDate ( month , day , year , hour , minute , second ) ; }
Converts a date String and a time String into a Date
33,983
public static java . util . Date toDate ( String monthStr , String dayStr , String yearStr , String hourStr , String minuteStr , String secondStr ) { int month , day , year , hour , minute , second ; try { month = Integer . parseInt ( monthStr ) ; day = Integer . parseInt ( dayStr ) ; year = Integer . parseInt ( yearStr ) ; hour = Integer . parseInt ( hourStr ) ; minute = Integer . parseInt ( minuteStr ) ; second = Integer . parseInt ( secondStr ) ; } catch ( Exception e ) { return null ; } return toDate ( month , day , year , hour , minute , second ) ; }
Makes a Date from separate Strings for month day year hour minute and second .
33,984
public static java . util . Date toDate ( int month , int day , int year , int hour , int minute , int second ) { Calendar calendar = Calendar . getInstance ( ) ; try { calendar . set ( year , month - 1 , day , hour , minute , second ) ; } catch ( Exception e ) { return null ; } return new java . util . Date ( calendar . getTime ( ) . getTime ( ) ) ; }
Makes a Date from separate ints for month day year hour minute and second .
33,985
public static java . sql . Timestamp monthBegin ( ) { Calendar mth = Calendar . getInstance ( ) ; mth . set ( Calendar . DAY_OF_MONTH , 1 ) ; mth . set ( Calendar . HOUR_OF_DAY , 0 ) ; mth . set ( Calendar . MINUTE , 0 ) ; mth . set ( Calendar . SECOND , 0 ) ; mth . set ( Calendar . AM_PM , Calendar . AM ) ; return new java . sql . Timestamp ( mth . getTime ( ) . getTime ( ) ) ; }
Makes a Timestamp for the beginning of the month
33,986
public ActionErrors validate ( ActionMapping mapping , HttpServletRequest request ) { ActionErrors errors = null ; Boolean maxLengthExceeded = ( Boolean ) request . getAttribute ( MultipartRequestHandler . ATTRIBUTE_MAX_LENGTH_EXCEEDED ) ; if ( ( maxLengthExceeded != null ) && ( maxLengthExceeded . booleanValue ( ) ) ) { errors = new ActionErrors ( ) ; errors . add ( ERROR_PROPERTY_MAX_LENGTH_EXCEEDED , new ActionMessage ( "maxLengthExceeded" ) ) ; } else if ( fileMap . size ( ) > MAX_IMAGES_COUNT ) { errors = new ActionErrors ( ) ; errors . add ( ERROR_PROPERTY_MAX_LENGTH_EXCEEDED , new ActionMessage ( "maxLengthExceeded" ) ) ; } else { Iterator iter = fileMap . values ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { FormFile file = ( FormFile ) iter . next ( ) ; String fileName = file . getFileName ( ) ; if ( ( ! fileName . toLowerCase ( ) . endsWith ( ".gif" ) ) && ! ( fileName . toLowerCase ( ) . endsWith ( ".jpg" ) ) && ! ( fileName . toLowerCase ( ) . endsWith ( ".png" ) ) ) { errors = new ActionErrors ( ) ; errors . add ( "notImage" , new ActionMessage ( "notImage" ) ) ; } } } return errors ; }
Check to make sure the client hasn t exceeded the maximum allowed upload size inside of this validate method .
33,987
public Object execute ( Method method , Object targetObj , Object [ ] p_args ) throws Throwable { try { if ( ( method == null ) || ( targetObj == null ) ) Debug . logError ( "[JdonFramework] no method or target, please check your configure" , module ) ; if ( p_args == null ) p_args = new Object [ 0 ] ; Debug . logVerbose ( "[JdonFramework] method invoke: " + targetObj . getClass ( ) . getName ( ) + " method=" + method . getName ( ) , module ) ; Object result = method . invoke ( targetObj , p_args ) ; Debug . logVerbose ( "[JdonFramework] method invoke successfully " , module ) ; return result ; } catch ( IllegalArgumentException iex ) { String errorInfo = "Errors happened in your method:[" + targetObj . getClass ( ) . getName ( ) + "." + method . getName ( ) + "]" ; Debug . logError ( errorInfo , module ) ; errorInfo = "[JdonFramework] method invoke IllegalArgumentException: " + iex + " method argument type :[" + method . getParameterTypes ( ) + "], but method arguments value p_args type:" + p_args . getClass ( ) . getName ( ) ; Debug . logError ( errorInfo , module ) ; throw new Throwable ( errorInfo , iex ) ; } catch ( InvocationTargetException ex ) { Debug . logError ( ex ) ; String errorInfo = "Errors happened in your method:[" + targetObj . getClass ( ) . getName ( ) + "." + method . getName ( ) + "]" ; Debug . logError ( errorInfo , module ) ; throw new Throwable ( errorInfo ) ; } catch ( IllegalAccessException ex ) { String errorInfo = "Errors happened in your method:[" + targetObj . getClass ( ) . getName ( ) + "." + method . getName ( ) + "]" ; Debug . logError ( errorInfo , module ) ; Debug . logError ( "[JdonFramework] method invoke IllegalAccessException: " + ex , module ) ; throw new Throwable ( "access method:" + method + " " + ex , ex ) ; } catch ( Exception ex ) { String errorInfo = "Errors happened in your method:[" + targetObj . getClass ( ) . getName ( ) + "." + method . getName ( ) + "]" ; Debug . logError ( errorInfo , module ) ; Debug . logError ( "[JdonFramework] method invoke error: " + ex , module ) ; throw new Throwable ( " method invoke error: " + ex ) ; } }
the service execute by method reflection
33,988
public Object createTargetObject ( TargetServiceFactory targetServiceFactory ) { Debug . logVerbose ( "[JdonFramework] now getTargetObject by visitor " , module ) ; Object targetObjRef = null ; try { TargetMetaRequest targetMetaRequest = targetMetaRequestsHolder . getTargetMetaRequest ( ) ; TargetMetaDef targetMetaDef = targetMetaRequest . getTargetMetaDef ( ) ; if ( targetMetaDef . isEJB ( ) ) { ComponentVisitor cm = targetMetaRequest . getComponentVisitor ( ) ; targetMetaRequest . setVisitableName ( ComponentKeys . TARGETSERVICE_FACTORY ) ; Debug . logVerbose ( ComponentKeys . TARGETSERVICE_FACTORY + " in action (cache)" , module ) ; targetObjRef = cm . visit ( ) ; } else { Debug . logVerbose ( "[JdonFramework] not active targer service instance cache !!!!" , module ) ; targetObjRef = targetServiceFactory . create ( ) ; } } catch ( Exception e ) { Debug . logError ( "[JdonFramework]createTargetObject error: " + e , module ) ; } return targetObjRef ; }
if target service is ejb object cache it so this function can active stateful session bean .
33,989
public Object initModelIF ( EventModel em , ModelForm form , HttpServletRequest request ) throws Exception { return initModel ( request ) ; }
Presentation layer need a ModelForm instance that include some initially data these data must obtain from service . this method implements these functions by deleagating service .
33,990
public Object findModelIF ( Object keyValue , HttpServletRequest request ) throws Exception { return findModelByKey ( ( String ) keyValue , request ) ; }
obtain a existed Model instance by his primtive key .
33,991
public void modelCopyToForm ( Model model , ModelForm form ) throws Exception { try { PropertyUtils . copyProperties ( form , model ) ; } catch ( Exception e ) { String error = " Model:" + model . getClass ( ) . getName ( ) + " copy To ModelForm:" + form . getClass ( ) . getName ( ) + " error:" + e ; Debug . logError ( error , module ) ; throw new Exception ( error ) ; } }
for old version below 1 . 4
33,992
public void formCopyToModelIF ( ModelForm form , Object model ) throws Exception { if ( model == null || form == null ) return ; if ( model instanceof Model ) { formCopyToModel ( form , ( Model ) model ) ; return ; } try { PropertyUtils . copyProperties ( model , form ) ; } catch ( InvocationTargetException ie ) { String error = "error happened in getXXX method of ModelForm:" + form . getClass ( ) . getName ( ) + " error:" + ie ; Debug . logError ( error , module ) ; throw new Exception ( error ) ; } catch ( Exception e ) { String error = " ModelForm:" + form . getClass ( ) . getName ( ) + " copy To Model:" + model . getClass ( ) . getName ( ) + " error:" + e ; Debug . logError ( error , module ) ; throw new Exception ( error ) ; } }
ModelForm object s data transfer to Model object
33,993
public void writeObject ( Object obj , AbstractHessianOutput out ) throws IOException { if ( out . addRef ( obj ) ) { return ; } Class < ? > cl = obj . getClass ( ) ; try { if ( writeReplace != null ) { Object repl = writeReplace . invoke ( obj , new Object [ 0 ] ) ; out . removeRef ( obj ) ; out . writeObject ( repl ) ; out . replaceRef ( repl , obj ) ; return ; } } catch ( Exception e ) { log . log ( Level . FINE , e . toString ( ) , e ) ; } int ref = out . writeObjectBegin ( cl . getName ( ) ) ; if ( ref < - 1 ) { for ( int i = 0 ; i < localMethods . length ; i ++ ) { Object value = null ; try { value = localMethods [ i ] . invoke ( obj , ( Object [ ] ) null ) ; } catch ( Exception e ) { log . log ( Level . FINE , e . toString ( ) , e ) ; } if ( ! LazyUtil . isPropertyInitialized ( value ) ) { continue ; } out . writeString ( localNames [ i ] ) ; out . writeObject ( value ) ; } out . writeMapEnd ( ) ; } else { if ( ref == - 1 ) { out . writeInt ( localNames . length ) ; for ( int i = 0 ; i < localNames . length ; i ++ ) { out . writeString ( localNames [ i ] ) ; } out . writeObjectBegin ( cl . getName ( ) ) ; } for ( int i = 0 ; i < localMethods . length ; i ++ ) { Object value = null ; try { value = localMethods [ i ] . invoke ( obj , ( Object [ ] ) null ) ; } catch ( Exception e ) { log . log ( Level . FINER , e . toString ( ) , e ) ; } if ( ! LazyUtil . isPropertyInitialized ( value ) ) { continue ; } out . writeObject ( value ) ; } } }
Write object in output
33,994
private Method findSetter ( Method [ ] methods , String getterName , Class < ? > arg ) { String setterName = "set" + getterName . substring ( INT_VALUE ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method method = methods [ i ] ; if ( ! method . getName ( ) . equals ( setterName ) ) { continue ; } if ( ! method . getReturnType ( ) . equals ( void . class ) ) { continue ; } Class < ? > [ ] params = method . getParameterTypes ( ) ; if ( params . length == 1 && params [ 0 ] . equals ( arg ) ) { return method ; } } return null ; }
Finds any matching setter .
33,995
public ServiceFactory getServiceFactory ( AppContextWrapper sc ) { ContainerWrapper containerWrapper = containerFinder . findContainer ( sc ) ; ServiceFactory serviceFactory = ( ServiceFactory ) containerWrapper . lookup ( ComponentKeys . WEBSERVICE_FACTORY ) ; return serviceFactory ; }
the model configure in jdonframework . xml will execute the service directly .
33,996
public Object execute ( String name , MethodMetaArgs methodMetaArgs , AppContextWrapper acw ) throws Exception { if ( ( methodMetaArgs == null ) || ( methodMetaArgs . getMethodName ( ) == null ) ) { Debug . logWarning ( " methodMetaArgs is null. cann't invoke service.execute" ) ; } Debug . logVerbose ( "++++++++++++++++++++++++++++++<begin: invoking from jdonframework.xml" , module ) ; Debug . logVerbose ( "+++++++++++++++execute new service='" + name + "' method='" + methodMetaArgs . getMethodName ( ) + "'" , module ) ; ContainerWrapper cw = containerCallback . getContainerWrapper ( ) ; TargetMetaDef targetMetaDef = userTargetMetaDefFactory . getTargetMetaDef ( name , cw ) ; if ( targetMetaDef == null ) return null ; Object result = execute ( targetMetaDef , methodMetaArgs , acw ) ; Debug . logVerbose ( "+++++++++++++++execute service='" + name + "' method='" + methodMetaArgs . getMethodName ( ) + "' successfully!" , module ) ; Debug . logVerbose ( "++++++++++++++++++++++++++++++<end:" , module ) ; return result ; }
running the service and return the result without session
33,997
private boolean methodMatchsModelGET ( Method method ) { boolean condition = false ; try { if ( isModelCache . contains ( method ) ) { condition = true ; return condition ; } String mehtodName = method . getName ( ) ; if ( method . getReturnType ( ) == null ) return condition ; Class returnClass = method . getReturnType ( ) ; if ( returnClass . getSuperclass ( ) == null ) return condition ; Debug . logVerbose ( "[JdonFramework]methodMatchsModelGET: returnClassName = " + returnClass . getName ( ) , module ) ; if ( ModelUtil . isModel ( returnClass ) ) { if ( mehtodName . indexOf ( match_MethodName ) != - 1 ) { condition = true ; isModelCache . add ( method ) ; } } } catch ( Exception ex ) { Debug . logError ( "[JdonFramework]Exception error:" + ex , module ) ; } catch ( Throwable the ) { Debug . logError ( "[JdonFramework]Throwable error:" + the , module ) ; } return condition ; }
1 . check return type if is Model 2 . check method name if include get 3 . if found them cache this method
33,998
public String getProperty ( String name ) { if ( propertyCache . containsKey ( name ) ) { return ( String ) propertyCache . get ( name ) ; } String [ ] propName = parsePropertyName ( name ) ; Element element = doc . getRootElement ( ) ; for ( int i = 0 ; i < propName . length ; i ++ ) { element = element . getChild ( propName [ i ] ) ; if ( element == null ) { return null ; } } String value = element . getText ( ) ; if ( "" . equals ( value ) ) { return null ; } else { value = value . trim ( ) ; propertyCache . put ( name , value ) ; return value ; } }
Returns the value of the specified property .
33,999
public void setProperty ( String name , String value ) { propertyCache . put ( name , value ) ; String [ ] propName = parsePropertyName ( name ) ; Element element = doc . getRootElement ( ) ; for ( int i = 0 ; i < propName . length ; i ++ ) { if ( element . getChild ( propName [ i ] ) == null ) { element . addContent ( new Element ( propName [ i ] ) ) ; } element = element . getChild ( propName [ i ] ) ; } element . setText ( value ) ; }
Sets the value of the specified property . If the property doesn t currently exist it will be automatically created .