idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
34,400
public static Object applyMethod ( Object pObject , String pMethod , Object ... pArgs ) { Class < ? > clazz = pObject . getClass ( ) ; try { Method method = extractMethod ( pMethod , clazz , pArgs ) ; return method . invoke ( pObject , pArgs ) ; } catch ( NoSuchMethodException e ) { throw new IllegalArgumentException (...
Apply a method to a given object with optional arguments . The method is looked up the whole class hierarchy .
34,401
public static Set < String > getResources ( String pResource ) throws IOException { List < ClassLoader > clls = findClassLoaders ( ) ; if ( clls . size ( ) != 0 ) { Set < String > ret = new HashSet < String > ( ) ; for ( ClassLoader cll : clls ) { Enumeration < URL > urlEnum = cll . getResources ( pResource ) ; ret . a...
Get all resources from the classpath which are specified by the given path .
34,402
private static < T > Constructor < T > lookupConstructor ( Class < T > clazz , Object [ ] pArguments ) throws NoSuchMethodException { Class [ ] argTypes = extractArgumentTypes ( pArguments ) ; return clazz . getConstructor ( argTypes ) ; }
Lookup appropriate constructor
34,403
public static Date fromISO8601 ( String pDateString ) { if ( datatypeFactory != null ) { return datatypeFactory . newXMLGregorianCalendar ( pDateString . trim ( ) ) . toGregorianCalendar ( ) . getTime ( ) ; } else { try { String date = pDateString . replaceFirst ( "([+-])(0\\d)\\:(\\d{2})$" , "$1$2$3" ) ; date = date ....
Parse an ISO - 8601 string into an date object
34,404
public static String toISO8601 ( Date pDate , TimeZone pTimeZone ) { SimpleDateFormat dateFormat = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ssZ" ) ; dateFormat . setTimeZone ( pTimeZone ) ; String ret = dateFormat . format ( pDate ) ; ret = ret . replaceAll ( "\\+0000$" , "Z" ) ; return ret . replaceAll ( "(\\d\\d)$"...
Convert a given date to an ISO - 8601 compliant string representation for a given timezone
34,405
public static void streamResponseAndClose ( Writer pWriter , JSONStreamAware pJson , String callback ) throws IOException { try { if ( callback == null ) { pJson . writeJSONString ( pWriter ) ; } else { pWriter . write ( callback ) ; pWriter . write ( "(" ) ; pJson . writeJSONString ( pWriter ) ; pWriter . write ( ");"...
Stream a JSON stream to a given writer potentiall wrap it in a callback for a JSONP response and then flush & close the writer . The writer is closed in any case also when an exception occurs
34,406
public int getParameterAsInt ( ConfigKey pConfigKey ) { String intValueS = processingConfig . get ( pConfigKey ) ; if ( intValueS != null ) { return Integer . parseInt ( intValueS ) ; } else { return 0 ; } }
Get a processing configuration as integer or null if not set
34,407
public Boolean getParameterAsBool ( ConfigKey pConfigKey ) { String booleanS = getParameter ( pConfigKey ) ; return Boolean . parseBoolean ( booleanS != null ? booleanS : pConfigKey . getDefaultValue ( ) ) ; }
Get a processing configuration as a boolean value
34,408
public JSONObject toJSON ( ) { JSONObject ret = new JSONObject ( ) ; ret . put ( "type" , type . getName ( ) ) ; if ( targetConfig != null ) { ret . put ( "target" , targetConfig . toJSON ( ) ) ; } if ( pathParts != null ) { try { ret . put ( "path" , getPath ( ) ) ; } catch ( UnsupportedOperationException exp ) { } } ...
Convert this request to a JSON object which can be used as a part of a return value .
34,409
private void initParameters ( ProcessingParameters pParams ) { processingConfig = pParams ; String ignoreErrors = processingConfig . get ( ConfigKey . IGNORE_ERRORS ) ; if ( ignoreErrors != null && ignoreErrors . matches ( "^(true|yes|on|1)$" ) ) { valueFaultHandler = ValueFaultHandler . IGNORING_VALUE_FAULT_HANDLER ; ...
Init parameters and value fault handler
34,410
protected List < String > prepareExtraArgs ( Stack < String > pElements ) { if ( pElements == null || pElements . size ( ) == 0 ) { return null ; } List < String > ret = new ArrayList < String > ( ) ; while ( ! pElements . isEmpty ( ) ) { String element = pElements . pop ( ) ; ret . add ( "*" . equals ( element ) ? nul...
Extract extra arguments from the remaining element on the stack .
34,411
private static String extractPathInfo ( String pPathInfo , ProcessingParameters pProcessingParams ) { String pathInfo = pPathInfo ; if ( pProcessingParams != null && ( pPathInfo == null || pPathInfo . length ( ) == 0 || pathInfo . matches ( "^/+$" ) ) ) { pathInfo = pProcessingParams . getPathInfo ( ) ; } return normal...
Extract path info either from the real URL path or from an request parameter
34,412
private static String normalizePathInfo ( String pPathInfo ) { if ( pPathInfo != null && pPathInfo . length ( ) > 0 ) { return pPathInfo . startsWith ( "/" ) ? pPathInfo . substring ( 1 ) : pPathInfo ; } else { return "" ; } }
Return always a non - null string and strip of leading slash
34,413
private static RequestCreator getCreator ( RequestType pType ) { RequestCreator creator = CREATOR_MAP . get ( pType ) ; if ( creator == null ) { throw new UnsupportedOperationException ( "Type " + pType + " is not supported (yet)" ) ; } return creator ; }
Get the request creator for a specific type
34,414
public static boolean isValidCallback ( String pCallback ) { Pattern validJavaScriptFunctionNamePattern = Pattern . compile ( "^[$A-Z_][0-9A-Z_$]*$" , Pattern . CASE_INSENSITIVE ) ; return validJavaScriptFunctionNamePattern . matcher ( pCallback ) . matches ( ) ; }
Check that a callback matches a javascript function name . The argument must be not null
34,415
public static PolicyRestrictor lookupPolicyRestrictor ( String pLocation ) throws IOException { InputStream is ; if ( pLocation . startsWith ( "classpath:" ) ) { String path = pLocation . substring ( "classpath:" . length ( ) ) ; is = ClassUtil . getResourceAsStream ( path ) ; if ( is == null ) { is = RestrictorFactory...
Lookup a restrictor based on an URL
34,416
void update ( JSONObject pJSONObject , MBeanInfo pMBeanInfo , Stack < String > pPathStack ) { boolean isPathEmpty = pPathStack == null || pPathStack . empty ( ) ; String filter = pPathStack != null && ! pPathStack . empty ( ) ? pPathStack . pop ( ) : null ; verifyThatPathIsEmpty ( pPathStack ) ; JSONObject attrMap = ex...
Update the given JSON object with the data extracted from the given MBeanInfo
34,417
protected void verifyThatPathIsEmpty ( Stack < String > pPathStack ) { if ( pPathStack != null && pPathStack . size ( ) > 0 ) { throw new IllegalArgumentException ( "Path contains extra elements not usable for a list request: " + pPathStack ) ; } }
Check whether the given path is empty if not then throw an exception
34,418
private void checkCertForClientUsage ( X509Certificate clientCert ) { try { if ( extendedClientCheck && ( clientCert . getExtendedKeyUsage ( ) == null || ! clientCert . getExtendedKeyUsage ( ) . contains ( CLIENTAUTH_OID ) ) ) { throw new SecurityException ( "No extended key usage available" ) ; } } catch ( Certificate...
If an empty list as allowedPrincipals is given no one is allowed to access
34,419
private boolean checkRestrictorService ( RestrictorCheck pCheck , Object ... args ) { try { ServiceReference [ ] serviceRefs = bundleContext . getServiceReferences ( Restrictor . class . getName ( ) , null ) ; if ( serviceRefs != null ) { boolean ret = true ; boolean found = false ; for ( ServiceReference serviceRef : ...
Actual check which delegate to one or more restrictor services if available .
34,420
public void log ( String pMessage , Throwable pThrowable ) { add ( System . currentTimeMillis ( ) / 1000 , pMessage , pThrowable ) ; }
Store the given message in this store if debug is switched on
34,421
public String debugInfo ( ) { if ( ! isDebug || debugEntries . size ( ) == 0 ) { return "" ; } StringBuffer ret = new StringBuffer ( ) ; for ( int i = debugEntries . size ( ) - 1 ; i >= 0 ; i -- ) { Entry entry = debugEntries . get ( i ) ; ret . append ( entry . timestamp ) . append ( ": " ) . append ( entry . message ...
Get back all previously logged and stored debug messages
34,422
private synchronized void add ( long pTime , String message ) { debugEntries . addFirst ( new Entry ( pTime , message ) ) ; trim ( ) ; }
add a message along with a time stamp
34,423
public void updateGlobalConfiguration ( ConfigExtractor pExtractor ) { Enumeration e = pExtractor . getNames ( ) ; while ( e . hasMoreElements ( ) ) { String keyS = ( String ) e . nextElement ( ) ; ConfigKey key = ConfigKey . getGlobalConfigKey ( keyS ) ; if ( key != null ) { globalConfig . put ( key , pExtractor . get...
Update the configuration hold by this object
34,424
public void updateGlobalConfiguration ( Map < String , String > pConfig ) { for ( ConfigKey c : ConfigKey . values ( ) ) { if ( c . isGlobalConfig ( ) ) { String value = pConfig . get ( c . getKeyValue ( ) ) ; if ( value != null ) { globalConfig . put ( c , value ) ; } } } }
Update this global configuration from a string - string . Only the known keys are taken from this map
34,425
public String get ( ConfigKey pKey ) { String value = globalConfig . get ( pKey ) ; if ( value == null ) { value = pKey . getDefaultValue ( ) ; } return value ; }
Get a configuration value if set as configuration or the default value if not
34,426
public int getAsInt ( ConfigKey pKey ) { int ret ; try { ret = Integer . parseInt ( get ( pKey ) ) ; } catch ( NumberFormatException exp ) { ret = Integer . parseInt ( pKey . getDefaultValue ( ) ) ; } return ret ; }
Get an configuration value as int value
34,427
public ProcessingParameters getProcessingParameters ( Map < String , String > pParams ) { Map < ConfigKey , String > procParams = ProcessingParameters . convertToConfigMap ( pParams ) ; for ( Map . Entry < ConfigKey , String > entry : globalConfig . entrySet ( ) ) { ConfigKey key = entry . getKey ( ) ; if ( key . isReq...
Get processing parameters from a string - string map
34,428
private Thread [ ] enumerateThreads ( ) { boolean fits = false ; int inc = 50 ; Thread [ ] threads = null ; int nrThreads = 0 ; while ( ! fits ) { try { threads = new Thread [ Thread . activeCount ( ) + inc ] ; nrThreads = Thread . enumerate ( threads ) ; fits = true ; } catch ( ArrayIndexOutOfBoundsException exp ) { i...
Enumerate all active threads
34,429
private boolean joinThreads ( Thread pThreads [ ] ) { for ( int i = 0 ; i < pThreads . length ; i ++ ) { final Thread t = pThreads [ i ] ; if ( t . isDaemon ( ) || t . getThreadGroup ( ) == null || t . getThreadGroup ( ) . equals ( threadGroup ) || checkExcludedNames ( t . getName ( ) ) ) { continue ; } try { t . join ...
Join threads return false if only our own threads are left .
34,430
public synchronized HttpContext getHttpContext ( ) { if ( jolokiaHttpContext == null ) { final String user = getConfiguration ( USER ) ; final String authMode = getConfiguration ( AUTH_MODE ) ; if ( user == null ) { if ( ServiceAuthenticationHttpContext . shouldBeUsed ( authMode ) ) { jolokiaHttpContext = new ServiceAu...
Get the security context for out servlet . Dependent on the configuration this is either a no - op context or one which authenticates with a given user
34,431
private Dictionary < String , String > getConfiguration ( ) { Dictionary < String , String > config = new Hashtable < String , String > ( ) ; for ( ConfigKey key : ConfigKey . values ( ) ) { String value = getConfiguration ( key ) ; if ( value != null ) { config . put ( key . getKeyValue ( ) , value ) ; } } String jolo...
Customizer for registering servlet at a HttpService
34,432
void push ( Object object ) { callStack . push ( object ) ; if ( object != null && ! SIMPLE_TYPES . contains ( object . getClass ( ) ) ) { objectsInCallStack . add ( object ) ; } objectCount ++ ; }
Push a new object on the stack
34,433
Object pop ( ) { Object ret = callStack . pop ( ) ; if ( ret != null && ! SIMPLE_TYPES . contains ( ret . getClass ( ) ) ) { objectsInCallStack . remove ( ret ) ; } return ret ; }
Remove an object from top of the call stack
34,434
private void extractMbeanConfiguration ( NodeList pNodes , MBeanPolicyConfig pConfig ) throws MalformedObjectNameException { for ( int i = 0 ; i < pNodes . getLength ( ) ; i ++ ) { Node node = pNodes . item ( i ) ; if ( node . getNodeType ( ) != Node . ELEMENT_NODE ) { continue ; } extractPolicyConfig ( pConfig , node ...
Extract configuration and put it into a given MBeanPolicyConfig
34,435
private boolean wildcardMatch ( Set < String > pValues , String pValue ) { for ( String pattern : pValues ) { if ( pattern . contains ( "*" ) && pValue . matches ( pattern . replaceAll ( "\\*" , ".*" ) ) ) { return true ; } } return false ; }
Check whether a value matches patterns in pValues
34,436
private String extractVersionFromFullVersion ( String pFullVersion ) { if ( pFullVersion != null ) { Matcher matcher = GLASSFISH_VERSION . matcher ( pFullVersion ) ; if ( matcher . matches ( ) ) { serverName = GLASSFISH_NAME ; vendorName = GLASSFISH_VENDOR_NAME ; return matcher . group ( 1 ) ; } matcher = PAYARA_VERSIO...
Tries to match Glassfish first then Payara Server updating server and vendor name
34,437
private synchronized boolean bootAmx ( MBeanServerExecutor pServers , final LogHandler pLoghandler ) { ObjectName bootMBean = null ; try { bootMBean = new ObjectName ( "amx-support:type=boot-amx" ) ; } catch ( MalformedObjectNameException e ) { } try { pServers . call ( bootMBean , new MBeanServerExecutor . MBeanAction...
Return true if AMX could be booted false otherwise
34,438
protected final void addExtractor ( String pName , AttributeExtractor < T > pExtractor ) { extractorMap . put ( pName , pExtractor ) ; }
Add a single extractor
34,439
public synchronized void setGlobalMaxEntries ( int pGlobalMaxEntries ) { globalMaxEntries = pGlobalMaxEntries ; for ( HistoryEntry entry : historyStore . values ( ) ) { entry . setMaxEntries ( globalMaxEntries ) ; } }
Set the global maximum limit for history entries .
34,440
public synchronized void configure ( HistoryKey pKey , HistoryLimit pHistoryLimit ) { if ( pHistoryLimit == null ) { removeEntries ( pKey ) ; return ; } HistoryLimit limit = pHistoryLimit . respectGlobalMaxEntries ( globalMaxEntries ) ; if ( pKey . isMBeanPattern ( ) ) { patterns . put ( pKey , limit ) ; for ( HistoryK...
Configure the history length for a specific entry . If the length is 0 disable history for this key . Please note that this method might change the limit object so the ownership of this object goes over to the callee .
34,441
public synchronized void updateAndAdd ( JmxRequest pJmxReq , JSONObject pJson ) { long timestamp = System . currentTimeMillis ( ) / 1000 ; pJson . put ( KEY_TIMESTAMP , timestamp ) ; RequestType type = pJmxReq . getType ( ) ; HistoryUpdater updater = historyUpdaters . get ( type ) ; if ( updater != null ) { updater . u...
Update the history store with the value of an an read write or execute operation . Also the timestamp of the insertion is recorded . Also the recorded history values are added to the given json value .
34,442
public synchronized int getSize ( ) { try { ByteArrayOutputStream bOut = new ByteArrayOutputStream ( ) ; ObjectOutputStream oOut = new ObjectOutputStream ( bOut ) ; oOut . writeObject ( historyStore ) ; bOut . close ( ) ; return bOut . size ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Cannot ser...
Get the size of this history store in bytes
34,443
private void initHistoryUpdaters ( ) { historyUpdaters . put ( RequestType . EXEC , new HistoryUpdater < JmxExecRequest > ( ) { public void updateHistory ( JSONObject pJson , JmxExecRequest request , long pTimestamp ) { HistoryEntry entry = historyStore . get ( new HistoryKey ( request ) ) ; if ( entry != null ) { sync...
A set of updaters which are dispatched to for certain request types
34,444
private void updateReadHistory ( JmxReadRequest pJmxReq , JSONObject pJson , long pTimestamp ) { ObjectName name = pJmxReq . getObjectName ( ) ; if ( name . isPattern ( ) ) { Map < String , Object > values = ( Map < String , Object > ) pJson . get ( KEY_VALUE ) ; if ( values != null ) { JSONObject history = updateHisto...
return multiple values with a single request
34,445
private JSONObject addAttributeFromSingleValue ( HistoryKey pKey , String pAttrName , Object pValue , long pTimestamp ) { HistoryEntry entry = getEntry ( pKey , pValue , pTimestamp ) ; return entry != null ? addToHistoryEntryAndGetCurrentHistory ( new JSONObject ( ) , entry , pAttrName , pValue , pTimestamp ) : null ; ...
Return a fresh map
34,446
private < R extends J4pResponse < T > , T extends J4pRequest > List < R > extractResponses ( JSONAware pJsonResponse , List < T > pRequests , J4pResponseExtractor pResponseExtractor ) throws J4pException { JSONArray responseArray = ( JSONArray ) pJsonResponse ; List < R > ret = new ArrayList < R > ( responseArray . siz...
Extract J4pResponses from a returned bulk JSON answer
34,447
private J4pException mapException ( Exception pException ) throws J4pException { if ( pException instanceof ConnectException ) { return new J4pConnectException ( "Cannot connect to " + requestHandler . getJ4pServerUrl ( ) + ": " + pException . getMessage ( ) , ( ConnectException ) pException ) ; } else if ( pException ...
Map IO - Exceptions accordingly
34,448
private void verifyBulkJsonResponse ( JSONAware pJsonResponse ) throws J4pException { if ( ! ( pJsonResponse instanceof JSONArray ) ) { if ( pJsonResponse instanceof JSONObject ) { JSONObject errorObject = ( JSONObject ) pJsonResponse ; if ( ! errorObject . containsKey ( "status" ) || ( Long ) errorObject . get ( "stat...
Verify the returned JSON answer .
34,449
public JSONObject handleRequest ( JmxRequest pJmxReq ) throws InstanceNotFoundException , AttributeNotFoundException , ReflectionException , MBeanException , IOException { lazyInitIfNeeded ( ) ; boolean debug = isDebug ( ) ; long time = 0 ; if ( debug ) { time = System . currentTimeMillis ( ) ; } JSONObject json ; try ...
Handle a single JMXRequest . The response status is set to 200 if the request was successful
34,450
public Object convertExceptionToJson ( Throwable pExp , JmxRequest pJmxReq ) { JsonConvertOptions opts = getJsonConvertOptions ( pJmxReq ) ; try { JSONObject expObj = ( JSONObject ) converters . getToJsonConverter ( ) . convertToJson ( pExp , null , opts ) ; return expObj ; } catch ( AttributeNotFoundException e ) { re...
Convert a Throwable to a JSON object so that it can be included in an error response
34,451
public boolean isRemoteAccessAllowed ( String pRemoteHost , String pRemoteAddr ) { return restrictor . isRemoteAccessAllowed ( pRemoteHost != null ? new String [ ] { pRemoteHost , pRemoteAddr } : new String [ ] { pRemoteAddr } ) ; }
Check whether remote access from the given client is allowed .
34,452
public void info ( String msg ) { logHandler . info ( msg ) ; if ( debugStore != null ) { debugStore . log ( msg ) ; } }
Log at info level
34,453
public void debug ( String msg ) { logHandler . debug ( msg ) ; if ( debugStore != null ) { debugStore . log ( msg ) ; } }
Log at debug level
34,454
private void init ( Configuration pConfig ) { converters = new Converters ( ) ; initLimits ( pConfig ) ; localDispatcher = new LocalRequestDispatcher ( converters , restrictor , pConfig , logHandler ) ; ServerHandle serverHandle = localDispatcher . getServerHandle ( ) ; requestDispatchers = createRequestDispatchers ( p...
Initialize this object ;
34,455
private List < RequestDispatcher > createRequestDispatchers ( Configuration pConfig , Converters pConverters , ServerHandle pServerHandle , Restrictor pRestrictor ) { List < RequestDispatcher > ret = new ArrayList < RequestDispatcher > ( ) ; String classes = pConfig != null ? pConfig . get ( DISPATCHER_CLASSES ) : null...
a list an empty one if no request dispatcher should be created
34,456
private RequestDispatcher createDispatcher ( String pDispatcherClass , Converters pConverters , ServerHandle pServerHandle , Restrictor pRestrictor , Configuration pConfig ) { try { Class clazz = ClassUtil . classForName ( pDispatcherClass , getClass ( ) . getClassLoader ( ) ) ; if ( clazz == null ) { throw new Illegal...
Create a single dispatcher
34,457
private JSONObject callRequestDispatcher ( JmxRequest pJmxReq ) throws InstanceNotFoundException , AttributeNotFoundException , ReflectionException , MBeanException , IOException , NotChangedException { Object retValue = null ; boolean useValueWithPath = false ; boolean found = false ; for ( RequestDispatcher dispatche...
call the an appropriate request dispatcher
34,458
private void initMBeans ( Configuration pConfig ) { int maxEntries = pConfig . getAsInt ( HISTORY_MAX_ENTRIES ) ; int maxDebugEntries = pConfig . getAsInt ( DEBUG_MAX_ENTRIES ) ; historyStore = new HistoryStore ( maxEntries ) ; debugStore = new DebugStore ( maxDebugEntries , pConfig . getAsBoolean ( DEBUG ) ) ; try { l...
init various application wide stores for handling history and debug output .
34,459
private void intError ( String message , Throwable t ) { logHandler . error ( message , t ) ; debugStore . log ( message , t ) ; }
Final private error log for use in the constructor above
34,460
public static File lookupJarFile ( ) { try { return new File ( OptionsAndArgs . class . getProtectionDomain ( ) . getCodeSource ( ) . getLocation ( ) . toURI ( ) ) ; } catch ( URISyntaxException e ) { throw new IllegalStateException ( "Error: Cannot lookup jar for this class: " + e , e ) ; } }
Lookup the JAR File from where this class is loaded
34,461
private String getNextListIndexSuffix ( Map < String , String > options , String key ) { if ( ! options . containsKey ( key ) ) { return "" ; } else { int i = 1 ; while ( options . containsKey ( key + "." + i ) ) { i ++ ; } return "." + i ; } }
check for the next key with a suffix like . 1 which is not already set
34,462
private void init ( Set < String > pCommands , String ... pArgs ) { quiet = options . containsKey ( "quiet" ) ; verbose = options . containsKey ( "verbose" ) ; jarFile = lookupJarFile ( ) ; extraArgs = checkCommandAndArgs ( pCommands , pArgs ) ; }
Initialise default command and validate
34,463
public int dispatchCommand ( Object pVm , VirtualMachineHandler pHandler ) throws InvocationTargetException , NoSuchMethodException , IllegalAccessException { String commandName = options . getCommand ( ) ; AbstractBaseCommand command = COMMANDS . get ( commandName ) ; if ( command == null ) { throw new IllegalArgument...
Dispatch the command
34,464
public < R extends JmxRequest > Object handleRequest ( JsonRequestHandler < R > pRequestHandler , R pJmxReq ) throws MBeanException , ReflectionException , AttributeNotFoundException , InstanceNotFoundException , NotChangedException { AttributeNotFoundException attrException = null ; InstanceNotFoundException objNotFou...
Handle a single request
34,465
public String encrypt ( final String pText ) throws GeneralSecurityException { byte [ ] clearBytes = pText . getBytes ( Charset . forName ( "UTF-8" ) ) ; byte [ ] salt = getSalt ( SALT_SIZE ) ; Cipher cipher = createCipher ( salt , Cipher . ENCRYPT_MODE ) ; byte [ ] encryptedBytes = cipher . doFinal ( clearBytes ) ; in...
Encrypt a string with a password .
34,466
public String getParameter ( String name ) { String [ ] values = parameters . get ( name ) ; if ( values == null ) { return null ; } if ( values . length == 0 ) { return "" ; } return values [ 0 ] ; }
Get a single parameter of the parsed URI
34,467
private Map < String , String [ ] > parseQuery ( String qs ) { Map < String , String [ ] > ret = new TreeMap < String , String [ ] > ( ) ; try { String pairs [ ] = qs . split ( "&" ) ; for ( String pair : pairs ) { String name ; String value ; int pos = pair . indexOf ( '=' ) ; if ( pos == - 1 ) { name = pair ; value =...
parse the query
34,468
protected String getProcessDescription ( OptionsAndArgs pOpts , VirtualMachineHandler pHandler ) { if ( pOpts . getPid ( ) != null ) { return "PID " + pOpts . getPid ( ) ; } else if ( pOpts . getProcessPattern ( ) != null ) { StringBuffer desc = new StringBuffer ( "process matching \"" ) . append ( pOpts . getProcessPa...
Get a description of the process attached either the numeric id only or if a pattern is given the pattern and the associated PID
34,469
public void start ( ) { String configUrl = NetworkUtil . replaceExpression ( config . getJolokiaConfig ( ) . get ( ConfigKey . DISCOVERY_AGENT_URL ) ) ; jolokiaHttpHandler . start ( lazy , configUrl != null ? configUrl : url , config . getAuthenticator ( ) != null ) ; if ( httpServer != null ) { ThreadGroup threadGroup...
Start this server . If we manage an own HttpServer then the HttpServer will be started as well .
34,470
protected final void init ( JolokiaServerConfig pConfig , boolean pLazy ) throws IOException { httpServer = createHttpServer ( pConfig ) ; init ( httpServer , pConfig , pLazy ) ; }
Initialize this JolokiaServer and use an own created HttpServer
34,471
private HttpServer createHttpServer ( JolokiaServerConfig pConfig ) throws IOException { int port = pConfig . getPort ( ) ; InetAddress address = pConfig . getAddress ( ) ; InetSocketAddress socketAddress = new InetSocketAddress ( address , port ) ; HttpServer server = pConfig . useHttps ( ) ? createHttpsServer ( socke...
Create the HttpServer to use . Can be overridden if a custom or already existing HttpServer should be used
34,472
private void addException ( ObjectName pName , Exception pExp ) { JSONObject mBeansMap = getOrCreateJSONObject ( infoMap , pName . getDomain ( ) ) ; JSONObject mBeanMap = getOrCreateJSONObject ( mBeansMap , getKeyPropertyString ( pName ) ) ; mBeanMap . put ( DataKeys . ERROR . getKey ( ) , pExp . toString ( ) ) ; }
Add an exception to the info map
34,473
private Stack < String > truncatePathStack ( int pLevel ) { if ( pathStack . size ( ) < pLevel ) { return new Stack < String > ( ) ; } else { Stack < String > ret = ( Stack < String > ) pathStack . clone ( ) ; for ( int i = 0 ; i < pLevel ; i ++ ) { ret . pop ( ) ; } return ret ; } }
Trim down the stack by some value or return an empty stack
34,474
private Object navigatePath ( ) { int size = pathStack . size ( ) ; JSONObject innerMap = infoMap ; while ( size > 0 ) { Collection vals = innerMap . values ( ) ; if ( vals . size ( ) == 0 ) { return innerMap ; } else if ( vals . size ( ) != 1 ) { throw new IllegalStateException ( "Internal: More than one key found whe...
Navigate to sub map or leaf value
34,475
protected Server getServer ( MuleAgentConfig pConfig ) { Server newServer = new Server ( ) ; Connector connector = createConnector ( newServer ) ; if ( pConfig . getHost ( ) != null ) { ClassUtil . applyMethod ( connector , "setHost" , pConfig . getHost ( ) ) ; } ClassUtil . applyMethod ( connector , "setPort" , pConfi...
Get the agent server for suing it with mule
34,476
public void setServerInfo ( String pVendor , String pProduct , String pVersion ) { checkSeal ( ) ; serverVendor = pVendor ; serverProduct = pProduct ; serverVersion = pVersion ; }
Single method for updating the server information when the server has been detected
34,477
public JSONObject toJSONObject ( ) { JSONObject resp = new JSONObject ( ) ; add ( resp , URL , url ) ; if ( secured != null ) { add ( resp , SECURED , secured ) ; } add ( resp , SERVER_VENDOR , serverVendor ) ; add ( resp , SERVER_PRODUCT , serverProduct ) ; add ( resp , SERVER_VERSION , serverVersion ) ; add ( resp , ...
Get the details as JSON Object
34,478
public Result authenticate ( HttpExchange httpExchange ) { Result result = null ; for ( Authenticator a : authenticators ) { result = a . authenticate ( httpExchange ) ; if ( ( result instanceof Success && mode == Mode . ANY ) || ( ! ( result instanceof Success ) && mode == Mode . ALL ) ) { return result ; } } return r...
Authenticate against the given request
34,479
public HttpUriRequest getHttpRequest ( J4pRequest pRequest , String pPreferredMethod , Map < J4pQueryParameter , String > pProcessingOptions ) throws UnsupportedEncodingException , URISyntaxException { String method = pPreferredMethod ; if ( method == null ) { method = pRequest . getPreferredHttpMethod ( ) ; } if ( met...
Get the HttpRequest for executing the given single request
34,480
public < T extends J4pRequest > HttpUriRequest getHttpRequest ( List < T > pRequests , Map < J4pQueryParameter , String > pProcessingOptions ) throws UnsupportedEncodingException , URISyntaxException { JSONArray bulkRequest = new JSONArray ( ) ; String queryParams = prepareQueryParameters ( pProcessingOptions ) ; HttpP...
Get an HTTP Request for requesting multiples requests at once
34,481
@ SuppressWarnings ( "PMD.PreserveStackTrace" ) public JSONAware extractJsonResponse ( HttpResponse pHttpResponse ) throws IOException , ParseException { HttpEntity entity = pHttpResponse . getEntity ( ) ; try { JSONParser parser = new JSONParser ( ) ; Header contentEncoding = entity . getContentEncoding ( ) ; if ( con...
Extract the complete JSON response out of a HTTP response
34,482
private URI createRequestURI ( String path , String queryParams ) throws URISyntaxException { return new URI ( j4pServerUrl . getScheme ( ) , j4pServerUrl . getUserInfo ( ) , j4pServerUrl . getHost ( ) , j4pServerUrl . getPort ( ) , path , queryParams , null ) ; }
Create the request URI to use
34,483
private String prepareQueryParameters ( Map < J4pQueryParameter , String > pProcessingOptions ) { if ( pProcessingOptions != null && pProcessingOptions . size ( ) > 0 ) { StringBuilder queryParams = new StringBuilder ( ) ; for ( Map . Entry < J4pQueryParameter , String > entry : pProcessingOptions . entrySet ( ) ) { qu...
prepare query parameters
34,484
private void checkHttpMethod ( R pRequest ) { if ( ! restrictor . isHttpMethodAllowed ( pRequest . getHttpMethod ( ) ) ) { throw new SecurityException ( "HTTP method " + pRequest . getHttpMethod ( ) . getMethod ( ) + " is not allowed according to the installed security policy" ) ; } }
Check whether the HTTP method with which the request was sent is allowed according to the policy installed
34,485
protected void checkForModifiedSince ( MBeanServerExecutor pServerManager , JmxRequest pRequest ) throws NotChangedException { int ifModifiedSince = pRequest . getParameterAsInt ( ConfigKey . IF_MODIFIED_SINCE ) ; if ( ! pServerManager . hasMBeansListChangedSince ( ifModifiedSince ) ) { throw new NotChangedException ( ...
Check whether the set of MBeans for any managed MBeanServer has been change since the timestamp provided in the given request
34,486
private Server getServer ( MuleAgentConfig pConfig ) { Server newServer = new Server ( ) ; Connector connector = new SelectChannelConnector ( ) ; if ( pConfig . getHost ( ) != null ) { connector . setHost ( pConfig . getHost ( ) ) ; } connector . setPort ( pConfig . getPort ( ) ) ; newServer . setConnectors ( new Conne...
Create a Jetty Server with the agent servlet installed
34,487
public void addMBeanServers ( Set < MBeanServerConnection > servers ) { if ( ! isJBoss ( ) ) { InitialContext ctx ; try { ctx = new InitialContext ( ) ; MBeanServer server = ( MBeanServer ) ctx . lookup ( "java:comp/env/jmx/runtime" ) ; if ( server != null ) { servers . add ( server ) ; } } catch ( NamingException e ) ...
Adde Weblogic specific runtime MBeanServer
34,488
public String getDescription ( ) { String hostDescr = host ; try { if ( hostDescr == null ) { hostDescr = NetworkUtil . getLocalAddress ( ) . getHostName ( ) ; } } catch ( IOException e ) { hostDescr = "localhost" ; } return "Jolokia Agent: http://" + hostDescr + ":" + getPort ( ) + "/jolokia" ; }
Description including agent URL
34,489
public static MBeanServer getJolokiaMBeanServer ( ) { MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; MBeanServer jolokiaMBeanServer ; try { jolokiaMBeanServer = ( MBeanServer ) server . getAttribute ( createObjectName ( JolokiaMBeanServerHolderMBean . OBJECT_NAME ) , JOLOKIA_MBEAN_SERVER_ATTRIBUT...
Lookup the JolokiaMBean server via a JMX lookup to the Jolokia - internal MBean exposing this MBeanServer
34,490
static MBeanServer registerJolokiaMBeanServerHolderMBean ( MBeanServer pServer ) { JolokiaMBeanServerHolder holder = new JolokiaMBeanServerHolder ( ) ; ObjectName holderName = createObjectName ( JolokiaMBeanServerHolderMBean . OBJECT_NAME ) ; MBeanServer jolokiaMBeanServer ; try { pServer . registerMBean ( holder , hol...
package visible for unit testing
34,491
private void verifyArguments ( JmxExecRequest request , OperationAndParamType pTypes , int pNrParams , List < Object > pArgs ) { if ( ( pNrParams > 0 && pArgs == null ) || ( pArgs != null && pArgs . size ( ) != pNrParams ) ) { throw new IllegalArgumentException ( "Invalid number of operation arguments. Operation " + re...
check whether the given arguments are compatible with the signature and if not so raise an excepton
34,492
private OperationAndParamType extractOperationTypes ( MBeanServerConnection pServer , JmxExecRequest pRequest ) throws ReflectionException , InstanceNotFoundException , IOException { if ( pRequest . getOperation ( ) == null ) { throw new IllegalArgumentException ( "No operation given for exec Request on MBean " + pRequ...
Extract the operation and type list from a given request
34,493
private List < MBeanParameterInfo [ ] > extractMBeanParameterInfos ( MBeanServerConnection pServer , JmxExecRequest pRequest , String pOperation ) throws InstanceNotFoundException , ReflectionException , IOException { try { MBeanInfo mBeanInfo = pServer . getMBeanInfo ( pRequest . getObjectName ( ) ) ; List < MBeanPara...
Extract a list of operation signatures which match a certain operation name . The returned list can contain multiple signature in case of overloaded JMX operations .
34,494
private List < String > splitOperation ( String pOperation ) { List < String > ret = new ArrayList < String > ( ) ; Pattern p = Pattern . compile ( "^(.*)\\((.*)\\)$" ) ; Matcher m = p . matcher ( pOperation ) ; if ( m . matches ( ) ) { ret . add ( m . group ( 1 ) ) ; if ( m . group ( 2 ) . length ( ) > 0 ) { String [ ...
Extract operation and optional type parameters
34,495
public ImmutableSubstitution < ImmutableTerm > composeWith ( ImmutableSubstitution < ? extends ImmutableTerm > f ) { if ( isEmpty ( ) ) { return ( ImmutableSubstitution < ImmutableTerm > ) f ; } if ( f . isEmpty ( ) ) { return ( ImmutableSubstitution < ImmutableTerm > ) this ; } Map < Variable , ImmutableTerm > substit...
this o f
34,496
protected Optional < ImmutableMap < Variable , T > > computeUnionMap ( ImmutableSubstitution < T > otherSubstitution ) { ImmutableMap . Builder < Variable , T > mapBuilder = ImmutableMap . builder ( ) ; mapBuilder . putAll ( getImmutableMap ( ) ) ; ImmutableMap < Variable , T > otherMap = otherSubstitution . getImmutab...
In case some sub - classes wants to add a new unionXX method returning an optional in their own type .
34,497
private Map . Entry < Variable , ImmutableTerm > applyNullNormalization ( Map . Entry < Variable , ImmutableTerm > substitutionEntry ) { ImmutableTerm value = substitutionEntry . getValue ( ) ; if ( value instanceof ImmutableFunctionalTerm ) { ImmutableTerm newValue = normalizeFunctionalTerm ( ( ImmutableFunctionalTerm...
Most functional terms do not accept NULL as arguments . If this happens they become NULL .
34,498
private Optional < IRI > getPredicateIRI ( DataRangeExpression expression ) { if ( expression instanceof Datatype ) { return Optional . of ( ( ( Datatype ) expression ) . getIRI ( ) ) ; } if ( expression instanceof DataPropertyRangeExpression ) { return Optional . of ( ( ( DataPropertyRangeExpression ) expression ) . g...
if the answer is no drop the Optional and throw an exception instead
34,499
public static Connection createConnection ( OntopSQLCredentialSettings settings ) throws SQLException { try { return DriverManager . getConnection ( settings . getJdbcUrl ( ) , settings . getJdbcUser ( ) , settings . getJdbcPassword ( ) ) ; } catch ( SQLException ex ) { if ( settings . getJdbcDriver ( ) . isPresent ( )...
Brings robustness to some Tomcat classloading issues .