idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
34,300
public void stop ( ) { if ( discoveryMulticastResponder != null ) { discoveryMulticastResponder . stop ( ) ; discoveryMulticastResponder = null ; } backendManager . destroy ( ) ; backendManager = null ; requestHandler = null ; }
Stop the handler
34,301
public void handle ( final HttpExchange pHttpExchange ) throws IOException { try { checkAuthentication ( pHttpExchange ) ; Subject subject = ( Subject ) pHttpExchange . getAttribute ( ConfigKey . JAAS_SUBJECT_REQUEST_ATTRIBUTE ) ; if ( subject != null ) { doHandleAs ( subject , pHttpExchange ) ; } else { doHandle ( pHttpExchange ) ; } } catch ( SecurityException exp ) { sendForbidden ( pHttpExchange , exp ) ; } }
Handle a request . If the handler is not yet started an exception is thrown . If running with JAAS security enabled it will run as the given subject .
34,302
private void doHandleAs ( Subject subject , final HttpExchange pHttpExchange ) { try { Subject . doAs ( subject , new PrivilegedExceptionAction < Void > ( ) { public Void run ( ) throws IOException { doHandle ( pHttpExchange ) ; return null ; } } ) ; } catch ( PrivilegedActionException e ) { throw new SecurityException ( "Security exception: " + e . getCause ( ) , e . getCause ( ) ) ; } }
run as priviledged action
34,303
private String extractOriginOrReferer ( HttpExchange pExchange ) { Headers headers = pExchange . getRequestHeaders ( ) ; String origin = headers . getFirst ( "Origin" ) ; if ( origin == null ) { origin = headers . getFirst ( "Referer" ) ; } return origin != null ? origin . replaceAll ( "[\\n\\r]*" , "" ) : null ; }
Used for checking origin or referer is an origin policy is enabled
34,304
private String getHostName ( InetSocketAddress address ) { return configuration . getAsBoolean ( ConfigKey . ALLOW_DNS_REVERSE_LOOKUP ) ? address . getHostName ( ) : null ; }
Return hostnmae of given address but only when reverse DNS lookups are allowed
34,305
private String getMimeType ( ParsedUri pParsedUri ) { return MimeTypeUtil . getResponseMimeType ( pParsedUri . getParameter ( ConfigKey . MIME_TYPE . getKeyValue ( ) ) , configuration . get ( ConfigKey . MIME_TYPE ) , pParsedUri . getParameter ( ConfigKey . CALLBACK . getKeyValue ( ) ) ) ; }
Get the proper mime type according to configuration
34,306
private LogHandler createLogHandler ( String pLogHandlerClass , String pDebug ) { if ( pLogHandlerClass != null ) { return ClassUtil . newInstance ( pLogHandlerClass ) ; } else { final boolean debug = Boolean . valueOf ( pDebug ) ; return new LogHandler . StdoutLogHandler ( debug ) ; } }
out to stderr
34,307
public static MuleAgentHttpServer create ( Agent pParent , MuleAgentConfig pConfig ) { if ( ClassUtil . checkForClass ( "org.mortbay.jetty.Server" ) ) { return new MortbayMuleAgentHttpServer ( pParent , pConfig ) ; } else if ( ClassUtil . checkForClass ( "org.eclipse.jetty.server.ServerConnector" ) ) { return new Jetty9MuleAgentHttpServer ( pParent , pConfig ) ; } else if ( ClassUtil . checkForClass ( "org.eclipse.jetty.server.Server" ) ) { return new Jetty7And8MuleAgentHttpServer ( pParent , pConfig ) ; } throw new IllegalStateException ( "Cannot detect Jetty version (tried 6,7,8,9)" ) ; }
Create the internal HTTP server . Create the Jetty Server of Mortbay packages or Eclipse Foundation packages .
34,308
public static String dump ( Set < MBeanServerConnection > servers ) { StringBuffer ret = new StringBuffer ( ) ; ret . append ( "Found " ) . append ( servers . size ( ) ) . append ( " MBeanServers\n" ) ; for ( MBeanServerConnection c : servers ) { MBeanServer s = ( MBeanServer ) c ; ret . append ( " " ) . append ( "++ " ) . append ( s . toString ( ) ) . append ( ": default domain = " ) . append ( s . getDefaultDomain ( ) ) . append ( ", " ) . append ( s . getMBeanCount ( ) ) . append ( " MBeans\n" ) ; ret . append ( " Domains:\n" ) ; for ( String d : s . getDomains ( ) ) { appendDomainInfo ( ret , s , d ) ; } } ret . append ( "\n" ) ; ret . append ( "Platform MBeanServer: " ) . append ( ManagementFactory . getPlatformMBeanServer ( ) ) . append ( "\n" ) ; return ret . toString ( ) ; }
Dump out a list of MBeanServer with some statistics .
34,309
private Object mapAndInvoke ( String pOperation , Object [ ] pParams , String [ ] pSignature , OperationMapInfo pOpMapInfo ) throws InstanceNotFoundException , MBeanException , ReflectionException { Object realParams [ ] = new Object [ pSignature . length ] ; String realSignature [ ] = new String [ pSignature . length ] ; for ( int i = 0 ; i < pSignature . length ; i ++ ) { if ( pOpMapInfo . isParamMapped ( i ) ) { String origType = pOpMapInfo . getOriginalType ( i ) ; OpenType openType = pOpMapInfo . getOpenMBeanType ( i ) ; if ( openType != null ) { realParams [ i ] = fromJson ( openType , ( String ) pParams [ i ] ) ; } else { realParams [ i ] = fromJson ( origType , ( String ) pParams [ i ] ) ; } realSignature [ i ] = origType ; } else { realParams [ i ] = pParams [ i ] ; realSignature [ i ] = pSignature [ i ] ; } } Object ret = jolokiaMBeanServer . invoke ( objectName , pOperation , realParams , realSignature ) ; return pOpMapInfo . isRetTypeMapped ( ) ? toJson ( ret ) : ret ; }
Map the parameters and the return value if required
34,310
private OperationMapInfo getOperationMapInfo ( String pOperation , String [ ] pSignature ) { List < OperationMapInfo > opMapInfoList = operationInfoMap . get ( pOperation ) ; OperationMapInfo opMapInfo = null ; if ( opMapInfoList != null ) { for ( OperationMapInfo i : opMapInfoList ) { if ( i . matchSignature ( pSignature ) ) { opMapInfo = i ; break ; } } } return opMapInfo ; }
Lookup whether a mapping is required for this call
34,311
private MBeanInfo getWrappedInfo ( MBeanInfo pMBeanInfo ) { MBeanAttributeInfo [ ] attrInfo = getWrappedAttributeInfo ( pMBeanInfo ) ; MBeanOperationInfo [ ] opInfo = getWrappedOperationInfo ( pMBeanInfo ) ; return new MBeanInfo ( pMBeanInfo . getClassName ( ) , pMBeanInfo . getDescription ( ) , attrInfo , null , opInfo , pMBeanInfo . getNotifications ( ) ) ; }
Wrap the given MBeanInfo modified for translated signatures
34,312
private List < String > extractBeanAttributes ( Object pValue ) { List < String > attrs = new ArrayList < String > ( ) ; for ( Method method : pValue . getClass ( ) . getMethods ( ) ) { if ( ! Modifier . isStatic ( method . getModifiers ( ) ) && ! IGNORE_METHODS . contains ( method . getName ( ) ) && ! isIgnoredType ( method . getReturnType ( ) ) && ! hasAnnotation ( method , "java.beans.Transient" ) ) { addAttributes ( attrs , method ) ; } } return attrs ; }
Extract all attributes from a given bean
34,313
@ SuppressWarnings ( "PMD.UnnecessaryCaseChange" ) private void addAttributes ( List < String > pAttrs , Method pMethod ) { String name = pMethod . getName ( ) ; for ( String pref : GETTER_PREFIX ) { if ( name . startsWith ( pref ) && name . length ( ) > pref . length ( ) && pMethod . getParameterTypes ( ) . length == 0 ) { int len = pref . length ( ) ; String firstLetter = name . substring ( len , len + 1 ) ; if ( firstLetter . toUpperCase ( ) . equals ( firstLetter ) ) { String attribute = new StringBuffer ( firstLetter . toLowerCase ( ) ) . append ( name . substring ( len + 1 ) ) . toString ( ) ; pAttrs . add ( attribute ) ; } } } }
Add attributes which are taken from get methods to the given list
34,314
private boolean isIgnoredType ( Class < ? > pReturnType ) { for ( Class < ? > type : IGNORED_RETURN_TYPES ) { if ( type . isAssignableFrom ( pReturnType ) ) { return true ; } } return false ; }
as safety net . I messed up my complete local Maven repository only be serializing a Jetty ServletContext
34,315
public void afterPropertiesSet ( ) throws IOException { Map < String , String > finalConfig = new HashMap < String , String > ( ) ; if ( systemPropertyMode == SystemPropertyMode . MODE_FALLBACK ) { finalConfig . putAll ( lookupSystemProperties ( ) ) ; } if ( config != null ) { finalConfig . putAll ( config . getConfig ( ) ) ; } if ( lookupConfig ) { Map < String , SpringJolokiaConfigHolder > configsMap = context . getBeansOfType ( SpringJolokiaConfigHolder . class ) ; List < SpringJolokiaConfigHolder > configs = new ArrayList < SpringJolokiaConfigHolder > ( configsMap . values ( ) ) ; Collections . sort ( configs , new OrderComparator ( ) ) ; for ( SpringJolokiaConfigHolder c : configs ) { if ( c != config ) { finalConfig . putAll ( c . getConfig ( ) ) ; } } } if ( systemPropertyMode == SystemPropertyMode . MODE_OVERRIDE ) { finalConfig . putAll ( lookupSystemProperties ( ) ) ; } String autoStartS = finalConfig . remove ( "autoStart" ) ; boolean autoStart = true ; if ( autoStartS != null ) { autoStart = Boolean . parseBoolean ( autoStartS ) ; } init ( new JolokiaServerConfig ( finalConfig ) , false ) ; if ( autoStart ) { start ( ) ; } }
Callback used for initializing and optionally starting up the server
34,316
private Map < String , String > lookupSystemProperties ( ) { Map < String , String > ret = new HashMap < String , String > ( ) ; Enumeration propEnum = System . getProperties ( ) . propertyNames ( ) ; while ( propEnum . hasMoreElements ( ) ) { String prop = ( String ) propEnum . nextElement ( ) ; if ( prop . startsWith ( "jolokia." ) ) { String key = prop . substring ( "jolokia." . length ( ) ) ; ret . put ( key , System . getProperty ( prop ) ) ; } } return ret ; }
Lookup system properties for all configurations possible
34,317
public void setSystemPropertiesMode ( String pMode ) { systemPropertyMode = SystemPropertyMode . fromMode ( pMode ) ; if ( systemPropertyMode == null ) { systemPropertyMode = SystemPropertyMode . MODE_NEVER ; } }
Set the system propert mode for how to deal with configuration coming from system properties
34,318
public JSONObject toJSON ( ) { JSONObject ret = super . toJSON ( ) ; if ( arguments != null && arguments . size ( ) > 0 ) { ret . put ( "arguments" , arguments ) ; } ret . put ( "operation" , operation ) ; return ret ; }
Return this request in a proper JSON representation
34,319
private static List < String > convertSpecialStringTags ( List < String > extraArgs ) { if ( extraArgs == null ) { return null ; } List < String > args = new ArrayList < String > ( ) ; for ( String arg : extraArgs ) { args . add ( StringToObjectConverter . convertSpecialStringTags ( arg ) ) ; } return args ; }
Conver string tags if required
34,320
public JsonRequestHandler getRequestHandler ( RequestType pType ) { JsonRequestHandler handler = requestHandlerMap . get ( pType ) ; if ( handler == null ) { throw new UnsupportedOperationException ( "Unsupported operation '" + pType + "'" ) ; } return handler ; }
Get the request handler for the given type
34,321
private void addJsr160DispatcherIfExternallyConfigured ( Configuration pConfig ) { String dispatchers = pConfig . get ( ConfigKey . DISPATCHER_CLASSES ) ; String jsr160DispatcherClass = "org.jolokia.jsr160.Jsr160RequestDispatcher" ; if ( dispatchers == null || ! dispatchers . contains ( jsr160DispatcherClass ) ) { for ( String param : new String [ ] { System . getProperty ( "org.jolokia.jsr160ProxyEnabled" ) , System . getenv ( "JOLOKIA_JSR160_PROXY_ENABLED" ) } ) { if ( param != null && ( param . isEmpty ( ) || Boolean . parseBoolean ( param ) ) ) { { pConfig . updateGlobalConfiguration ( Collections . singletonMap ( ConfigKey . DISPATCHER_CLASSES . getKeyValue ( ) , ( dispatchers != null ? dispatchers + "," : "" ) + jsr160DispatcherClass ) ) ; } return ; } } if ( dispatchers == null ) { pConfig . updateGlobalConfiguration ( Collections . singletonMap ( ConfigKey . DISPATCHER_CLASSES . getKeyValue ( ) , Jsr160ProxyNotEnabledByDefaultAnymoreDispatcher . class . getCanonicalName ( ) ) ) ; } } }
Add the JsrRequestDispatcher if configured via a system property or env variable . The JSR160 dispatcher is disabled by default but this allows to enable it again without reconfiguring the servlet
34,322
private String findAgentUrl ( Configuration pConfig ) { String url = System . getProperty ( "jolokia." + ConfigKey . DISCOVERY_AGENT_URL . getKeyValue ( ) ) ; if ( url == null ) { url = System . getenv ( "JOLOKIA_DISCOVERY_AGENT_URL" ) ; if ( url == null ) { url = pConfig . get ( ConfigKey . DISCOVERY_AGENT_URL ) ; } } return NetworkUtil . replaceExpression ( url ) ; }
Try to find an URL for system props or config
34,323
private boolean listenForDiscoveryMcRequests ( Configuration pConfig ) { boolean sysProp = System . getProperty ( "jolokia." + ConfigKey . DISCOVERY_ENABLED . getKeyValue ( ) ) != null ; boolean env = System . getenv ( "JOLOKIA_DISCOVERY" ) != null ; boolean config = pConfig . getAsBoolean ( ConfigKey . DISCOVERY_ENABLED ) ; return sysProp || env || config ; }
For war agent needs to be switched on
34,324
protected void doOptions ( HttpServletRequest req , HttpServletResponse resp ) throws ServletException , IOException { Map < String , String > responseHeaders = requestHandler . handleCorsPreflightRequest ( getOriginOrReferer ( req ) , req . getHeader ( "Access-Control-Request-Headers" ) ) ; for ( Map . Entry < String , String > entry : responseHeaders . entrySet ( ) ) { resp . setHeader ( entry . getKey ( ) , entry . getValue ( ) ) ; } }
OPTION requests are treated as CORS preflight requests
34,325
private void updateAgentDetailsIfNeeded ( HttpServletRequest pReq ) { AgentDetails details = backendManager . getAgentDetails ( ) ; if ( details . isInitRequired ( ) ) { synchronized ( details ) { if ( details . isInitRequired ( ) ) { if ( details . isUrlMissing ( ) ) { String url = getBaseUrl ( NetworkUtil . sanitizeLocalUrl ( pReq . getRequestURL ( ) . toString ( ) ) , extractServletPath ( pReq ) ) ; details . setUrl ( url ) ; } if ( details . isSecuredMissing ( ) ) { details . setSecured ( pReq . getAuthType ( ) != null ) ; } details . seal ( ) ; } } } }
Update the agent URL in the agent details if not already done
34,326
private String getBaseUrl ( String pUrl , String pServletPath ) { String sUrl ; try { URL url = new URL ( pUrl ) ; String host = getIpIfPossible ( url . getHost ( ) ) ; sUrl = new URL ( url . getProtocol ( ) , host , url . getPort ( ) , pServletPath ) . toExternalForm ( ) ; } catch ( MalformedURLException exp ) { sUrl = plainReplacement ( pUrl , pServletPath ) ; } return sUrl ; }
Strip off everything unneeded
34,327
private String getIpIfPossible ( String pHost ) { try { InetAddress address = InetAddress . getByName ( pHost ) ; return address . getHostAddress ( ) ; } catch ( UnknownHostException e ) { return pHost ; } }
Check for an IP since this seems to be safer to return then a plain name
34,328
private String plainReplacement ( String pUrl , String pServletPath ) { int idx = pUrl . lastIndexOf ( pServletPath ) ; String url ; if ( idx != - 1 ) { url = pUrl . substring ( 0 , idx ) + pServletPath ; } else { url = pUrl ; } return url ; }
Fallback used if URL creation didnt work
34,329
private void setCorsHeader ( HttpServletRequest pReq , HttpServletResponse pResp ) { String origin = requestHandler . extractCorsOrigin ( pReq . getHeader ( "Origin" ) ) ; if ( origin != null ) { pResp . setHeader ( "Access-Control-Allow-Origin" , origin ) ; pResp . setHeader ( "Access-Control-Allow-Credentials" , "true" ) ; } }
Set an appropriate CORS header if requested and if allowed
34,330
private ServletRequestHandler newPostHttpRequestHandler ( ) { return new ServletRequestHandler ( ) { public JSONAware handleRequest ( HttpServletRequest pReq , HttpServletResponse pResp ) throws IOException { String encoding = pReq . getCharacterEncoding ( ) ; InputStream is = pReq . getInputStream ( ) ; return requestHandler . handlePostRequest ( pReq . getRequestURI ( ) , is , encoding , getParameterMap ( pReq ) ) ; } } ; }
factory method for POST request handler
34,331
private ServletRequestHandler newGetHttpRequestHandler ( ) { return new ServletRequestHandler ( ) { public JSONAware handleRequest ( HttpServletRequest pReq , HttpServletResponse pResp ) { return requestHandler . handleGetRequest ( pReq . getRequestURI ( ) , pReq . getPathInfo ( ) , getParameterMap ( pReq ) ) ; } } ; }
factory method for GET request handler
34,332
Configuration initConfig ( ServletConfig pConfig ) { Configuration config = new Configuration ( ConfigKey . AGENT_ID , NetworkUtil . getAgentId ( hashCode ( ) , "servlet" ) ) ; config . updateGlobalConfiguration ( new ServletConfigFacade ( pConfig ) ) ; config . updateGlobalConfiguration ( new ServletContextFacade ( getServletContext ( ) ) ) ; config . updateGlobalConfiguration ( Collections . singletonMap ( ConfigKey . AGENT_TYPE . getKeyValue ( ) , "servlet" ) ) ; return config ; }
Configuration from the servlet context overrides servlet parameters defined in web . xml
34,333
public Object setObjectValue ( StringToObjectConverter pConverter , Object pInner , String pIndex , Object pValue ) throws IllegalAccessException , InvocationTargetException { Class clazz = pInner . getClass ( ) ; if ( ! clazz . isArray ( ) ) { throw new IllegalArgumentException ( "Not an array to set a value, but " + clazz + ". (index = " + pIndex + ", value = " + pValue + ")" ) ; } int idx ; try { idx = Integer . parseInt ( pIndex ) ; } catch ( NumberFormatException exp ) { throw new IllegalArgumentException ( "Non-numeric index for accessing array " + pInner + ". (index = " + pIndex + ", value to set = " + pValue + ")" , exp ) ; } Class type = clazz . getComponentType ( ) ; Object value = pConverter . prepareValue ( type . getName ( ) , pValue ) ; Object oldValue = Array . get ( pInner , idx ) ; Array . set ( pInner , idx , value ) ; return oldValue ; }
Set a value in an array
34,334
public void detachAgent ( Object pVm ) { try { if ( pVm != null ) { Class clazz = pVm . getClass ( ) ; Method method = clazz . getMethod ( "detach" ) ; method . setAccessible ( true ) ; method . invoke ( pVm ) ; } } catch ( InvocationTargetException e ) { throw new ProcessingException ( "Error while detaching" , e , options ) ; } catch ( NoSuchMethodException e ) { throw new ProcessingException ( "Error while detaching" , e , options ) ; } catch ( IllegalAccessException e ) { throw new ProcessingException ( "Error while detaching" , e , options ) ; } }
Detach from the virtual machine
34,335
public List < ProcessDescription > listProcesses ( ) throws NoSuchMethodException , InvocationTargetException , IllegalAccessException { List < ProcessDescription > ret = new ArrayList < ProcessDescription > ( ) ; Class vmClass = lookupVirtualMachineClass ( ) ; Method method = vmClass . getMethod ( "list" ) ; List vmDescriptors = ( List ) method . invoke ( null ) ; for ( Object descriptor : vmDescriptors ) { Method idMethod = descriptor . getClass ( ) . getMethod ( "id" ) ; String id = ( String ) idMethod . invoke ( descriptor ) ; Method displayMethod = descriptor . getClass ( ) . getMethod ( "displayName" ) ; String display = ( String ) displayMethod . invoke ( descriptor ) ; ret . add ( new ProcessDescription ( id , display ) ) ; } return ret ; }
Return a list of all Java processes
34,336
public ProcessDescription findProcess ( Pattern pPattern ) throws InvocationTargetException , NoSuchMethodException , IllegalAccessException { List < ProcessDescription > ret = new ArrayList < ProcessDescription > ( ) ; String ownId = getOwnProcessId ( ) ; for ( ProcessDescription desc : listProcesses ( ) ) { Matcher matcher = pPattern . matcher ( desc . getDisplay ( ) ) ; if ( ! desc . getId ( ) . equals ( ownId ) && matcher . find ( ) ) { ret . add ( desc ) ; } } if ( ret . size ( ) == 1 ) { return ret . get ( 0 ) ; } else if ( ret . size ( ) == 0 ) { throw new IllegalArgumentException ( "No attachable process found matching \"" + pPattern . pattern ( ) + "\"" ) ; } else { StringBuilder buf = new StringBuilder ( ) ; for ( ProcessDescription desc : ret ) { buf . append ( desc . getId ( ) ) . append ( " (" ) . append ( desc . getDisplay ( ) ) . append ( ")," ) ; } throw new IllegalArgumentException ( "More than one attachable process found matching \"" + pPattern . pattern ( ) + "\": " + buf . substring ( 0 , buf . length ( ) - 1 ) ) ; } }
Filter the process list for a regular expression and returns the description . The process this JVM is running in is ignored . If more than one process or no process is found an exception is raised .
34,337
private String getOwnProcessId ( ) { String name = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; int endIdx = name . indexOf ( '@' ) ; return endIdx != - 1 ? name . substring ( 0 , endIdx ) : name ; }
whole agent so it should be safe
34,338
private Class lookupVirtualMachineClass ( ) { try { return ToolsClassFinder . lookupClass ( "com.sun.tools.attach.VirtualMachine" ) ; } catch ( ClassNotFoundException exp ) { throw new ProcessingException ( "Cannot find classes from tools.jar. The heuristics for loading tools.jar which contains\n" + "essential classes for attaching to a running JVM could locate the necessary jar file.\n" + "\n" + "Please call this launcher with a qualified classpath on the command line like\n" + "\n" + " java -cp path/to/tools.jar:" + options . getJarFileName ( ) + " org.jolokia.jvmagent.client.AgentLauncher [options] <command> <ppid>\n" , exp , options ) ; } }
lookup virtual machine class
34,339
public synchronized void handleNotification ( Notification notification , Object handback ) { String type = notification . getType ( ) ; if ( REGISTRATION_NOTIFICATION . equals ( type ) ) { jolokiaMBeanServer = lookupJolokiaMBeanServer ( ) ; if ( jolokiaMBeanServerListener != null ) { JmxUtil . addMBeanRegistrationListener ( jolokiaMBeanServer , jolokiaMBeanServerListener , null ) ; } } else if ( UNREGISTRATION_NOTIFICATION . equals ( type ) ) { jolokiaMBeanServer = null ; } allMBeanServers . clear ( ) ; if ( jolokiaMBeanServer != null ) { allMBeanServers . add ( jolokiaMBeanServer ) ; } allMBeanServers . addAll ( detectedMBeanServers ) ; }
Fetch Jolokia MBeanServer when it gets registered remove it if being unregistered
34,340
private MBeanServer lookupJolokiaMBeanServer ( ) { MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; try { return server . isRegistered ( JOLOKIA_MBEAN_SERVER_ONAME ) ? ( MBeanServer ) server . getAttribute ( JOLOKIA_MBEAN_SERVER_ONAME , "JolokiaMBeanServer" ) : null ; } catch ( JMException e ) { throw new IllegalStateException ( "Internal: Cannot get Jolokia MBeanServer via JMX lookup: " + e , e ) ; } }
Check whether the Jolokia MBean Server is available and return it .
34,341
protected void assertNodeName ( Node pNode , String ... pExpected ) { for ( String expected : pExpected ) { if ( pNode . getNodeName ( ) . equals ( expected ) ) { return ; } } StringBuilder buffer = new StringBuilder ( ) ; for ( int i = 0 ; i < pExpected . length ; i ++ ) { buffer . append ( pExpected [ i ] ) ; if ( i < pExpected . length - 1 ) { buffer . append ( "," ) ; } } throw new SecurityException ( "Expected element " + buffer . toString ( ) + " but got " + pNode . getNodeName ( ) ) ; }
Verify that a given node has one of a set of expected node names
34,342
private JsonMBean extractJsonMBeanAnnotation ( Object object ) { Class < ? > clazz = object . getClass ( ) ; JsonMBean anno = clazz . getAnnotation ( JsonMBean . class ) ; if ( anno == null && ModelMBean . class . isAssignableFrom ( object . getClass ( ) ) ) { Boolean isAccessible = null ; Field field = null ; try { field = findField ( clazz , "managedResource" ) ; if ( field != null ) { isAccessible = field . isAccessible ( ) ; field . setAccessible ( true ) ; Object managedResource = field . get ( object ) ; anno = managedResource . getClass ( ) . getAnnotation ( JsonMBean . class ) ; } } catch ( IllegalAccessException e ) { } finally { if ( isAccessible != null ) { field . setAccessible ( isAccessible ) ; } } } return anno ; }
Lookup a JsonMBean annotation
34,343
private Field findField ( Class < ? > pClazz , String pField ) { Class c = pClazz ; do { try { return c . getDeclaredField ( pField ) ; } catch ( NoSuchFieldException e ) { c = pClazz . getSuperclass ( ) ; } } while ( c != null ) ; return null ; }
Find a field in an inheritance hierarchy
34,344
String toJson ( Object object , JsonConvertOptions pConvertOptions ) { try { Object ret = converters . getToJsonConverter ( ) . convertToJson ( object , null , pConvertOptions ) ; return ret . toString ( ) ; } catch ( AttributeNotFoundException exp ) { return "" ; } }
Converter used by JsonMBean for converting from Object to JSON representation
34,345
private JsonConvertOptions getJsonConverterOptions ( JsonMBean pAnno ) { if ( pAnno == null ) { return JsonConvertOptions . DEFAULT ; } else { ValueFaultHandler faultHandler = pAnno . faultHandling ( ) == JsonMBean . FaultHandler . IGNORE_ERRORS ? ValueFaultHandler . IGNORING_VALUE_FAULT_HANDLER : ValueFaultHandler . THROWING_VALUE_FAULT_HANDLER ; return new JsonConvertOptions . Builder ( ) . maxCollectionSize ( pAnno . maxCollectionSize ( ) ) . maxDepth ( pAnno . maxDepth ( ) ) . maxObjects ( pAnno . maxObjects ( ) ) . faultHandler ( faultHandler ) . build ( ) ; } }
Extract convert options from annotation
34,346
protected void init ( Map < String , String > pConfig ) { Map < String , String > finalCfg = getDefaultConfig ( pConfig ) ; finalCfg . putAll ( pConfig ) ; prepareDetectorOptions ( finalCfg ) ; addJolokiaId ( finalCfg ) ; jolokiaConfig = new Configuration ( ) ; jolokiaConfig . updateGlobalConfiguration ( finalCfg ) ; initConfigAndValidate ( finalCfg ) ; }
Initialize the configuration with the given map
34,347
private void addJolokiaId ( Map < String , String > pFinalCfg ) { if ( ! pFinalCfg . containsKey ( ConfigKey . AGENT_ID . getKeyValue ( ) ) ) { pFinalCfg . put ( ConfigKey . AGENT_ID . getKeyValue ( ) , NetworkUtil . getAgentId ( hashCode ( ) , "jvm" ) ) ; } pFinalCfg . put ( ConfigKey . AGENT_TYPE . getKeyValue ( ) , "jvm" ) ; }
Add a unique jolokia id for this agent
34,348
public void updateHTTPSSettingsFromContext ( SSLContext sslContext ) { SSLParameters parameters = sslContext . getSupportedSSLParameters ( ) ; if ( sslProtocols == null ) { sslProtocols = parameters . getProtocols ( ) ; } else { List < String > supportedProtocols = Arrays . asList ( parameters . getProtocols ( ) ) ; List < String > sslProtocolsList = new ArrayList < String > ( Arrays . asList ( sslProtocols ) ) ; Iterator < String > pit = sslProtocolsList . iterator ( ) ; while ( pit . hasNext ( ) ) { String protocol = pit . next ( ) ; if ( ! supportedProtocols . contains ( protocol ) ) { System . out . println ( "Jolokia: Discarding unsupported protocol: " + protocol ) ; pit . remove ( ) ; } } sslProtocols = sslProtocolsList . toArray ( new String [ 0 ] ) ; } if ( sslCipherSuites == null ) { sslCipherSuites = parameters . getCipherSuites ( ) ; } else { List < String > supportedCipherSuites = Arrays . asList ( parameters . getCipherSuites ( ) ) ; List < String > sslCipherSuitesList = new ArrayList < String > ( Arrays . asList ( sslCipherSuites ) ) ; Iterator < String > cit = sslCipherSuitesList . iterator ( ) ; while ( cit . hasNext ( ) ) { String cipher = cit . next ( ) ; if ( ! supportedCipherSuites . contains ( cipher ) ) { System . out . println ( "Jolokia: Discarding unsupported cipher suite: " + cipher ) ; cit . remove ( ) ; } } sslCipherSuites = sslCipherSuitesList . toArray ( new String [ 0 ] ) ; } }
Filter the list of protocols and ciphers to those supported by the given SSLContext
34,349
protected void initConfigAndValidate ( Map < String , String > agentConfig ) { initContext ( ) ; initProtocol ( agentConfig ) ; initAddress ( agentConfig ) ; port = Integer . parseInt ( agentConfig . get ( "port" ) ) ; backlog = Integer . parseInt ( agentConfig . get ( "backlog" ) ) ; initExecutor ( agentConfig ) ; initThreadNamePrefix ( agentConfig ) ; initThreadNr ( agentConfig ) ; initHttpsRelatedSettings ( agentConfig ) ; initAuthenticator ( ) ; }
Initialise and validate early in order to fail fast in case of an configuration error
34,350
private List < String > extractList ( Map < String , String > pAgentConfig , String pKey ) { List < String > ret = new ArrayList < String > ( ) ; if ( pAgentConfig . containsKey ( pKey ) ) { ret . add ( pAgentConfig . get ( pKey ) ) ; } int idx = 1 ; String keyIdx = pKey + "." + idx ; while ( pAgentConfig . containsKey ( keyIdx ) ) { ret . add ( pAgentConfig . get ( keyIdx ) ) ; keyIdx = pKey + "." + ++ idx ; } return ret . size ( ) > 0 ? ret : null ; }
More elements can be given with . 1 . 2 ... added .
34,351
protected void prepareDetectorOptions ( Map < String , String > pConfig ) { StringBuffer detectorOpts = new StringBuffer ( "{" ) ; if ( pConfig . containsKey ( "bootAmx" ) && Boolean . parseBoolean ( pConfig . get ( "bootAmx" ) ) ) { detectorOpts . append ( "\"glassfish\" : { \"bootAmx\" : true }" ) ; } if ( detectorOpts . length ( ) > 1 ) { detectorOpts . append ( "}" ) ; pConfig . put ( ConfigKey . DETECTOR_OPTIONS . getKeyValue ( ) , detectorOpts . toString ( ) ) ; } }
Add detector specific options if given on the command line
34,352
public ObjectName registerMBeanAtServer ( MBeanServer pServer , Object pMBean , String pName ) throws MBeanRegistrationException , InstanceAlreadyExistsException , NotCompliantMBeanException , MalformedObjectNameException { if ( pName != null ) { ObjectName oName = new ObjectName ( pName ) ; return pServer . registerMBean ( pMBean , oName ) . getObjectName ( ) ; } else { return pServer . registerMBean ( pMBean , null ) . getObjectName ( ) ; } }
Register a MBean at the dedicated server . This method can be overridden if something special registration procedure is required like for using the specific name for the registration or deligating the namin to MBean to register .
34,353
public JSONObject toJSONObject ( MBeanServerExecutor pServerManager ) { JSONObject ret = new JSONObject ( ) ; addNullSafe ( ret , "vendor" , vendor ) ; addNullSafe ( ret , "product" , product ) ; addNullSafe ( ret , "version" , version ) ; Map < String , String > extra = getExtraInfo ( pServerManager ) ; if ( extra != null ) { JSONObject jsonExtra = new JSONObject ( ) ; for ( Map . Entry < String , String > entry : extra . entrySet ( ) ) { jsonExtra . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } ret . put ( "extraInfo" , jsonExtra ) ; } return ret ; }
Return this info as an JSONObject
34,354
protected JSONObject getDetectorOptions ( Configuration pConfig , LogHandler pLogHandler ) { String options = pConfig . get ( ConfigKey . DETECTOR_OPTIONS ) ; try { if ( options != null ) { JSONObject opts = ( JSONObject ) new JSONParser ( ) . parse ( options ) ; return ( JSONObject ) opts . get ( getProduct ( ) ) ; } return null ; } catch ( ParseException e ) { pLogHandler . error ( "Could not parse detector options '" + options + "' as JSON object: " + e , e ) ; } return null ; }
Get the optional options used for detectors . This should be a JSON string specifying all options for all detectors . Keys are the name of the detector s product the values are JSON object containing specific parameters for this agent . E . g .
34,355
protected Map < String , String > getDefaultConfig ( Map < String , String > pConfig ) { Map < String , String > config = super . getDefaultConfig ( pConfig ) ; if ( pConfig . containsKey ( "config" ) ) { config . putAll ( readConfig ( pConfig . get ( "config" ) ) ) ; } return config ; }
Beside reading the default configuration from an internal property file also add extra configuration given in an external properties where the path to this property file is given under the key config
34,356
private static Map < String , String > split ( String pAgentArgs ) { Map < String , String > ret = new HashMap < String , String > ( ) ; if ( pAgentArgs != null && pAgentArgs . length ( ) > 0 ) { for ( String arg : EscapeUtil . splitAsArray ( pAgentArgs , EscapeUtil . CSV_ESCAPE , "," ) ) { String [ ] prop = arg . split ( "=" , 2 ) ; if ( prop == null || prop . length != 2 ) { throw new IllegalArgumentException ( "jolokia: Invalid option '" + arg + "'" ) ; } else { ret . put ( prop [ 0 ] , prop [ 1 ] ) ; } } } return ret ; }
Split arguments into a map
34,357
public static < T > List < T > createServiceObjects ( String ... pDescriptorPaths ) { try { ServiceEntry . initDefaultOrder ( ) ; TreeMap < ServiceEntry , T > extractorMap = new TreeMap < ServiceEntry , T > ( ) ; for ( String descriptor : pDescriptorPaths ) { readServiceDefinitions ( extractorMap , descriptor ) ; } ArrayList < T > ret = new ArrayList < T > ( ) ; for ( T service : extractorMap . values ( ) ) { ret . add ( service ) ; } return ret ; } finally { ServiceEntry . removeDefaultOrder ( ) ; } }
Create a list of services ordered according to the ordering given in the service descriptor files . Note that the descriptor will be looked up in the whole classpath space which can result in reading in multiple descriptors with a single path . Note that the reading order for multiple resources with the same name is not defined .
34,358
public Collection < ObjectName > getObjectNames ( ) throws MalformedObjectNameException { ObjectName mBean = getRequest ( ) . getObjectName ( ) ; if ( mBean . isPattern ( ) ) { JSONObject values = getValue ( ) ; Set < ObjectName > ret = new HashSet < ObjectName > ( ) ; for ( Object name : values . keySet ( ) ) { ret . add ( new ObjectName ( ( String ) name ) ) ; } return ret ; } else { return Arrays . asList ( mBean ) ; } }
Get all MBean names for which the request fetched values . If the request contained an MBean pattern then all MBean names matching this pattern and which contained attributes of the given name are returned . If the MBean wasnt a pattern a single value collection with the single MBean name of the request is returned .
34,359
public JSONObject toJson ( ) { JSONObject ret = new JSONObject ( ) ; ret . put ( "url" , url ) ; if ( user != null ) { ret . put ( "user" , user ) ; ret . put ( "password" , password ) ; } return ret ; }
Get a JSON representation of this target configuration
34,360
public void add ( Object pObject , long pTime ) { values . addFirst ( new ValueEntry ( pObject , pTime ) ) ; trim ( ) ; }
Add a new value with the given times stamp to the values list
34,361
private void trim ( ) { while ( values . size ( ) > limit . getMaxEntries ( ) ) { values . removeLast ( ) ; } if ( limit . getMaxDuration ( ) > 0 && ! values . isEmpty ( ) ) { long duration = limit . getMaxDuration ( ) ; long start = values . getFirst ( ) . getTimestamp ( ) ; while ( start - values . getLast ( ) . getTimestamp ( ) > duration ) { values . removeLast ( ) ; } } }
Truncate list so that no more than max entries are stored in the list
34,362
private HistoryLimit limitOrNull ( int pMaxEntries , long pMaxDuration ) { return pMaxEntries != 0 || pMaxDuration != 0 ? new HistoryLimit ( pMaxEntries , pMaxDuration ) : null ; }
The limit or null if the entry should be disabled in the history store
34,363
public static boolean matches ( String pExpected , String pToCheck ) { String [ ] parts = pExpected . split ( "/" , 2 ) ; if ( parts . length == 1 ) { convertToIntTuple ( pExpected ) ; convertToIntTuple ( pToCheck ) ; return pExpected . equals ( pToCheck ) ; } else if ( parts . length == 2 ) { int ipToCheck [ ] = convertToIntTuple ( pToCheck ) ; int ipPattern [ ] = convertToIntTuple ( parts [ 0 ] ) ; int netmask [ ] ; if ( parts [ 1 ] . length ( ) <= 2 ) { netmask = transformCidrToNetmask ( parts [ 1 ] ) ; } else { netmask = convertToIntTuple ( parts [ 1 ] ) ; } for ( int i = 0 ; i < ipToCheck . length ; i ++ ) { if ( ( ipPattern [ i ] & netmask [ i ] ) != ( ipToCheck [ i ] & netmask [ i ] ) ) { return false ; } } return true ; } else { throw new IllegalArgumentException ( "Invalid IP adress specification " + pExpected ) ; } }
Check whether a given IP Adress falls within a subnet or is equal to
34,364
public JSONObject toJSON ( ) { JSONObject ret = new JSONObject ( ) ; ret . put ( "url" , url ) ; if ( env != null ) { ret . put ( "env" , env ) ; } return ret ; }
As JSON representation
34,365
public static void addMBeanRegistrationListener ( MBeanServerConnection pServer , NotificationListener pListener , ObjectName pObjectNameToFilter ) { MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter ( ) ; if ( pObjectNameToFilter == null ) { filter . enableAllObjectNames ( ) ; } else { filter . enableObjectName ( pObjectNameToFilter ) ; } try { pServer . addNotificationListener ( getMBeanServerDelegateName ( ) , pListener , filter , null ) ; } catch ( InstanceNotFoundException e ) { throw new IllegalStateException ( "Cannot find " + getMBeanServerDelegateName ( ) + " in server " + pServer , e ) ; } catch ( IOException e ) { throw new IllegalStateException ( "IOException while registering notification listener for " + getMBeanServerDelegateName ( ) , e ) ; } }
Register a notification listener which listens for registration and deregistration of MBeans at a certain server
34,366
public static void removeMBeanRegistrationListener ( MBeanServerConnection pServer , NotificationListener pListener ) { try { pServer . removeNotificationListener ( JmxUtil . getMBeanServerDelegateName ( ) , pListener ) ; } catch ( ListenerNotFoundException e ) { } catch ( InstanceNotFoundException e ) { throw new IllegalStateException ( "Cannot find " + getMBeanServerDelegateName ( ) + " in server " + pServer , e ) ; } catch ( IOException e ) { throw new IllegalStateException ( "IOException while registering notification listener for " + getMBeanServerDelegateName ( ) , e ) ; } }
Remove a notification listener from the given MBeanServer while listening for MBeanServer registration events
34,367
public Object convertToJson ( Object pValue , List < String > pPathParts , JsonConvertOptions pOptions ) throws AttributeNotFoundException { Stack < String > extraStack = pPathParts != null ? EscapeUtil . reversePath ( pPathParts ) : new Stack < String > ( ) ; return extractObjectWithContext ( pValue , extraStack , pOptions , true ) ; }
Convert the return value to a JSON object .
34,368
private Object setObjectValue ( Object pInner , String pAttribute , Object pValue ) throws IllegalAccessException , InvocationTargetException { Class clazz = pInner . getClass ( ) ; if ( clazz . isArray ( ) ) { return arrayExtractor . setObjectValue ( stringToObjectConverter , pInner , pAttribute , pValue ) ; } Extractor handler = getExtractor ( clazz ) ; if ( handler != null ) { return handler . setObjectValue ( stringToObjectConverter , pInner , pAttribute , pValue ) ; } else { throw new IllegalStateException ( "Internal error: No handler found for class " + clazz + " for setting object value." + " (object: " + pInner + ", attribute: " + pAttribute + ", value: " + pValue + ")" ) ; } }
Set an value of an inner object
34,369
void setupContext ( JsonConvertOptions pOpts ) { ObjectSerializationContext stackContext = new ObjectSerializationContext ( pOpts ) ; stackContextLocal . set ( stackContext ) ; }
Setup the context with the limits given in the request or with the default limits if not . In all cases hard limits as defined in the servlet configuration are never exceeded .
34,370
private Extractor getExtractor ( Class pClazz ) { for ( Extractor handler : handlers ) { if ( handler . canSetValue ( ) && handler . getType ( ) != null && handler . getType ( ) . isAssignableFrom ( pClazz ) ) { return handler ; } } return null ; }
Get the extractor for a certain class
34,371
private void addSimplifiers ( List < Extractor > pHandlers , Extractor [ ] pSimplifyHandlers ) { if ( pSimplifyHandlers != null && pSimplifyHandlers . length > 0 ) { pHandlers . addAll ( Arrays . asList ( pSimplifyHandlers ) ) ; } else { pHandlers . addAll ( ServiceObjectFactory . < Extractor > createServiceObjects ( SIMPLIFIERS_DEFAULT_DEF , SIMPLIFIERS_DEF ) ) ; } }
Simplifiers are added either explicitely or by reflection from a subpackage
34,372
JSONObject toJson ( ) { JSONObject ret = new JSONObject ( ) ; ret . put ( "type" , type . name ( ) ) ; if ( targetConfig != null ) { ret . put ( "target" , targetConfig . toJson ( ) ) ; } return ret ; }
Get a JSON representation of this request
34,373
private String nullEscape ( Object pArg ) { if ( pArg == null ) { return "[null]" ; } else if ( pArg instanceof String && ( ( String ) pArg ) . length ( ) == 0 ) { return "\"\"" ; } else if ( pArg instanceof JSONAware ) { return ( ( JSONAware ) pArg ) . toJSONString ( ) ; } else { return pArg . toString ( ) ; } }
null escape used for GET requests
34,374
public static List < DiscoveryIncomingMessage > sendQueryAndCollectAnswers ( DiscoveryOutgoingMessage pOutMsg , int pTimeout , LogHandler pLogHandler ) throws IOException { final List < Future < List < DiscoveryIncomingMessage > > > futures = sendDiscoveryRequests ( pOutMsg , pTimeout , pLogHandler ) ; return collectIncomingMessages ( pTimeout , futures , pLogHandler ) ; }
Sent out a message to Jolokia s multicast group over all network interfaces supporting multicasts
34,375
private static List < Future < List < DiscoveryIncomingMessage > > > sendDiscoveryRequests ( DiscoveryOutgoingMessage pOutMsg , int pTimeout , LogHandler pLogHandler ) throws SocketException , UnknownHostException { List < InetAddress > addresses = getMulticastAddresses ( ) ; ExecutorService executor = Executors . newFixedThreadPool ( addresses . size ( ) ) ; final List < Future < List < DiscoveryIncomingMessage > > > futures = new ArrayList < Future < List < DiscoveryIncomingMessage > > > ( addresses . size ( ) ) ; for ( InetAddress address : addresses ) { DatagramPacket out = pOutMsg . createDatagramPacket ( InetAddress . getByName ( JOLOKIA_MULTICAST_GROUP ) , JOLOKIA_MULTICAST_PORT ) ; Callable < List < DiscoveryIncomingMessage > > findAgentsCallable = new FindAgentsCallable ( address , out , pTimeout , pLogHandler ) ; futures . add ( executor . submit ( findAgentsCallable ) ) ; } executor . shutdownNow ( ) ; return futures ; }
Send requests in parallel threads return the futures for getting the result
34,376
private static List < InetAddress > getMulticastAddresses ( ) throws SocketException , UnknownHostException { List < InetAddress > addresses = NetworkUtil . getMulticastAddresses ( ) ; if ( addresses . size ( ) == 0 ) { throw new UnknownHostException ( "Cannot find address of local host which can be used for sending discovery request" ) ; } return addresses ; }
All addresses which can be used for sending multicast addresses
34,377
private static List < DiscoveryIncomingMessage > collectIncomingMessages ( int pTimeout , List < Future < List < DiscoveryIncomingMessage > > > pFutures , LogHandler pLogHandler ) throws UnknownHostException { List < DiscoveryIncomingMessage > ret = new ArrayList < DiscoveryIncomingMessage > ( ) ; Set < String > seen = new HashSet < String > ( ) ; int nrCouldntSend = 0 ; for ( Future < List < DiscoveryIncomingMessage > > future : pFutures ) { try { List < DiscoveryIncomingMessage > inMsgs = future . get ( pTimeout + 500 , TimeUnit . MILLISECONDS ) ; for ( DiscoveryIncomingMessage inMsg : inMsgs ) { AgentDetails details = inMsg . getAgentDetails ( ) ; String id = details . getAgentId ( ) ; if ( ! seen . contains ( id ) ) { ret . add ( inMsg ) ; seen . add ( id ) ; } } } catch ( InterruptedException exp ) { } catch ( ExecutionException e ) { Throwable exp = e . getCause ( ) ; if ( exp instanceof CouldntSendDiscoveryPacketException ) { nrCouldntSend ++ ; pLogHandler . debug ( " + ( ( CouldntSendDiscoveryPacketException ) exp ) . getAddress ( ) + ": " + exp . getCause ( ) ) ; } pLogHandler . debug ( " + e ) ; } catch ( TimeoutException e ) { } } if ( nrCouldntSend == pFutures . size ( ) ) { throw new UnknownHostException ( "Cannot send a single multicast recovery request on any multicast enabled interface" ) ; } return ret ; }
Collect the incoming messages and filter out duplicates
34,378
private static int joinMcGroupsOnAllNetworkInterfaces ( MulticastSocket pSocket , InetSocketAddress pSocketAddress , LogHandler pLogHandler ) throws IOException { Enumeration < NetworkInterface > nifs = NetworkInterface . getNetworkInterfaces ( ) ; int interfacesJoined = 0 ; while ( nifs . hasMoreElements ( ) ) { NetworkInterface n = nifs . nextElement ( ) ; if ( NetworkUtil . isMulticastSupported ( n ) ) { try { pSocket . joinGroup ( pSocketAddress , n ) ; interfacesJoined ++ ; } catch ( IOException exp ) { pLogHandler . info ( "Cannot join multicast group on NIF " + n . getDisplayName ( ) + ": " + exp . getMessage ( ) ) ; } } } return interfacesJoined ; }
We are using all interfaces available and try to join them
34,379
public boolean check ( String [ ] pHostOrAddresses ) { if ( allowedHostsSet == null ) { return true ; } for ( String addr : pHostOrAddresses ) { if ( allowedHostsSet . contains ( addr ) ) { return true ; } if ( allowedSubnetsSet != null && IP_PATTERN . matcher ( addr ) . matches ( ) ) { for ( String subnet : allowedSubnetsSet ) { if ( IpChecker . matches ( subnet , addr ) ) { return true ; } } } } return false ; }
Check for one or more hosts .
34,380
public Object setObjectValue ( StringToObjectConverter pConverter , Object pMap , String pKey , Object pValue ) throws IllegalAccessException , InvocationTargetException { Map < Object , Object > map = ( Map < Object , Object > ) pMap ; Object oldValue = null ; Object oldKey = pKey ; for ( Map . Entry entry : map . entrySet ( ) ) { if ( pKey . equals ( entry . getKey ( ) . toString ( ) ) ) { oldValue = entry . getValue ( ) ; oldKey = entry . getKey ( ) ; break ; } } Object value = oldValue != null ? pConverter . prepareValue ( oldValue . getClass ( ) . getName ( ) , pValue ) : pValue ; map . put ( oldKey , value ) ; return oldValue ; }
Set the value within a map where the attribute is taken as key into the map .
34,381
public String get ( ConfigKey pKey ) { String value = params . get ( pKey ) ; if ( value != null ) { return value ; } else { return pKey . getDefaultValue ( ) ; } }
Get a processing parameter
34,382
public ProcessingParameters mergedParams ( Map < String , String > pConfig ) { if ( pConfig == null ) { return this ; } else { Map < ConfigKey , String > newParams = new HashMap < ConfigKey , String > ( ) ; newParams . putAll ( params ) ; newParams . putAll ( convertToConfigMap ( pConfig ) ) ; return new ProcessingParameters ( newParams , pathInfo ) ; } }
Merge in a configuration and return a ProcessingParameters object representing the merged values
34,383
static Map < ConfigKey , String > convertToConfigMap ( Map < String , String > pParams ) { Map < ConfigKey , String > config = new HashMap < ConfigKey , String > ( ) ; if ( pParams != null ) { for ( Map . Entry < String , ? > entry : pParams . entrySet ( ) ) { ConfigKey cKey = ConfigKey . getRequestConfigKey ( entry . getKey ( ) ) ; if ( cKey != null ) { Object value = entry . getValue ( ) ; config . put ( cKey , value != null ? value . toString ( ) : null ) ; } } } return config ; }
map to a ConfigKey are filtered out
34,384
public JSONAware handleGetRequest ( String pUri , String pPathInfo , Map < String , String [ ] > pParameterMap ) { String pathInfo = extractPathInfo ( pUri , pPathInfo ) ; JmxRequest jmxReq = JmxRequestFactory . createGetRequest ( pathInfo , getProcessingParameter ( pParameterMap ) ) ; if ( backendManager . isDebug ( ) ) { logHandler . debug ( "URI: " + pUri ) ; logHandler . debug ( "Path-Info: " + pathInfo ) ; logHandler . debug ( "Request: " + jmxReq . toString ( ) ) ; } return executeRequest ( jmxReq ) ; }
Handle a GET request
34,385
public JSONAware handlePostRequest ( String pUri , InputStream pInputStream , String pEncoding , Map < String , String [ ] > pParameterMap ) throws IOException { if ( backendManager . isDebug ( ) ) { logHandler . debug ( "URI: " + pUri ) ; } Object jsonRequest = extractJsonRequest ( pInputStream , pEncoding ) ; if ( jsonRequest instanceof JSONArray ) { List < JmxRequest > jmxRequests = JmxRequestFactory . createPostRequests ( ( List ) jsonRequest , getProcessingParameter ( pParameterMap ) ) ; JSONArray responseList = new JSONArray ( ) ; for ( JmxRequest jmxReq : jmxRequests ) { if ( backendManager . isDebug ( ) ) { logHandler . debug ( "Request: " + jmxReq . toString ( ) ) ; } JSONObject resp = executeRequest ( jmxReq ) ; responseList . add ( resp ) ; } return responseList ; } else if ( jsonRequest instanceof JSONObject ) { JmxRequest jmxReq = JmxRequestFactory . createPostRequest ( ( Map < String , ? > ) jsonRequest , getProcessingParameter ( pParameterMap ) ) ; return executeRequest ( jmxReq ) ; } else { throw new IllegalArgumentException ( "Invalid JSON Request " + jsonRequest ) ; } }
Handle the input stream as given by a POST request
34,386
public JSONObject getErrorJSON ( int pErrorCode , Throwable pExp , JmxRequest pJmxReq ) { JSONObject jsonObject = new JSONObject ( ) ; jsonObject . put ( "status" , pErrorCode ) ; jsonObject . put ( "error" , getExceptionMessage ( pExp ) ) ; jsonObject . put ( "error_type" , pExp . getClass ( ) . getName ( ) ) ; addErrorInfo ( jsonObject , pExp , pJmxReq ) ; if ( backendManager . isDebug ( ) ) { backendManager . error ( "Error " + pErrorCode , pExp ) ; } if ( pJmxReq != null ) { jsonObject . put ( "request" , pJmxReq . toJSON ( ) ) ; } return jsonObject ; }
Get the JSON representation for a an exception
34,387
public String extractCorsOrigin ( String pOrigin ) { if ( pOrigin != null ) { String origin = pOrigin . replaceAll ( "[\\n\\r]*" , "" ) ; if ( backendManager . isOriginAllowed ( origin , false ) ) { return "null" . equals ( origin ) ? "*" : origin ; } else { return null ; } } return null ; }
Check whether for the given host is a cross - browser request allowed . This check is delegated to the backendmanager which is responsible for the security configuration . Also some sanity checks are applied .
34,388
private String getExceptionMessage ( Throwable pException ) { String message = pException . getLocalizedMessage ( ) ; return pException . getClass ( ) . getName ( ) + ( message != null ? " : " + message : "" ) ; }
Extract class and exception message for an error message
34,389
private JSONObject errorForUnwrappedException ( Exception e , JmxRequest pJmxReq ) { Throwable cause = e . getCause ( ) ; int code = cause instanceof IllegalArgumentException ? 400 : cause instanceof SecurityException ? 403 : 500 ; return getErrorJSON ( code , cause , pJmxReq ) ; }
and extract the error code accordingly
34,390
protected Set < ObjectName > searchMBeans ( MBeanServerExecutor pMBeanServerExecutor , String pMbeanPattern ) { try { ObjectName oName = new ObjectName ( pMbeanPattern ) ; return pMBeanServerExecutor . queryNames ( oName ) ; } catch ( MalformedObjectNameException e ) { return new HashSet < ObjectName > ( ) ; } catch ( IOException e ) { return new HashSet < ObjectName > ( ) ; } }
Check for the existence of a certain MBean . All known MBeanServers are queried
34,391
protected String getSingleStringAttribute ( MBeanServerExecutor pMBeanServerExecutor , String pMBeanName , String pAttribute ) { Set < ObjectName > serverMBeanNames = searchMBeans ( pMBeanServerExecutor , pMBeanName ) ; if ( serverMBeanNames . size ( ) == 0 ) { return null ; } Set < String > attributeValues = new HashSet < String > ( ) ; for ( ObjectName oName : serverMBeanNames ) { String val = getAttributeValue ( pMBeanServerExecutor , oName , pAttribute ) ; if ( val != null ) { attributeValues . add ( val ) ; } } if ( attributeValues . size ( ) == 0 || attributeValues . size ( ) > 1 ) { return null ; } return attributeValues . iterator ( ) . next ( ) ; }
Get a single attribute for a given MBeanName pattern .
34,392
protected String getVersionFromJsr77 ( MBeanServerExecutor pMbeanServers ) { Set < ObjectName > names = searchMBeans ( pMbeanServers , "*:j2eeType=J2EEServer,*" ) ; if ( names . size ( ) > 0 ) { return getAttributeValue ( pMbeanServers , names . iterator ( ) . next ( ) , "serverVersion" ) ; } return null ; }
Get the version number from a JSR - 77 compliant server
34,393
protected boolean isClassLoaded ( String className , Instrumentation instrumentation ) { if ( instrumentation == null || className == null ) { throw new IllegalArgumentException ( "instrumentation and className must not be null" ) ; } Class < ? > [ ] classes = instrumentation . getAllLoadedClasses ( ) ; for ( Class < ? > c : classes ) { if ( className . equals ( c . getName ( ) ) ) { return true ; } } return false ; }
Tests if the given class name has been loaded by the JVM . Don t use this method in case you have access to the class loader which will be loading the class because the used approach is not very efficient .
34,394
public final J4pClientBuilder proxy ( String pProxyHost , int pProxyPort , String pProxyUser , String pProxyPass ) { httpProxy = new Proxy ( pProxyHost , pProxyPort , pProxyUser , pProxyPass ) ; return this ; }
Set the proxy for this client
34,395
public final J4pClientBuilder useProxyFromEnvironment ( ) { Map < String , String > env = System . getenv ( ) ; for ( String key : env . keySet ( ) ) { if ( key . equalsIgnoreCase ( "http_proxy" ) ) { httpProxy = parseProxySettings ( env . get ( key ) ) ; break ; } } return this ; }
Set the proxy for this client based on http_proxy system environment variable
34,396
public J4pClient build ( ) { return new J4pClient ( url , createHttpClient ( ) , targetUrl != null ? new J4pTargetConfig ( targetUrl , targetUser , targetPassword ) : null , responseExtractor ) ; }
Build the agent with the information given before
34,397
static Proxy parseProxySettings ( String spec ) { try { if ( spec == null || spec . length ( ) == 0 ) { return null ; } return new Proxy ( spec ) ; } catch ( URISyntaxException e ) { return null ; } }
Parse proxy specification and return a proxy object representing the proxy configuration .
34,398
public static < T > T newInstance ( String pClassName , Object ... pArguments ) { Class < T > clazz = classForName ( pClassName ) ; if ( clazz == null ) { throw new IllegalArgumentException ( "Cannot find " + pClassName ) ; } return newInstance ( clazz , pArguments ) ; }
Instantiate an instance of the given class with its default constructor . The context class loader is used to lookup the class
34,399
public static < T > T newInstance ( Class < T > pClass , Object ... pArguments ) { try { if ( pClass != null ) { if ( pArguments . length == 0 ) { return pClass . newInstance ( ) ; } else { Constructor < T > ctr = lookupConstructor ( pClass , pArguments ) ; return ctr . newInstance ( pArguments ) ; } } else { throw new IllegalArgumentException ( "Given class must not be null" ) ; } } catch ( InstantiationException e ) { throw new IllegalArgumentException ( "Cannot instantiate " + pClass + ": " + e , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( "Cannot instantiate " + pClass + ": " + e , e ) ; } catch ( NoSuchMethodException e ) { throw new IllegalArgumentException ( "Cannot instantiate " + pClass + ": " + e , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalArgumentException ( "Cannot instantiate " + pClass + ": " + e , e ) ; } }
Instantiate an instance of the given class with its default constructor