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 ( pHt...
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...
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 Jetty...
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 ( "+...
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 ...
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 ( pSignat...
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 , opInf...
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 ( ...
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 == ...
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 ...
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...
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 ...
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 ) ; } }...
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_ENABL...
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 ...
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 . sanitizeL...
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 ...
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" , "tru...
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 request...
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 ( ge...
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 " + ...
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 , op...
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 vmDe...
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 m...
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 ...
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 . addMBeanRegistrationList...
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 ) { th...
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 ...
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 { fi...
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 . T...
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 ) ; i...
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 ( ) , ...
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 ( ) ) ; Li...
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 ) ; ini...
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...
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 ( detectorOp...
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 . registerMB...
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 != ...
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 ( ) ) ; } ...
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 . spli...
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 ) ; } Arr...
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 no...
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 . ...
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 ( ) . getT...
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 [ ] = conve...
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 . ...
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 Ille...
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 , pOp...
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 ) ; } Extract...
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 ( S...
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 collectIn...
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 . newF...
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 di...
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 =...
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 ( ) ) { Netwo...
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 : allowedSub...
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 . ent...
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 ProcessingPara...
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 . ...
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 ( )...
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 ( js...
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 ( ) ) ; addErr...
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 ( ...
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 HashS...
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 < ?...
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...
Instantiate an instance of the given class with its default constructor