idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
15,000
private void writeInbound ( Definition def , Writer out , int indent ) throws IOException { writeIndent ( out , indent ) ; out . write ( "<inbound-resourceadapter>" ) ; writeEol ( out ) ; writeIndent ( out , indent + 1 ) ; out . write ( "<messageadapter>" ) ; writeEol ( out ) ; writeIndent ( out , indent + 2 ) ; out . write ( "<messagelistener>" ) ; writeEol ( out ) ; writeIndent ( out , indent + 3 ) ; if ( ! def . isDefaultPackageInbound ( ) ) { out . write ( "<messagelistener-type>" + def . getMlClass ( ) + "</messagelistener-type>" ) ; } else { out . write ( "<messagelistener-type>" + def . getRaPackage ( ) + ".inflow." + def . getMlClass ( ) + "</messagelistener-type>" ) ; } writeEol ( out ) ; writeIndent ( out , indent + 3 ) ; out . write ( "<activationspec>" ) ; writeEol ( out ) ; writeIndent ( out , indent + 4 ) ; out . write ( "<activationspec-class>" + def . getRaPackage ( ) + ".inflow." + def . getAsClass ( ) + "</activationspec-class>" ) ; writeEol ( out ) ; writeAsConfigPropsXml ( def . getAsConfigProps ( ) , out , indent + 4 ) ; writeIndent ( out , indent + 3 ) ; out . write ( "</activationspec>" ) ; writeEol ( out ) ; writeIndent ( out , indent + 2 ) ; out . write ( "</messagelistener>" ) ; writeEol ( out ) ; writeIndent ( out , indent + 1 ) ; out . write ( "</messageadapter>" ) ; writeEol ( out ) ; writeIndent ( out , indent ) ; out . write ( "</inbound-resourceadapter>" ) ; writeEol ( out ) ; }
Output inbound xml part
15,001
public static void main ( String [ ] args ) { String outputDir = "out" ; String defxml = null ; int arg = 0 ; if ( args . length > 0 ) { while ( args . length > arg + 1 ) { if ( args [ arg ] . startsWith ( "-" ) ) { if ( args [ arg ] . equals ( "-o" ) ) { arg ++ ; if ( arg >= args . length ) { usage ( ) ; System . exit ( OTHER ) ; } outputDir = args [ arg ] ; } else if ( args [ arg ] . equals ( "-f" ) ) { arg ++ ; if ( arg >= args . length ) { usage ( ) ; System . exit ( OTHER ) ; } defxml = args [ arg ] ; } } else { usage ( ) ; System . exit ( OTHER ) ; } arg ++ ; } } try { File out = new File ( outputDir ) ; Utils . recursiveDelete ( out ) ; Definition def ; if ( defxml == null ) def = inputFromCommandLine ( ) ; else def = inputFromXml ( defxml ) ; if ( def == null ) System . exit ( ERROR ) ; def . setOutputDir ( outputDir ) ; Profile profile ; switch ( def . getVersion ( ) ) { case "1.7" : profile = new JCA17Profile ( ) ; break ; case "1.6" : profile = new JCA16Profile ( ) ; break ; case "1.5" : profile = new JCA15Profile ( ) ; break ; default : profile = new JCA10Profile ( ) ; break ; } profile . generate ( def ) ; if ( def . getBuild ( ) . equals ( "ant" ) ) copyAllJars ( outputDir ) ; System . out . println ( rb . getString ( "code.wrote" ) ) ; System . exit ( SUCCESS ) ; } catch ( IOException | JAXBException e ) { e . printStackTrace ( ) ; } }
Code generator stand alone tool
15,002
private static Definition inputFromXml ( String defxml ) throws IOException , JAXBException { JAXBContext context = JAXBContext . newInstance ( "org.ironjacamar.codegenerator" ) ; Unmarshaller unmarshaller = context . createUnmarshaller ( ) ; return ( Definition ) unmarshaller . unmarshal ( new File ( defxml ) ) ; }
input from xml file
15,003
private static void setDefaultValue ( Definition def , String className , String stringValue ) { if ( className . endsWith ( stringValue ) ) def . setDefaultValue ( className . substring ( 0 , className . length ( ) - stringValue . length ( ) ) ) ; }
check defalut value and set it
15,004
private static void copyAllJars ( String outputDir ) throws IOException { File out = new File ( outputDir ) ; String targetPath = out . getAbsolutePath ( ) + File . separatorChar + "lib" ; File current = new File ( "." ) ; String path = current . getCanonicalPath ( ) ; String libPath = path + File . separatorChar + ".." + File . separatorChar + ".." + File . separatorChar + "lib" ; Utils . copyFolder ( libPath , targetPath , "jar" , false ) ; }
copy all jars
15,005
private static Properties loadProperties ( ) { Properties properties = new Properties ( ) ; boolean loaded = false ; String sysProperty = SecurityActions . getSystemProperty ( "ironjacamar.options" ) ; if ( sysProperty != null && ! sysProperty . equals ( "" ) ) { File file = new File ( sysProperty ) ; if ( file . exists ( ) ) { FileInputStream fis = null ; try { fis = new FileInputStream ( file ) ; properties . load ( fis ) ; loaded = true ; } catch ( Throwable t ) { } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException ioe ) { } } } } } if ( ! loaded ) { File file = new File ( IRONJACAMAR_PROPERTIES ) ; if ( file . exists ( ) ) { FileInputStream fis = null ; try { fis = new FileInputStream ( file ) ; properties . load ( fis ) ; loaded = true ; } catch ( Throwable t ) { } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException ioe ) { } } } } } if ( ! loaded ) { InputStream is = null ; try { ClassLoader cl = Main . class . getClassLoader ( ) ; is = cl . getResourceAsStream ( IRONJACAMAR_PROPERTIES ) ; properties . load ( is ) ; loaded = true ; } catch ( Throwable t ) { } finally { if ( is != null ) { try { is . close ( ) ; } catch ( IOException ioe ) { } } } } return properties ; }
Load configuration values specified from either a file or the classloader
15,006
private static String configurationString ( Properties properties , String key , String defaultValue ) { if ( properties != null ) { return properties . getProperty ( key , defaultValue ) ; } return defaultValue ; }
Get configuration string
15,007
private static boolean configurationBoolean ( Properties properties , String key , boolean defaultValue ) { if ( properties != null ) { if ( properties . containsKey ( key ) ) return Boolean . valueOf ( properties . getProperty ( key ) ) ; } return defaultValue ; }
Get configuration boolean
15,008
private static int configurationInteger ( Properties properties , String key , int defaultValue ) { if ( properties != null ) { if ( properties . containsKey ( key ) ) return Integer . valueOf ( properties . getProperty ( key ) ) ; } return defaultValue ; }
Get configuration integer
15,009
private static void applySystemProperties ( Properties properties ) { if ( properties != null ) { for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { String key = ( String ) entry . getKey ( ) ; if ( key . startsWith ( "system.property." ) ) { key = key . substring ( 16 ) ; SecurityActions . setSystemProperty ( key , ( String ) entry . getValue ( ) ) ; } } } }
Apply any defined system properties
15,010
public void setResourceAdapterClassLoader ( ResourceAdapterClassLoader v ) { if ( trace ) log . tracef ( "%s: setResourceAdapterClassLoader(%s)" , Integer . toHexString ( System . identityHashCode ( this ) ) , v ) ; resourceAdapterClassLoader = v ; }
Set the resource adapter class loader
15,011
private static void bind ( Context ctx , Name name , Object value ) throws NamingException { int size = name . size ( ) ; String atom = name . get ( size - 1 ) ; Context parentCtx = createSubcontext ( ctx , name . getPrefix ( size - 1 ) ) ; parentCtx . bind ( atom , value ) ; }
Bind val to name in ctx and make sure that all intermediate contexts exist
15,012
public void startTransaction ( ) { Long key = Long . valueOf ( Thread . currentThread ( ) . getId ( ) ) ; TransactionImpl tx = txs . get ( key ) ; if ( tx == null ) { TransactionImpl newTx = new TransactionImpl ( key ) ; tx = txs . putIfAbsent ( key , newTx ) ; if ( tx == null ) tx = newTx ; } tx . active ( ) ; }
Start a transaction
15,013
public void commitTransaction ( ) throws SystemException { Long key = Long . valueOf ( Thread . currentThread ( ) . getId ( ) ) ; TransactionImpl tx = txs . get ( key ) ; if ( tx != null ) { try { tx . commit ( ) ; } catch ( Throwable t ) { SystemException se = new SystemException ( "Error during commit" ) ; se . initCause ( t ) ; throw se ; } } else { throw new IllegalStateException ( "No transaction to commit" ) ; } }
Commit a transaction
15,014
public void assignTransaction ( TransactionImpl v ) { txs . put ( Long . valueOf ( Thread . currentThread ( ) . getId ( ) ) , v ) ; }
Assign a transaction
15,015
public static ClassLoader getClassLoader ( final Class < ? > c ) { if ( System . getSecurityManager ( ) == null ) return c . getClassLoader ( ) ; return AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { public ClassLoader run ( ) { return c . getClassLoader ( ) ; } } ) ; }
Get the classloader .
15,016
public static String restoreExpression ( Map < String , String > m , String key , String subkey , String v ) { String k = key ; if ( subkey != null ) { if ( ! isIncorrectExpression ( subkey ) && subkey . startsWith ( "${" ) ) { subkey = subkey . substring ( 2 , subkey . length ( ) - 1 ) ; if ( subkey . indexOf ( ":" ) != - 1 ) subkey = subkey . substring ( 0 , subkey . indexOf ( ":" ) ) ; } k += "|" + subkey ; } return substituteValueInExpression ( m . get ( k ) , v ) ; }
Restores expression with substituted default value
15,017
public static String substituteValueInExpression ( String expression , String newValue ) { ExpressionTemplate t = new ExpressionTemplate ( expression ) ; if ( newValue != null && ( getExpressionKey ( t . getTemplate ( ) ) == null || ( t . isComplex ( ) && ! newValue . equals ( t . getValue ( ) ) ) ) ) return newValue ; String result = t . getSubstitution ( ) ; if ( ! t . isComplex ( ) && newValue != null ) { int start = result . lastIndexOf ( ":$" ) ; start = result . indexOf ( ":" , start + 1 ) ; int end = result . indexOf ( "}" , start + 1 ) ; if ( start < 0 || end < 0 || start == result . lastIndexOf ( "${:}" ) + 2 ) return result ; result = result . substring ( 0 , start + 1 ) + newValue + result . substring ( end ) ; } return result ; }
Substitutes a default value in expression by a new one
15,018
public static String getExpressionKey ( String result ) { if ( result == null ) return null ; try { int from = result . indexOf ( startTag ) ; int to = result . indexOf ( endTag , from ) ; Integer . parseInt ( result . substring ( from + 5 , to ) ) ; return result . substring ( from , to + 5 ) ; } catch ( Exception e ) { return null ; } }
Get an entities map key from the string
15,019
private void writeXAResource ( Definition def , Writer out , int indent ) throws IOException { writeWithIndent ( out , indent , "/**\n" ) ; writeWithIndent ( out , indent , " * This method is called by the application server during crash recovery.\n" ) ; writeWithIndent ( out , indent , " *\n" ) ; writeWithIndent ( out , indent , " * @param specs An array of ActivationSpec JavaBeans \n" ) ; writeWithIndent ( out , indent , " * @throws ResourceException generic exception \n" ) ; writeWithIndent ( out , indent , " * @return An array of XAResource objects\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "public XAResource[] getXAResources(ActivationSpec[] specs)\n" ) ; writeWithIndent ( out , indent + 1 , "throws ResourceException" ) ; writeLeftCurlyBracket ( out , indent ) ; writeLogging ( def , out , indent + 1 , "trace" , "getXAResources" , "specs.toString()" ) ; writeWithIndent ( out , indent + 1 , "return null;" ) ; writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; }
Output getXAResources method
15,020
private void writeEndpointLifecycle ( Definition def , Writer out , int indent ) throws IOException { writeWithIndent ( out , indent , "/**\n" ) ; writeWithIndent ( out , indent , " * This is called during the activation of a message endpoint.\n" ) ; writeWithIndent ( out , indent , " *\n" ) ; writeWithIndent ( out , indent , " * @param endpointFactory A message endpoint factory instance.\n" ) ; writeWithIndent ( out , indent , " * @param spec An activation spec JavaBean instance.\n" ) ; writeWithIndent ( out , indent , " * @throws ResourceException generic exception \n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "public void endpointActivation(MessageEndpointFactory endpointFactory,\n" ) ; writeWithIndent ( out , indent + 1 , "ActivationSpec spec) throws ResourceException" ) ; writeLeftCurlyBracket ( out , indent ) ; if ( def . isSupportInbound ( ) ) { writeIndent ( out , indent + 1 ) ; out . write ( def . getActivationClass ( ) + " activation = new " + def . getActivationClass ( ) + "(this, endpointFactory, (" + def . getAsClass ( ) + ")spec);\n" ) ; writeWithIndent ( out , indent + 1 , "activations.put((" + def . getAsClass ( ) + ")spec, activation);\n" ) ; writeWithIndent ( out , indent + 1 , "activation.start();\n\n" ) ; } writeLogging ( def , out , indent + 1 , "trace" , "endpointActivation" , "endpointFactory" , "spec" ) ; writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; writeWithIndent ( out , indent , "/**\n" ) ; writeWithIndent ( out , indent , " * This is called when a message endpoint is deactivated. \n" ) ; writeWithIndent ( out , indent , " *\n" ) ; writeWithIndent ( out , indent , " * @param endpointFactory A message endpoint factory instance.\n" ) ; writeWithIndent ( out , indent , " * @param spec An activation spec JavaBean instance.\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "public void endpointDeactivation(MessageEndpointFactory endpointFactory,\n" ) ; writeWithIndent ( out , indent + 1 , "ActivationSpec spec)" ) ; writeLeftCurlyBracket ( out , indent ) ; if ( def . isSupportInbound ( ) ) { writeIndent ( out , indent + 1 ) ; out . write ( def . getActivationClass ( ) + " activation = activations.remove(spec);\n" ) ; writeWithIndent ( out , indent + 1 , "if (activation != null)\n" ) ; writeWithIndent ( out , indent + 2 , "activation.stop();\n\n" ) ; } writeLogging ( def , out , indent + 1 , "trace" , "endpointDeactivation" , "endpointFactory" ) ; writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; }
Output EndpointLifecycle method
15,021
private void writeGetAs ( Definition def , Writer out , int indent ) throws IOException { writeWithIndent ( out , indent , "/**\n" ) ; writeWithIndent ( out , indent , " * Get activation spec class\n" ) ; writeWithIndent ( out , indent , " * @return Activation spec\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "public " + def . getAsClass ( ) + " getActivationSpec()" ) ; writeLeftCurlyBracket ( out , indent ) ; writeWithIndent ( out , indent + 1 , "return spec;" ) ; writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; }
Output get activation spec method
15,022
private void writeMef ( Definition def , Writer out , int indent ) throws IOException { writeWithIndent ( out , indent , "/**\n" ) ; writeWithIndent ( out , indent , " * Get message endpoint factory\n" ) ; writeWithIndent ( out , indent , " * @return Message endpoint factory\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "public MessageEndpointFactory getMessageEndpointFactory()" ) ; writeLeftCurlyBracket ( out , indent ) ; writeWithIndent ( out , indent + 1 , "return endpointFactory;" ) ; writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; }
Output message endpoint factory method
15,023
public void unregisterWorkManager ( WorkManager wm ) { if ( wm != null ) { if ( wm . getName ( ) == null || wm . getName ( ) . trim ( ) . equals ( "" ) ) throw new IllegalArgumentException ( "The name of WorkManager is invalid: " + wm ) ; if ( trace ) log . tracef ( "Unregistering WorkManager: %s" , wm ) ; if ( workmanagers . keySet ( ) . contains ( wm . getName ( ) ) ) { workmanagers . remove ( wm . getName ( ) ) ; if ( wm instanceof DistributedWorkManager ) { WorkManagerEventQueue wmeq = WorkManagerEventQueue . getInstance ( ) ; List < WorkManagerEvent > events = wmeq . getEvents ( wm . getName ( ) ) ; events . clear ( ) ; } } } }
Unregister work manager
15,024
public void setDefaultWorkManager ( WorkManager wm ) { if ( trace ) log . tracef ( "Default WorkManager: %s" , wm ) ; String currentName = null ; if ( defaultWorkManager != null ) currentName = defaultWorkManager . getName ( ) ; defaultWorkManager = wm ; if ( wm != null ) { workmanagers . put ( wm . getName ( ) , wm ) ; } else if ( currentName != null ) { workmanagers . remove ( currentName ) ; } }
Set the default work manager
15,025
public DistributedWorkManager resolveDistributedWorkManager ( Address address ) { if ( trace ) { log . tracef ( "resolveDistributedWorkManager(%s)" , address ) ; log . tracef ( " ActiveWorkManagers: %s" , activeWorkmanagers ) ; } WorkManager wm = activeWorkmanagers . get ( address . getWorkManagerId ( ) ) ; if ( wm != null ) { if ( wm instanceof DistributedWorkManager ) { if ( trace ) log . tracef ( " WorkManager: %s" , wm ) ; return ( DistributedWorkManager ) wm ; } else { if ( trace ) log . tracef ( " WorkManager not distributable: %s" , wm ) ; return null ; } } try { WorkManager template = workmanagers . get ( address . getWorkManagerName ( ) ) ; if ( template != null ) { wm = template . clone ( ) ; wm . setId ( address . getWorkManagerId ( ) ) ; if ( wm instanceof DistributedWorkManager ) { DistributedWorkManager dwm = ( DistributedWorkManager ) wm ; dwm . initialize ( ) ; activeWorkmanagers . put ( address . getWorkManagerId ( ) , dwm ) ; refCountWorkmanagers . put ( address . getWorkManagerId ( ) , Integer . valueOf ( 0 ) ) ; if ( trace ) log . tracef ( "Created WorkManager: %s" , dwm ) ; return dwm ; } } } catch ( Throwable t ) { } return null ; }
Resolve a distributed work manager
15,026
public synchronized WorkManager createWorkManager ( String id , String name ) { if ( id == null || id . trim ( ) . equals ( "" ) ) throw new IllegalArgumentException ( "The id of WorkManager is invalid: " + id ) ; if ( activeWorkmanagers . keySet ( ) . contains ( id ) ) { if ( trace ) log . tracef ( "RefCounting WorkManager: %s" , id ) ; Integer i = refCountWorkmanagers . get ( id ) ; refCountWorkmanagers . put ( id , Integer . valueOf ( i . intValue ( ) + 1 ) ) ; WorkManager wm = activeWorkmanagers . get ( id ) ; if ( wm instanceof DistributedWorkManager ) { DistributedWorkManager dwm = ( DistributedWorkManager ) wm ; if ( dwm . getTransport ( ) != null ) dwm . getTransport ( ) . register ( new Address ( wm . getId ( ) , wm . getName ( ) , dwm . getTransport ( ) . getId ( ) ) ) ; } return wm ; } try { WorkManager template = null ; if ( name != null ) { template = workmanagers . get ( name ) ; } else { template = defaultWorkManager ; } if ( template == null ) throw new IllegalArgumentException ( "The WorkManager wasn't found: " + name ) ; WorkManager wm = template . clone ( ) ; wm . setId ( id ) ; if ( wm instanceof DistributedWorkManager ) { DistributedWorkManager dwm = ( DistributedWorkManager ) wm ; dwm . initialize ( ) ; if ( dwm . getTransport ( ) != null ) { dwm . getTransport ( ) . register ( new Address ( wm . getId ( ) , wm . getName ( ) , dwm . getTransport ( ) . getId ( ) ) ) ; try { ( ( DistributedWorkManager ) wm ) . getTransport ( ) . startup ( ) ; } catch ( Throwable t ) { throw new ApplicationServerInternalException ( "Unable to start the DWM Transport ID:" + ( ( DistributedWorkManager ) wm ) . getTransport ( ) . getId ( ) , t ) ; } } else { throw new ApplicationServerInternalException ( "DistributedWorkManager " + dwm . getName ( ) + " doesn't have a transport associated" ) ; } } activeWorkmanagers . put ( id , wm ) ; refCountWorkmanagers . put ( id , Integer . valueOf ( 1 ) ) ; if ( trace ) log . tracef ( "Created WorkManager: %s" , wm ) ; return wm ; } catch ( Throwable t ) { throw new IllegalStateException ( "The WorkManager couldn't be created: " + name , t ) ; } }
Create a work manager
15,027
public synchronized void removeWorkManager ( String id ) { if ( id == null || id . trim ( ) . equals ( "" ) ) throw new IllegalArgumentException ( "The id of WorkManager is invalid: " + id ) ; Integer i = refCountWorkmanagers . get ( id ) ; if ( i != null ) { int newValue = i . intValue ( ) - 1 ; if ( newValue == 0 ) { if ( trace ) log . tracef ( "Removed WorkManager: %s" , id ) ; WorkManager wm = activeWorkmanagers . get ( id ) ; if ( wm instanceof DistributedWorkManager ) { DistributedWorkManager dwm = ( DistributedWorkManager ) wm ; if ( dwm . getTransport ( ) != null ) dwm . getTransport ( ) . unregister ( new Address ( wm . getId ( ) , wm . getName ( ) , dwm . getTransport ( ) . getId ( ) ) ) ; } activeWorkmanagers . remove ( id ) ; refCountWorkmanagers . remove ( id ) ; } else { if ( trace ) log . tracef ( "DerefCount WorkManager: %s" , id ) ; refCountWorkmanagers . put ( id , Integer . valueOf ( newValue ) ) ; } } }
Remove a work manager
15,028
public synchronized void forceAdminObjects ( List < AdminObject > newContent ) { if ( newContent != null ) { this . adminobjects = new ArrayList < AdminObject > ( newContent ) ; } else { this . adminobjects = new ArrayList < AdminObject > ( 0 ) ; } }
Force adminobjects with new content . This method is thread safe
15,029
public void deltaTotalBlockingTime ( long delta ) { if ( enabled . get ( ) && delta > 0 ) { totalBlockingTime . addAndGet ( delta ) ; totalBlockingTimeInvocations . incrementAndGet ( ) ; if ( delta > maxWaitTime . get ( ) ) maxWaitTime . set ( delta ) ; } }
Add delta to total blocking timeout
15,030
public void deltaTotalCreationTime ( long delta ) { if ( enabled . get ( ) && delta > 0 ) { totalCreationTime . addAndGet ( delta ) ; if ( delta > maxCreationTime . get ( ) ) maxCreationTime . set ( delta ) ; } }
Add delta to total creation time
15,031
public void deltaTotalGetTime ( long delta ) { if ( enabled . get ( ) && delta > 0 ) { totalGetTime . addAndGet ( delta ) ; totalGetTimeInvocations . incrementAndGet ( ) ; if ( delta > maxGetTime . get ( ) ) maxGetTime . set ( delta ) ; } }
Add delta to total get time
15,032
public void deltaTotalPoolTime ( long delta ) { if ( enabled . get ( ) && delta > 0 ) { totalPoolTime . addAndGet ( delta ) ; totalPoolTimeInvocations . incrementAndGet ( ) ; if ( delta > maxPoolTime . get ( ) ) maxPoolTime . set ( delta ) ; } }
Add delta to total pool time
15,033
public void deltaTotalUsageTime ( long delta ) { if ( enabled . get ( ) && delta > 0 ) { totalUsageTime . addAndGet ( delta ) ; totalUsageTimeInvocations . incrementAndGet ( ) ; if ( delta > maxUsageTime . get ( ) ) maxUsageTime . set ( delta ) ; } }
Add delta to total usage time
15,034
@ SuppressWarnings ( "unchecked" ) private void verifyBeanValidation ( Object as ) throws Exception { if ( beanValidation != null ) { ValidatorFactory vf = null ; try { vf = beanValidation . getValidatorFactory ( ) ; Validator v = vf . getValidator ( ) ; Collection < String > l = bvGroups ; if ( l == null || l . isEmpty ( ) ) l = Arrays . asList ( javax . validation . groups . Default . class . getName ( ) ) ; Collection < Class < ? > > groups = new ArrayList < > ( ) ; for ( String clz : l ) { groups . add ( Class . forName ( clz , true , resourceAdapter . getClass ( ) . getClassLoader ( ) ) ) ; } Set failures = v . validate ( as , groups . toArray ( new Class < ? > [ groups . size ( ) ] ) ) ; if ( ! failures . isEmpty ( ) ) { throw new ConstraintViolationException ( "Violation for " + as , failures ) ; } } finally { if ( vf != null ) vf . close ( ) ; } } }
Verify activation spec against bean validation
15,035
private static void generateToCManagedConnection ( Map < String , TraceEvent > events , FileWriter fw ) throws Exception { writeString ( fw , "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"" ) ; writeEOL ( fw ) ; writeString ( fw , " \"http://www.w3.org/TR/html4/loose.dtd\">" ) ; writeEOL ( fw ) ; writeString ( fw , "<html>" ) ; writeEOL ( fw ) ; writeString ( fw , "<head>" ) ; writeEOL ( fw ) ; writeString ( fw , "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">" ) ; writeEOL ( fw ) ; writeString ( fw , "<title>Reference: ManagedConnection</title>" ) ; writeEOL ( fw ) ; writeString ( fw , "</head>" ) ; writeEOL ( fw ) ; writeString ( fw , "<body style=\"background: #D7D7D7;\">" ) ; writeEOL ( fw ) ; writeString ( fw , "<h1>Reference: ManagedConnection</h1>" ) ; writeEOL ( fw ) ; writeString ( fw , "<table>" ) ; writeEOL ( fw ) ; writeString ( fw , "<tr>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><b>ManagedConnection</b></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><b>ConnectionListener</b></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><b>ManagedConnectionPool</b></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><b>Pool</b></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "</tr>" ) ; writeEOL ( fw ) ; for ( Map . Entry < String , TraceEvent > entry : events . entrySet ( ) ) { TraceEvent te = entry . getValue ( ) ; writeString ( fw , "<tr>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><a href=\"" + te . getPool ( ) + "/" + te . getConnectionListener ( ) + "/index.html\">" + te . getPayload1 ( ) + "</a></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><a href=\"" + te . getPool ( ) + "/" + te . getConnectionListener ( ) + "/index.html\">" + te . getConnectionListener ( ) + "</a></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td>" + te . getManagedConnectionPool ( ) + "</td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><a href=\"" + te . getPool ( ) + "/index.html\">" + te . getPool ( ) + "</a></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "</tr>" ) ; writeEOL ( fw ) ; } writeString ( fw , "</table>" ) ; writeEOL ( fw ) ; writeString ( fw , "<p>" ) ; writeEOL ( fw ) ; writeString ( fw , "<a href=\"index.html\">Back</a>" ) ; writeEOL ( fw ) ; writeString ( fw , "</body>" ) ; writeEOL ( fw ) ; writeString ( fw , "</html>" ) ; writeEOL ( fw ) ; }
Write toc - mc . html for managed connections
15,036
private static void generateToCConnectionListener ( Map < String , List < TraceEvent > > events , FileWriter fw ) throws Exception { writeString ( fw , "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"" ) ; writeEOL ( fw ) ; writeString ( fw , " \"http://www.w3.org/TR/html4/loose.dtd\">" ) ; writeEOL ( fw ) ; writeString ( fw , "<html>" ) ; writeEOL ( fw ) ; writeString ( fw , "<head>" ) ; writeEOL ( fw ) ; writeString ( fw , "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">" ) ; writeEOL ( fw ) ; writeString ( fw , "<title>Reference: ConnectionListener</title>" ) ; writeEOL ( fw ) ; writeString ( fw , "</head>" ) ; writeEOL ( fw ) ; writeString ( fw , "<body style=\"background: #D7D7D7;\">" ) ; writeEOL ( fw ) ; writeString ( fw , "<h1>Reference: ConnectionListener</h1>" ) ; writeEOL ( fw ) ; writeString ( fw , "<table>" ) ; writeEOL ( fw ) ; writeString ( fw , "<tr>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><b>ConnectionListener</b></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><b>ManagedConnectionPool</b></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><b>Pool</b></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "</tr>" ) ; writeEOL ( fw ) ; for ( Map . Entry < String , List < TraceEvent > > entry : events . entrySet ( ) ) { TraceEvent te = entry . getValue ( ) . get ( 0 ) ; writeString ( fw , "<tr>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><a href=\"" + te . getPool ( ) + "/" + te . getConnectionListener ( ) + "/index.html\">" + te . getConnectionListener ( ) + "</a></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td>" + te . getManagedConnectionPool ( ) + "</td>" ) ; writeEOL ( fw ) ; writeString ( fw , "<td><a href=\"" + te . getPool ( ) + "/index.html\">" + te . getPool ( ) + "</a></td>" ) ; writeEOL ( fw ) ; writeString ( fw , "</tr>" ) ; writeEOL ( fw ) ; } writeString ( fw , "</table>" ) ; writeEOL ( fw ) ; writeString ( fw , "<p>" ) ; writeEOL ( fw ) ; writeString ( fw , "<a href=\"index.html\">Back</a>" ) ; writeEOL ( fw ) ; writeString ( fw , "</body>" ) ; writeEOL ( fw ) ; writeString ( fw , "</html>" ) ; writeEOL ( fw ) ; }
Write toc - cl . html for connection listeners
15,037
public void store ( Activation metadata , XMLStreamWriter writer ) throws Exception { if ( metadata != null && writer != null ) { writer . writeStartElement ( XML . ELEMENT_IRONJACAMAR ) ; storeCommon ( metadata , writer ) ; writer . writeEndElement ( ) ; } }
Store an ironjacamar . xml file
15,038
private static File extract ( File file , File directory ) throws IOException { if ( file == null ) throw new IllegalArgumentException ( "File is null" ) ; if ( directory == null ) throw new IllegalArgumentException ( "Directory is null" ) ; File target = new File ( directory , file . getName ( ) ) ; if ( target . exists ( ) ) recursiveDelete ( target ) ; if ( ! target . mkdirs ( ) ) throw new IOException ( "Could not create " + target ) ; JarFile jar = null ; try { jar = new JarFile ( file ) ; Enumeration < JarEntry > entries = jar . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry je = entries . nextElement ( ) ; File copy = new File ( target , je . getName ( ) ) ; if ( ! je . isDirectory ( ) ) { InputStream in = null ; OutputStream out = null ; if ( copy . getParentFile ( ) != null && ! copy . getParentFile ( ) . exists ( ) ) { if ( ! copy . getParentFile ( ) . mkdirs ( ) ) throw new IOException ( "Could not create " + copy . getParentFile ( ) ) ; } try { in = new BufferedInputStream ( jar . getInputStream ( je ) ) ; out = new BufferedOutputStream ( new FileOutputStream ( copy ) ) ; byte [ ] buffer = new byte [ 4096 ] ; for ( ; ; ) { int nBytes = in . read ( buffer ) ; if ( nBytes <= 0 ) break ; out . write ( buffer , 0 , nBytes ) ; } out . flush ( ) ; } finally { try { if ( out != null ) out . close ( ) ; } catch ( IOException ignore ) { } try { if ( in != null ) in . close ( ) ; } catch ( IOException ignore ) { } } } else { if ( ! copy . exists ( ) ) { if ( ! copy . mkdirs ( ) ) throw new IOException ( "Could not create " + copy ) ; } else { if ( ! copy . isDirectory ( ) ) throw new IOException ( copy + " isn't a directory" ) ; } } } } finally { try { if ( jar != null ) jar . close ( ) ; } catch ( IOException ignore ) { } } return target ; }
Extract a JAR type file
15,039
private void parse ( ) { template = text ; if ( StringUtils . isEmptyTrimmed ( template ) ) return ; int index = 0 ; while ( template . indexOf ( "${" ) != - 1 ) { int from = template . lastIndexOf ( "${" ) ; int to = template . indexOf ( "}" , from + 2 ) ; if ( to == - 1 ) { template = text ; complex = false ; entities . clear ( ) ; return ; } int dv = template . indexOf ( ":" , from + 2 ) ; if ( dv != - 1 && dv > to ) { dv = - 1 ; } String systemProperty = null ; String defaultValue = null ; String s = template . substring ( from + 2 , to ) ; if ( "/" . equals ( s ) ) { systemProperty = File . separator ; } else if ( ":" . equals ( s ) ) { systemProperty = File . pathSeparator ; dv = - 1 ; } else { systemProperty = SecurityActions . getSystemProperty ( s ) ; } if ( dv != - 1 ) { s = template . substring ( from + 2 , dv ) ; systemProperty = SecurityActions . getSystemProperty ( s ) ; defaultValue = template . substring ( dv + 1 , to ) ; } String prefix = "" ; String postfix = "" ; String key = StringUtils . createKey ( index ++ ) ; updateComplex ( defaultValue ) ; entities . put ( key , new Expression ( s , defaultValue , systemProperty ) ) ; if ( from != 0 ) { prefix = template . substring ( 0 , from ) ; } if ( to + 1 < template . length ( ) ) { postfix = template . substring ( to + 1 ) ; } template = prefix + key + postfix ; } updateComplex ( template ) ; }
Parse a text and get a template and expression entities
15,040
private void updateComplex ( String string ) { if ( string != null && StringUtils . getExpressionKey ( string ) != null && ! string . equals ( StringUtils . getExpressionKey ( string ) ) ) { complex = true ; } }
Updates the complexness of the expression based on a String value
15,041
private String resolveTemplate ( boolean toValue ) { String result = template ; if ( StringUtils . isEmptyTrimmed ( result ) ) return result ; String key ; while ( ( key = StringUtils . getExpressionKey ( result ) ) != null ) { String subs ; Expression ex = entities . get ( key ) ; String nKey = StringUtils . getExpressionKey ( ex . getDefaultValue ( ) ) ; if ( toValue ) subs = ex . getValue ( ) ; else if ( nKey != null && ex . getResolvedValue ( ) != null && ex . getDefaultValue ( ) . equals ( nKey ) ) { entities . get ( nKey ) . setResolvedValue ( ex . getResolvedValue ( ) ) ; subs = ex . toString ( ) ; } else subs = ex . toSubstitution ( ) ; result = result . replace ( key , subs ) ; } return result ; }
Resolves the template to the String value depending on boolean switch
15,042
public Connector merge ( Connector connector , AnnotationRepository annotationRepository , ClassLoader classLoader ) throws Exception { if ( connector == null || ( connector . getVersion ( ) == Version . V_16 || connector . getVersion ( ) == Version . V_17 ) ) { boolean isMetadataComplete = false ; if ( connector != null ) { isMetadataComplete = connector . isMetadataComplete ( ) ; } if ( connector == null || ! isMetadataComplete ) { if ( connector == null ) { Connector annotationsConnector = process ( annotationRepository , null , classLoader ) ; connector = annotationsConnector ; } else { Connector annotationsConnector = process ( annotationRepository , ( ( ResourceAdapter ) connector . getResourceadapter ( ) ) . getResourceadapterClass ( ) , classLoader ) ; connector = connector . merge ( annotationsConnector ) ; } } } return connector ; }
Scan for annotations in the URLs specified
15,043
private boolean hasAnnotation ( Class c , Class targetClass , AnnotationRepository annotationRepository ) { Collection < Annotation > values = annotationRepository . getAnnotation ( targetClass ) ; if ( values == null ) return false ; for ( Annotation annotation : values ) { if ( annotation . getClassName ( ) != null && annotation . getClassName ( ) . equals ( c . getName ( ) ) ) return true ; } return false ; }
hasAnnotation if class c contains annotation targetClass
15,044
private String getConfigPropertyName ( Annotation annotation ) throws ClassNotFoundException , NoSuchFieldException , NoSuchMethodException { if ( annotation . isOnField ( ) ) { return annotation . getMemberName ( ) ; } else if ( annotation . isOnMethod ( ) ) { String name = annotation . getMemberName ( ) ; if ( name . startsWith ( "set" ) ) { name = name . substring ( 3 ) ; } else if ( name . startsWith ( "get" ) ) { name = name . substring ( 3 ) ; } else if ( name . startsWith ( "is" ) ) { name = name . substring ( 2 ) ; } if ( name . length ( ) > 1 ) { return Character . toLowerCase ( name . charAt ( 0 ) ) + name . substring ( 1 ) ; } else { return Character . toString ( Character . toLowerCase ( name . charAt ( 0 ) ) ) ; } } throw new IllegalArgumentException ( bundle . unknownAnnotation ( annotation ) ) ; }
Get the config - property - name for an annotation
15,045
@ SuppressWarnings ( "unchecked" ) private String getConfigPropertyType ( Annotation annotation , Class < ? > type , ClassLoader classLoader ) throws ClassNotFoundException , ValidateException { if ( annotation . isOnField ( ) ) { Class clz = Class . forName ( annotation . getClassName ( ) , true , classLoader ) ; while ( ! Object . class . equals ( clz ) ) { try { Field field = SecurityActions . getDeclaredField ( clz , annotation . getMemberName ( ) ) ; if ( type == null || type . equals ( Object . class ) || type . equals ( field . getType ( ) ) ) { return field . getType ( ) . getName ( ) ; } else { throw new ValidateException ( bundle . wrongAnnotationType ( annotation ) ) ; } } catch ( NoSuchFieldException nsfe ) { clz = clz . getSuperclass ( ) ; } } } else if ( annotation . isOnMethod ( ) ) { Class clz = Class . forName ( annotation . getClassName ( ) , true , classLoader ) ; Class [ ] parameters = null ; if ( annotation . getParameterTypes ( ) != null ) { parameters = new Class [ annotation . getParameterTypes ( ) . size ( ) ] ; for ( int i = 0 ; i < annotation . getParameterTypes ( ) . size ( ) ; i ++ ) { String parameter = annotation . getParameterTypes ( ) . get ( i ) ; parameters [ i ] = Class . forName ( parameter , true , classLoader ) ; } } while ( ! Object . class . equals ( clz ) ) { try { Method method = SecurityActions . getDeclaredMethod ( clz , annotation . getMemberName ( ) , parameters ) ; if ( void . class . equals ( method . getReturnType ( ) ) ) { if ( parameters != null && parameters . length > 0 ) { if ( type == null || type . equals ( Object . class ) || type . equals ( parameters [ 0 ] ) ) { return parameters [ 0 ] . getName ( ) ; } else { throw new ValidateException ( bundle . wrongAnnotationType ( annotation ) ) ; } } } else { if ( type == null || type . equals ( Object . class ) || type . equals ( method . getReturnType ( ) ) ) { return method . getReturnType ( ) . getName ( ) ; } else { throw new ValidateException ( bundle . wrongAnnotationType ( annotation ) ) ; } } } catch ( NoSuchMethodException nsme ) { clz = clz . getSuperclass ( ) ; } } } throw new IllegalArgumentException ( bundle . unknownAnnotation ( annotation ) ) ; }
Get the config - property - type for an annotation
15,046
private Set < String > getClasses ( String name , ClassLoader cl ) { Set < String > result = new HashSet < String > ( ) ; try { Class < ? > clz = Class . forName ( name , true , cl ) ; while ( ! Object . class . equals ( clz ) ) { result . add ( clz . getName ( ) ) ; clz = clz . getSuperclass ( ) ; } } catch ( Throwable t ) { log . debugf ( "Couldn't load: %s" , name ) ; } return result ; }
Get the class names for a class and all of its super classes
15,047
private boolean hasNotNull ( AnnotationRepository annotationRepository , Annotation annotation ) { Collection < Annotation > values = annotationRepository . getAnnotation ( javax . validation . constraints . NotNull . class ) ; if ( values == null || values . isEmpty ( ) ) return false ; for ( Annotation notNullAnnotation : values ) { if ( notNullAnnotation . getClassName ( ) . equals ( annotation . getClassName ( ) ) && notNullAnnotation . getMemberName ( ) . equals ( annotation . getMemberName ( ) ) ) return true ; } return false ; }
Has a NotNull annotation attached
15,048
protected ConnectionListener validateConnectionListener ( Collection < ConnectionListener > listeners , ConnectionListener cl , int newState ) { ManagedConnectionFactory mcf = pool . getConnectionManager ( ) . getManagedConnectionFactory ( ) ; if ( mcf instanceof ValidatingManagedConnectionFactory ) { ValidatingManagedConnectionFactory vcf = ( ValidatingManagedConnectionFactory ) mcf ; try { Set candidateSet = Collections . singleton ( cl . getManagedConnection ( ) ) ; candidateSet = vcf . getInvalidConnections ( candidateSet ) ; if ( candidateSet != null && ! candidateSet . isEmpty ( ) ) { if ( Tracer . isEnabled ( ) ) Tracer . destroyConnectionListener ( pool . getConfiguration ( ) . getId ( ) , this , cl , false , false , true , false , false , false , false , Tracer . isRecordCallstacks ( ) ? new Throwable ( "CALLSTACK" ) : null ) ; destroyAndRemoveConnectionListener ( cl , listeners ) ; } else { cl . validated ( ) ; if ( cl . changeState ( VALIDATION , newState ) ) { return cl ; } else { if ( Tracer . isEnabled ( ) ) Tracer . destroyConnectionListener ( pool . getConfiguration ( ) . getId ( ) , this , cl , false , false , true , false , false , false , false , Tracer . isRecordCallstacks ( ) ? new Throwable ( "CALLSTACK" ) : null ) ; destroyAndRemoveConnectionListener ( cl , listeners ) ; } } } catch ( ResourceException re ) { if ( Tracer . isEnabled ( ) ) Tracer . destroyConnectionListener ( pool . getConfiguration ( ) . getId ( ) , this , cl , false , false , true , false , false , false , false , Tracer . isRecordCallstacks ( ) ? new Throwable ( "CALLSTACK" ) : null ) ; destroyAndRemoveConnectionListener ( cl , listeners ) ; } } else { log . debug ( "mcf is not instance of ValidatingManagedConnectionFactory" ) ; if ( cl . changeState ( VALIDATION , newState ) ) { return cl ; } else { if ( Tracer . isEnabled ( ) ) Tracer . destroyConnectionListener ( pool . getConfiguration ( ) . getId ( ) , this , cl , false , false , true , false , false , false , false , Tracer . isRecordCallstacks ( ) ? new Throwable ( "CALLSTACK" ) : null ) ; destroyAndRemoveConnectionListener ( cl , listeners ) ; } } return null ; }
Validate a connection listener
15,049
protected void destroyAndRemoveConnectionListener ( ConnectionListener cl , Collection < ConnectionListener > listeners ) { try { pool . destroyConnectionListener ( cl ) ; } catch ( ResourceException e ) { cl . setState ( ZOMBIE ) ; } finally { listeners . remove ( cl ) ; } }
Destroy and remove a connection listener
15,050
protected ConnectionListener findConnectionListener ( ManagedConnection mc , Object c , Collection < ConnectionListener > listeners ) { for ( ConnectionListener cl : listeners ) { if ( cl . getManagedConnection ( ) . equals ( mc ) && ( c == null || cl . getConnections ( ) . contains ( c ) ) ) return cl ; } return null ; }
Find a ConnectionListener instance
15,051
protected ConnectionListener removeConnectionListener ( boolean free , Collection < ConnectionListener > listeners ) { if ( free ) { for ( ConnectionListener cl : listeners ) { if ( cl . changeState ( FREE , IN_USE ) ) return cl ; } } else { for ( ConnectionListener cl : listeners ) { if ( cl . getState ( ) == IN_USE ) return cl ; } } return null ; }
Remove a free ConnectionListener instance
15,052
public Connector getStandardMetaData ( File root ) throws Exception { Connector result = null ; File metadataFile = new File ( root , "/META-INF/ra.xml" ) ; if ( metadataFile . exists ( ) ) { InputStream input = null ; String url = metadataFile . getAbsolutePath ( ) ; try { long start = System . currentTimeMillis ( ) ; input = new FileInputStream ( metadataFile ) ; XMLStreamReader xsr = XMLInputFactory . newInstance ( ) . createXMLStreamReader ( input ) ; result = ( new RaParser ( ) ) . parse ( xsr ) ; log . debugf ( "Total parse for %s took %d ms" , url , ( System . currentTimeMillis ( ) - start ) ) ; } catch ( Exception e ) { log . parsingErrorRaXml ( url , e ) ; throw e ; } finally { if ( input != null ) input . close ( ) ; } } else { log . tracef ( "metadata file %s does not exist" , metadataFile . toString ( ) ) ; } return result ; }
Get the JCA standard metadata
15,053
public Activation getIronJacamarMetaData ( File root ) throws Exception { Activation result = null ; File metadataFile = new File ( root , "/META-INF/ironjacamar.xml" ) ; if ( metadataFile . exists ( ) ) { InputStream input = null ; String url = metadataFile . getAbsolutePath ( ) ; try { long start = System . currentTimeMillis ( ) ; input = new FileInputStream ( metadataFile ) ; XMLStreamReader xsr = XMLInputFactory . newInstance ( ) . createXMLStreamReader ( input ) ; result = ( new IronJacamarParser ( ) ) . parse ( xsr ) ; log . debugf ( "Total parse for %s took %d ms" , url , ( System . currentTimeMillis ( ) - start ) ) ; } catch ( Exception e ) { log . parsingErrorIronJacamarXml ( url , e ) ; throw e ; } finally { if ( input != null ) input . close ( ) ; } } return result ; }
Get the IronJacamar specific metadata
15,054
public synchronized void forceConnectionDefinitions ( List < ConnectionDefinition > newContent ) { if ( newContent != null ) { this . connectionDefinition = new ArrayList < ConnectionDefinition > ( newContent ) ; } else { this . connectionDefinition = new ArrayList < ConnectionDefinition > ( 0 ) ; } }
Force connectionDefinition with new content . This method is thread safe
15,055
static InputStream getResourceAsStream ( final String name ) { if ( System . getSecurityManager ( ) == null ) return Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( name ) ; return AccessController . doPrivileged ( new PrivilegedAction < InputStream > ( ) { public InputStream run ( ) { return Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( name ) ; } } ) ; }
Get the input stream for a resource in the context class loader
15,056
static WorkClassLoader createWorkClassLoader ( final ClassBundle cb ) { return AccessController . doPrivileged ( new PrivilegedAction < WorkClassLoader > ( ) { public WorkClassLoader run ( ) { return new WorkClassLoader ( cb ) ; } } ) ; }
Create a WorkClassLoader
15,057
public static TraceEvent parse ( String data ) { String [ ] raw = data . split ( "-" ) ; String header = raw [ 0 ] ; String p = raw [ 1 ] ; String m = raw [ 2 ] ; long tid = Long . parseLong ( raw [ 3 ] ) ; int t = Integer . parseInt ( raw [ 4 ] ) ; long ts = Long . parseLong ( raw [ 5 ] ) ; String c = raw [ 6 ] ; String pyl = "" ; String py2 = "" ; if ( raw . length >= 8 ) pyl = raw [ 7 ] ; if ( raw . length >= 9 ) py2 = raw [ 8 ] ; return new TraceEvent ( p , m , tid , t , ts , c , pyl , py2 ) ; }
Parse a trace event
15,058
private void writeEIS ( Definition def , Writer out , int indent ) throws IOException { writeWithIndent ( out , indent , "/**\n" ) ; writeWithIndent ( out , indent , " * Returns product name of the underlying EIS instance connected\n" ) ; writeWithIndent ( out , indent , " *\n" ) ; writeWithIndent ( out , indent , " * @return Product name of the EIS instance\n" ) ; writeWithIndent ( out , indent , " * @throws ResourceException Failed to get the information\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "@Override\n" ) ; writeWithIndent ( out , indent , "public String getEISProductName() throws ResourceException" ) ; writeLeftCurlyBracket ( out , indent ) ; writeWithIndent ( out , indent + 1 , "return null; //TODO" ) ; writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; writeWithIndent ( out , indent , "/**\n" ) ; writeWithIndent ( out , indent , " * Returns product version of the underlying EIS instance.\n" ) ; writeWithIndent ( out , indent , " *\n" ) ; writeWithIndent ( out , indent , " * @return Product version of the EIS instance\n" ) ; writeWithIndent ( out , indent , " * @throws ResourceException Failed to get the information\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "@Override\n" ) ; writeWithIndent ( out , indent , "public String getEISProductVersion() throws ResourceException" ) ; writeLeftCurlyBracket ( out , indent ) ; writeWithIndent ( out , indent + 1 , "return null; //TODO" ) ; writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; }
Output eis info method
15,059
static ValidatorFactory createValidatorFactory ( ) { Configuration configuration = Validation . byDefaultProvider ( ) . configure ( ) ; Configuration < ? > conf = configuration . traversableResolver ( new IronJacamarTraversableResolver ( ) ) ; return conf . buildValidatorFactory ( ) ; }
Create a validator factory
15,060
Builder prepareNextPage ( ) { int offset = this . offset + pageSize ; validateOffset ( offset ) ; this . offset = offset ; return builder ; }
Updates offset to point at next data page by adding pageSize .
15,061
Builder preparePreviousPage ( ) { int offset = this . offset - pageSize ; validateOffset ( offset ) ; this . offset = offset ; return builder ; }
Updates offset to point at previous data page by subtracting pageSize .
15,062
public void handleFault ( BackendlessFault fault ) { progressDialog . cancel ( ) ; Toast . makeText ( context , fault . getMessage ( ) , Toast . LENGTH_SHORT ) . show ( ) ; }
This override is optional
15,063
public static Map < String , Object > serializeToMap ( Object entity ) { IObjectSerializer serializer = getSerializer ( entity . getClass ( ) ) ; return ( Map < String , Object > ) serializer . serializeToMap ( entity , new HashMap < Object , Map < String , Object > > ( ) ) ; }
Serializes Object to Map using WebOrb s serializer .
15,064
public static String getSimpleName ( Class clazz ) { IObjectSerializer serializer = getSerializer ( clazz ) ; return serializer . getClassName ( clazz ) ; }
Uses pluggable serializers to locate one for the class and get the name which should be used for serialization . The name must match the table name where instance of clazz are persisted
15,065
private Object getOrMakeSerializedObject ( Object entityEntryValue , Map < Object , Map < String , Object > > serializedCache ) { if ( serializedCache . containsKey ( entityEntryValue ) ) { return serializedCache . get ( entityEntryValue ) ; } else { return serializeToMap ( entityEntryValue , serializedCache ) ; } }
Returns serialized object from cache or serializes object if it s not present in cache .
15,066
public static void serializeUserProperties ( BackendlessUser user ) { Map < String , Object > serializedProperties = user . getProperties ( ) ; Set < Map . Entry < String , Object > > properties = serializedProperties . entrySet ( ) ; for ( Map . Entry < String , Object > property : properties ) { Object propertyValue = property . getValue ( ) ; if ( propertyValue != null && ! propertyValue . getClass ( ) . isArray ( ) && ! propertyValue . getClass ( ) . isEnum ( ) && ! isBelongsJdk ( propertyValue . getClass ( ) ) ) { property . setValue ( serializeToMap ( propertyValue ) ) ; } } user . setProperties ( serializedProperties ) ; }
Serializes entities inside BackendlessUser properties .
15,067
private static IObjectSerializer getSerializer ( Class clazz ) { Iterator < Map . Entry < Class , IObjectSerializer > > iterator = serializers . entrySet ( ) . iterator ( ) ; IObjectSerializer serializer = DEFAULT_SERIALIZER ; while ( iterator . hasNext ( ) ) { Map . Entry < Class , IObjectSerializer > entry = iterator . next ( ) ; if ( entry . getKey ( ) . isAssignableFrom ( clazz ) ) { serializer = entry . getValue ( ) ; break ; } } return serializer ; }
Returns a serializer for the class
15,068
public void setCurrentUser ( BackendlessUser user ) { if ( currentUser == null ) currentUser = user ; else currentUser . setProperties ( user . getProperties ( ) ) ; }
Sets the properties of the given user to current one .
15,069
public MessageStatus publish ( String channelName , Object message ) { return publish ( channelName , message , new PublishOptions ( ) ) ; }
Publishes message to specified channel . The message is not a push notification it does not have any headers and does not go into any subtopics .
15,070
public static Object getFieldValue ( Object object , String lowerKey , String upperKey ) { if ( object == null ) return null ; Method getMethod = getMethod ( object , "get" + lowerKey ) ; if ( getMethod == null ) getMethod = getMethod ( object , "get" + upperKey ) ; if ( getMethod == null ) getMethod = getMethod ( object , "is" + lowerKey ) ; if ( getMethod == null ) getMethod = getMethod ( object , "is" + upperKey ) ; if ( getMethod != null ) try { return getMethod . invoke ( object , new Object [ 0 ] ) ; } catch ( Throwable t ) { } try { Field field = getField ( object . getClass ( ) , lowerKey ) ; field . setAccessible ( true ) ; return field . get ( object ) ; } catch ( IllegalAccessException e ) { return null ; } catch ( NoSuchFieldException e1 ) { try { Field field = getField ( object . getClass ( ) , upperKey ) ; field . setAccessible ( true ) ; return field . get ( object ) ; } catch ( Throwable throwable ) { } return null ; } }
Retrieves the value of the field with given name from the given object .
15,071
public static boolean hasField ( Class clazz , String fieldName ) { try { clazz . getDeclaredField ( fieldName ) ; return true ; } catch ( NoSuchFieldException nfe ) { if ( clazz . getSuperclass ( ) != null ) { return hasField ( clazz . getSuperclass ( ) , fieldName ) ; } else { return false ; } } }
Checks whether given class contains a field with given name . Recursively checks superclasses .
15,072
public void afterMoveToRepository ( RunnerContext context , String fileUrlLocation , ExecutionResult < String > result ) throws Exception { }
Use afterUpload method
15,073
public ImmutableList < T > toList ( ) { return this . foldAbelian ( ( v , acc ) -> acc . cons ( v ) , ImmutableList . empty ( ) ) ; }
Does not guarantee ordering of elements in resulting list .
15,074
protected void setArrayValue ( final PreparedStatement statement , final int i , Connection connection , Object [ ] array ) throws SQLException { if ( array == null || ( isEmptyStoredAsNull ( ) && array . length == 0 ) ) { statement . setNull ( i , Types . ARRAY ) ; } else { statement . setArray ( i , connection . createArrayOf ( getDialectPrimitiveName ( ) , array ) ) ; } }
Stores the array conforming to the EMPTY_IS_NULL directive .
15,075
public final ArrayList < A > toArrayList ( ) { ArrayList < A > list = new ArrayList < > ( this . length ) ; ImmutableList < A > l = this ; for ( int i = 0 ; i < length ; i ++ ) { list . add ( ( ( NonEmptyImmutableList < A > ) l ) . head ) ; l = ( ( NonEmptyImmutableList < A > ) l ) . tail ; } return list ; }
Converts this list into a java . util . ArrayList .
15,076
public final LinkedList < A > toLinkedList ( ) { LinkedList < A > list = new LinkedList < > ( ) ; ImmutableList < A > l = this ; for ( int i = 0 ; i < length ; i ++ ) { list . add ( ( ( NonEmptyImmutableList < A > ) l ) . head ) ; l = ( ( NonEmptyImmutableList < A > ) l ) . tail ; } return list ; }
Converts this list into a java . util . LinkedList .
15,077
public < T > Get < T > read ( Class < T > cls ) throws APIException { return new Get < T > ( this , getDF ( cls ) ) ; }
Returns a Get Object ... same as get
15,078
public < T > Get < T > get ( Class < T > cls ) throws APIException { return new Get < T > ( this , getDF ( cls ) ) ; }
Returns a Get Object ... same as read
15,079
public < T > Post < T > post ( Class < T > cls ) throws APIException { return new Post < T > ( this , getDF ( cls ) ) ; }
Returns a Post Object ... same as create
15,080
public < T > Post < T > create ( Class < T > cls ) throws APIException { return new Post < T > ( this , getDF ( cls ) ) ; }
Returns a Post Object ... same as post
15,081
public < T > Put < T > put ( Class < T > cls ) throws APIException { return new Put < T > ( this , getDF ( cls ) ) ; }
Returns a Put Object ... same as update
15,082
public < T > Put < T > update ( Class < T > cls ) throws APIException { return new Put < T > ( this , getDF ( cls ) ) ; }
Returns a Put Object ... same as put
15,083
public < T > Delete < T > delete ( Class < T > cls ) throws APIException { return new Delete < T > ( this , getDF ( cls ) ) ; }
Returns a Delete Object
15,084
public void set ( TafResp tafResp , Lur lur ) { principal = tafResp . getPrincipal ( ) ; access = tafResp . getAccess ( ) ; this . lur = lur ; }
Allow setting of tafResp and lur after construction
15,085
public void invalidate ( String id ) { if ( lur instanceof EpiLur ) { ( ( EpiLur ) lur ) . remove ( id ) ; } else if ( lur instanceof CachingLur ) { ( ( CachingLur < ? > ) lur ) . remove ( id ) ; } }
Add a feature
15,086
public < RET > RET same ( SecuritySetter < HttpURLConnection > ss , Retryable < RET > retryable ) throws APIException , CadiException , LocatorException { RET ret = null ; boolean retry = true ; int retries = 0 ; Rcli < HttpURLConnection > client = retryable . lastClient ( ) ; try { do { if ( retryable . item ( ) == null ) { retryable . item ( loc . best ( ) ) ; retryable . lastClient = null ; } if ( client == null ) { Item item = retryable . item ( ) ; URI uri = loc . get ( item ) ; if ( uri == null ) { loc . invalidate ( retryable . item ( ) ) ; if ( loc . hasItems ( ) ) { retryable . item ( loc . next ( retryable . item ( ) ) ) ; continue ; } else { throw new LocatorException ( "No clients available for " + loc . toString ( ) ) ; } } client = new HRcli ( this , uri , item , ss ) . connectionTimeout ( connectionTimeout ) . readTimeout ( readTimeout ) . apiVersion ( apiVersion ) ; } else { client . setSecuritySetter ( ss ) ; } retry = false ; try { ret = retryable . code ( client ) ; } catch ( APIException | CadiException e ) { Item item = retryable . item ( ) ; loc . invalidate ( item ) ; retryable . item ( loc . next ( item ) ) ; try { Throwable ec = e . getCause ( ) ; if ( ec instanceof java . net . ConnectException ) { if ( client != null && ++ retries < 2 ) { access . log ( Level . WARN , "Connection refused, trying next available service" ) ; retry = true ; } else { throw new CadiException ( "Connection refused, no more available connections to try" ) ; } } else if ( ec instanceof SSLHandshakeException ) { retryable . item ( null ) ; throw e ; } else if ( ec instanceof SocketException ) { if ( "java.net.SocketException: Connection reset" . equals ( ec . getMessage ( ) ) ) { access . log ( Level . ERROR , ec . getMessage ( ) , " can mean Certificate Expiration or TLS Protocol issues" ) ; } retryable . item ( null ) ; throw e ; } else { retryable . item ( null ) ; throw e ; } } finally { client = null ; } } catch ( ConnectException e ) { Item item = retryable . item ( ) ; loc . invalidate ( item ) ; retryable . item ( loc . next ( item ) ) ; } } while ( retry ) ; } finally { retryable . lastClient = client ; } return ret ; }
Reuse the same service . This is helpful for multiple calls that change service side cached data so that there is not a speed issue .
15,087
protected int seg ( Cached < ? , ? > cache , Object ... fields ) { return cache == null ? 0 : cache . invalidate ( CachedDAO . keyFromObjs ( fields ) ) ; }
be treated by system as fields expected in Tables
15,088
public Result < DATA > create ( TRANS trans , DATA data ) { if ( createPS == null ) { Result . err ( Result . ERR_NotImplemented , "Create is disabled for %s" , getClass ( ) . getSimpleName ( ) ) ; } if ( async ) { Result < ResultSetFuture > rs = createPS . execAsync ( trans , C_TEXT , data ) ; if ( rs . notOK ( ) ) { return Result . err ( rs ) ; } } else { Result < ResultSet > rs = createPS . exec ( trans , C_TEXT , data ) ; if ( rs . notOK ( ) ) { return Result . err ( rs ) ; } } wasModified ( trans , CRUD . create , data ) ; return Result . ok ( data ) ; }
Given a DATA object extract the individual elements from the Data into an Object Array for the execute element .
15,089
public Result < List < DATA > > read ( TRANS trans , DATA data ) { if ( readPS == null ) { Result . err ( Result . ERR_NotImplemented , "Read is disabled for %s" , getClass ( ) . getSimpleName ( ) ) ; } return readPS . read ( trans , R_TEXT , data ) ; }
Read the Unique Row associated with Full Keys
15,090
public Result < Void > delete ( TRANS trans , DATA data , boolean reread ) { if ( deletePS == null ) { Result . err ( Result . ERR_NotImplemented , "Delete is disabled for %s" , getClass ( ) . getSimpleName ( ) ) ; } if ( reread ) { Result < List < DATA > > rd = read ( trans , data ) ; if ( rd . notOK ( ) ) { return Result . err ( rd ) ; } if ( rd . isEmpty ( ) ) { return Result . err ( Status . ERR_NotFound , "Not Found" ) ; } for ( DATA d : rd . value ) { if ( async ) { Result < ResultSetFuture > rs = deletePS . execAsync ( trans , D_TEXT , d ) ; if ( rs . notOK ( ) ) { return Result . err ( rs ) ; } } else { Result < ResultSet > rs = deletePS . exec ( trans , D_TEXT , d ) ; if ( rs . notOK ( ) ) { return Result . err ( rs ) ; } } wasModified ( trans , CRUD . delete , d ) ; } } else { if ( async ) { Result < ResultSetFuture > rs = deletePS . execAsync ( trans , D_TEXT , data ) ; if ( rs . notOK ( ) ) { return Result . err ( rs ) ; } } else { Result < ResultSet > rs = deletePS . exec ( trans , D_TEXT , data ) ; if ( rs . notOK ( ) ) { return Result . err ( rs ) ; } } wasModified ( trans , CRUD . delete , data ) ; } return Result . ok ( ) ; }
This method Sig for Cached ...
15,091
private String update ( ) { if ( checksum != 0 && checksum ( ) == checksum && now < last . getTime ( ) + graceEnds && now > last . getTime ( ) + lastdays ) { return null ; } else { return "UPDATE authz.notify SET last = '" + Chrono . dateOnlyStamp ( last ) + "', checksum=" + current + " WHERE user='" + user + "' AND type=" + type . getValue ( ) + ";" ; } }
Returns an Update String for CQL if there is data .
15,092
protected void addUser ( String key , User < PERM > user ) { userMap . put ( key , user ) ; }
Useful for looking up by WebToken etc .
15,093
protected boolean addMiss ( String key , byte [ ] bs ) { Miss miss = missMap . get ( key ) ; if ( miss == null ) { synchronized ( missMap ) { missMap . put ( key , new Miss ( bs , clean == null ? MIN_INTERVAL : clean . timeInterval ) ) ; } return true ; } return miss . add ( bs ) ; }
Add miss to missMap . If Miss exists or too many tries returns false .
15,094
public void remove ( String user ) { Object o = userMap . remove ( user ) ; if ( o != null ) { access . log ( Level . INFO , user , "removed from Client Cache by Request" ) ; } }
Removes user from the Cache
15,095
public Result < List < DATA > > read ( final String key , final TRANS trans , final Object ... objs ) { DAOGetter getter = new DAOGetter ( trans , dao , objs ) ; return get ( trans , key , getter ) ; }
Slight Improved performance available when String and Obj versions are known .
15,096
public String get ( String key ) { if ( key == null ) return null ; int idx = 0 , equal = 0 , amp = 0 ; while ( idx >= 0 && ( equal = tresp . indexOf ( '=' , idx ) ) >= 0 ) { amp = tresp . indexOf ( '&' , equal ) ; if ( key . regionMatches ( 0 , tresp , idx , equal - idx ) ) { return amp >= 0 ? tresp . substring ( equal + 1 , amp ) : tresp . substring ( equal + 1 ) ; } idx = amp + ( amp > 0 ? 1 : 0 ) ; } return null ; }
Get a value from a named TGuard Property
15,097
public static void timeSensitiveInit ( Env env , AuthAPI authzAPI , AuthzFacade facade , final DirectAAFUserPass directAAFUserPass ) throws Exception { authzAPI . route ( env , HttpMethods . GET , "/authn/basicAuth" , new Code ( facade , "Is given BasicAuth valid?" , true ) { public void handle ( AuthzTrans trans , HttpServletRequest req , HttpServletResponse resp ) throws Exception { Principal p = trans . getUserPrincipal ( ) ; if ( p instanceof BasicPrincipal ) { resp . setStatus ( HttpStatus . OK_200 ) ; } else if ( p instanceof X509Principal ) { String ba = req . getHeader ( "Authorization" ) ; if ( ba . startsWith ( "Basic " ) ) { String decoded = Symm . base64noSplit . decode ( ba . substring ( 6 ) ) ; int colon = decoded . indexOf ( ':' ) ; if ( directAAFUserPass . validate ( decoded . substring ( 0 , colon ) , CredVal . Type . PASSWORD , decoded . substring ( colon + 1 ) . getBytes ( ) ) ) { resp . setStatus ( HttpStatus . OK_200 ) ; } else { resp . setStatus ( HttpStatus . FORBIDDEN_403 ) ; } } } else if ( p == null ) { trans . error ( ) . log ( "Transaction not Authenticated... no Principal" ) ; resp . setStatus ( HttpStatus . FORBIDDEN_403 ) ; } else { trans . checkpoint ( "Basic Auth Check Failed: This wasn't a Basic Auth Trans" ) ; resp . setStatus ( HttpStatus . FORBIDDEN_403 ) ; } } } , "text/plain" ) ; authzAPI . route ( POST , "/authn/validate" , API . CRED_REQ , new Code ( facade , "Is given Credential valid?" , true ) { public void handle ( AuthzTrans trans , HttpServletRequest req , HttpServletResponse resp ) throws Exception { Result < Date > r = context . doesCredentialMatch ( trans , req , resp ) ; if ( r . isOK ( ) ) { resp . setStatus ( HttpStatus . OK_200 ) ; } else { resp . setStatus ( HttpStatus . FORBIDDEN_403 ) ; } } } ) ; authzAPI . route ( GET , "/authn/cert/id/:id" , API . CERTS , new Code ( facade , "Get Cert Info by ID" , true ) { public void handle ( AuthzTrans trans , HttpServletRequest req , HttpServletResponse resp ) throws Exception { Result < Void > r = context . getCertInfoByID ( trans , req , resp , pathParam ( req , ":id" ) ) ; if ( r . isOK ( ) ) { resp . setStatus ( HttpStatus . OK_200 ) ; } else { resp . setStatus ( HttpStatus . FORBIDDEN_403 ) ; } } } ) ; }
TIME SENSITIVE APIs
15,098
public Result < Void > addDescription ( AuthzTrans trans , String ns , String name , String description ) { try { getSession ( trans ) . execute ( UPDATE_SP + TABLE + " SET description = '" + description + "' WHERE ns = '" + ns + "' AND name = '" + name + "';" ) ; } catch ( DriverException | APIException | IOException e ) { reportPerhapsReset ( trans , e ) ; return Result . err ( Result . ERR_Backend , CassAccess . ERR_ACCESS_MSG ) ; } Data data = new Data ( ) ; data . ns = ns ; data . name = name ; wasModified ( trans , CRUD . update , data , "Added description " + description + " to role " + data . fullName ( ) , null ) ; return Result . ok ( ) ; }
Add description to role
15,099
public void setPathInfo ( String pathinfo ) { int qp = pathinfo . indexOf ( '?' ) ; if ( qp < 0 ) { client . setContext ( isProxy ? ( "/proxy" + pathinfo ) : pathinfo ) ; } else { client . setContext ( isProxy ? ( "/proxy" + pathinfo . substring ( 0 , qp ) ) : pathinfo . substring ( 0 , qp ) ) ; client . setQueryParams ( pathinfo . substring ( qp + 1 ) ) ; } }
DME2 can t handle having QueryParams on the URL line but it is the most natural way so ...