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 ( "Cannot call method " + pMethod + " on " + pObject + ": " + e , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalArgumentException ( "Cannot call method " + pMethod + " on " + pObject + ": " + e , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( "Cannot call method " + pMethod + " on " + pObject + ": " + e , e ) ; } } | 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 . addAll ( extractUrlAsStringsFromEnumeration ( urlEnum ) ) ; } return ret ; } else { return extractUrlAsStringsFromEnumeration ( ClassLoader . getSystemResources ( pResource ) ) ; } } | 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 . replaceFirst ( "Z$" , "+0000" ) ; SimpleDateFormat dateFormat = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ssZ" ) ; return dateFormat . parse ( date ) ; } catch ( ParseException e ) { throw new IllegalArgumentException ( "Cannot parse date '" + pDateString + "': " + e , e ) ; } } } | 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)$" , ":$1" ) ; } | 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 ( ");" ) ; } pWriter . write ( STREAM_END_MARKER ) ; } finally { pWriter . flush ( ) ; pWriter . close ( ) ; } } | 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 ) { } } return ret ; } | 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 ; } else { valueFaultHandler = ValueFaultHandler . THROWING_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 ) ? null : element ) ; } return ret ; } | 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 normalizePathInfo ( pathInfo ) ; } | 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 . class . getResourceAsStream ( path ) ; } } else { URL url = new URL ( pLocation ) ; is = url . openStream ( ) ; } return is != null ? new PolicyRestrictor ( is ) : null ; } | 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 = extractData ( pMBeanInfo , filter ) ; if ( attrMap . size ( ) > 0 ) { pJSONObject . put ( getKey ( ) , attrMap ) ; } else if ( ! isPathEmpty ) { throw new IllegalArgumentException ( "Path given but extracted value is empty" ) ; } } | 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 ( CertificateParsingException e ) { throw new SecurityException ( "Can't parse client cert" ) ; } } | 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 : serviceRefs ) { Restrictor restrictor = ( Restrictor ) bundleContext . getService ( serviceRef ) ; if ( restrictor != null ) { ret = ret && pCheck . check ( restrictor , args ) ; found = true ; } } return found && ret ; } else { return false ; } } catch ( InvalidSyntaxException e ) { throw new IllegalArgumentException ( "Impossible exception (we don't use a filter for fetching the services)" , e ) ; } } | 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 ) . append ( "\n" ) ; if ( entry . throwable != null ) { StringWriter writer = new StringWriter ( ) ; entry . throwable . printStackTrace ( new PrintWriter ( writer ) ) ; ret . append ( writer . toString ( ) ) ; } } return ret . toString ( ) ; } | 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 . getParameter ( keyS ) ) ; } } } | 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 . isRequestConfig ( ) && ! procParams . containsKey ( key ) ) { procParams . put ( key , entry . getValue ( ) ) ; } } return new ProcessingParameters ( procParams , pParams . get ( PATH_QUERY_PARAM ) ) ; } | 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 ) { inc += 50 ; } } Thread ret [ ] = new Thread [ nrThreads ] ; System . arraycopy ( threads , 0 , ret , 0 , nrThreads ) ; return ret ; } | 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 ( ) ; } catch ( Exception ex ) { } finally { return true ; } } return false ; } | 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 ServiceAuthenticationHttpContext ( bundleContext , authMode ) ; } else { jolokiaHttpContext = new DefaultHttpContext ( ) ; } } else { jolokiaHttpContext = new BasicAuthenticationHttpContext ( getConfiguration ( REALM ) , createAuthenticator ( authMode ) ) ; } } return jolokiaHttpContext ; } | 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 jolokiaId = NetworkUtil . replaceExpression ( config . get ( ConfigKey . AGENT_ID . getKeyValue ( ) ) ) ; if ( jolokiaId == null ) { config . put ( ConfigKey . AGENT_ID . getKeyValue ( ) , NetworkUtil . getAgentId ( hashCode ( ) , "osgi" ) ) ; } config . put ( ConfigKey . AGENT_TYPE . getKeyValue ( ) , "osgi" ) ; return config ; } | 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 . getChildNodes ( ) ) ; } } | 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_VERSION . matcher ( pFullVersion ) ; if ( matcher . matches ( ) ) { serverName = PAYARA_NAME ; vendorName = PAYARA_VENDOR_NAME ; return matcher . group ( 1 ) ; } } return null ; } | 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 < Void > ( ) { public Void execute ( MBeanServerConnection pConn , ObjectName pName , Object ... extraArgs ) throws ReflectionException , InstanceNotFoundException , IOException , MBeanException { pConn . invoke ( pName , "bootAMX" , null , null ) ; return null ; } } ) ; return true ; } catch ( InstanceNotFoundException e ) { pLoghandler . error ( "No bootAmx MBean found: " + e , e ) ; return false ; } catch ( IllegalArgumentException e ) { pLoghandler . error ( "Exception while booting AMX: " + e , e ) ; return true ; } catch ( Exception e ) { pLoghandler . error ( "Exception while executing bootAmx: " + e , e ) ; return true ; } } | 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 ( HistoryKey key : historyStore . keySet ( ) ) { if ( pKey . matches ( key ) ) { HistoryEntry entry = historyStore . get ( key ) ; entry . setLimit ( limit ) ; } } } else { HistoryEntry entry = historyStore . get ( pKey ) ; if ( entry != null ) { entry . setLimit ( limit ) ; } else { entry = new HistoryEntry ( limit ) ; historyStore . put ( pKey , entry ) ; } } } | 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 . updateHistory ( pJson , pJmxReq , timestamp ) ; } } | 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 serialize internal store: " + e , e ) ; } } | 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 ) { synchronized ( entry ) { pJson . put ( KEY_HISTORY , entry . jsonifyValues ( ) ) ; entry . add ( pJson . get ( KEY_VALUE ) , pTimestamp ) ; } } } } ) ; historyUpdaters . put ( RequestType . WRITE , new HistoryUpdater < JmxWriteRequest > ( ) { public void updateHistory ( JSONObject pJson , JmxWriteRequest request , long pTimestamp ) { HistoryEntry entry = historyStore . get ( new HistoryKey ( request ) ) ; if ( entry != null ) { synchronized ( entry ) { pJson . put ( KEY_HISTORY , entry . jsonifyValues ( ) ) ; entry . add ( request . getValue ( ) , pTimestamp ) ; } } } } ) ; historyUpdaters . put ( RequestType . READ , new HistoryUpdater < JmxReadRequest > ( ) { public void updateHistory ( JSONObject pJson , JmxReadRequest request , long pTimestamp ) { updateReadHistory ( request , pJson , pTimestamp ) ; } } ) ; } | 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 = updateHistoryForPatternRead ( pJmxReq , pTimestamp , values ) ; if ( history . size ( ) > 0 ) { pJson . put ( KEY_HISTORY , history ) ; } } } else if ( pJmxReq . isMultiAttributeMode ( ) || ! pJmxReq . hasAttribute ( ) ) { JSONObject history = addMultipleAttributeValues ( pJmxReq , ( ( Map < String , Object > ) pJson . get ( KEY_VALUE ) ) , pJmxReq . getObjectNameAsString ( ) , pTimestamp ) ; if ( history . size ( ) > 0 ) { pJson . put ( KEY_HISTORY , history ) ; } } else { addAttributeFromSingleValue ( pJson , new HistoryKey ( pJmxReq ) , KEY_HISTORY , pJson . get ( KEY_VALUE ) , pTimestamp ) ; } } | 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 . size ( ) ) ; J4pRemoteException remoteExceptions [ ] = new J4pRemoteException [ responseArray . size ( ) ] ; boolean exceptionFound = false ; for ( int i = 0 ; i < pRequests . size ( ) ; i ++ ) { T request = pRequests . get ( i ) ; Object jsonResp = responseArray . get ( i ) ; if ( ! ( jsonResp instanceof JSONObject ) ) { throw new J4pException ( "Response for request Nr. " + i + " is invalid (expected a map but got " + jsonResp . getClass ( ) + ")" ) ; } try { ret . add ( i , pResponseExtractor . < R , T > extract ( request , ( JSONObject ) jsonResp ) ) ; } catch ( J4pRemoteException exp ) { remoteExceptions [ i ] = exp ; exceptionFound = true ; ret . add ( i , null ) ; } } if ( exceptionFound ) { List partialResults = new ArrayList ( ) ; for ( int i = 0 ; i < pRequests . size ( ) ; i ++ ) { J4pRemoteException exp = remoteExceptions [ i ] ; if ( exp != null ) { partialResults . add ( exp ) ; } else { partialResults . add ( ret . get ( i ) ) ; } } throw new J4pBulkRemoteException ( partialResults ) ; } return ret ; } | 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 instanceof ConnectTimeoutException ) { return new J4pTimeoutException ( "Read timeout while request " + requestHandler . getJ4pServerUrl ( ) + ": " + pException . getMessage ( ) , ( ConnectTimeoutException ) pException ) ; } else if ( pException instanceof IOException ) { return new J4pException ( "IO-Error while contacting the server: " + pException , pException ) ; } else if ( pException instanceof URISyntaxException ) { URISyntaxException sExp = ( URISyntaxException ) pException ; return new J4pException ( "Invalid URI " + sExp . getInput ( ) + ": " + sExp . getReason ( ) , pException ) ; } else { return new J4pException ( "Exception " + pException , 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 ( "status" ) != 200 ) { throw new J4pRemoteException ( null , errorObject ) ; } } throw new J4pException ( "Invalid JSON answer for a bulk request (expected an array but got a " + pJsonResponse . getClass ( ) + ")" ) ; } } | 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 { json = callRequestDispatcher ( pJmxReq ) ; historyStore . updateAndAdd ( pJmxReq , json ) ; json . put ( "status" , 200 ) ; } catch ( NotChangedException exp ) { json = new JSONObject ( ) ; json . put ( "request" , pJmxReq . toJSON ( ) ) ; json . put ( "status" , 304 ) ; json . put ( "timestamp" , System . currentTimeMillis ( ) / 1000 ) ; } if ( debug ) { debug ( "Execution time: " + ( System . currentTimeMillis ( ) - time ) + " ms" ) ; debug ( "Response: " + json ) ; } return json ; } | 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 ) { return null ; } } | 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 ( pConfig , converters , serverHandle , restrictor ) ; requestDispatchers . add ( localDispatcher ) ; initMBeans ( pConfig ) ; agentDetails . setServerInfo ( serverHandle . getVendor ( ) , serverHandle . getProduct ( ) , serverHandle . getVersion ( ) ) ; } | 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 ; if ( classes != null && classes . length ( ) > 0 ) { String [ ] names = classes . split ( "\\s*,\\s*" ) ; for ( String name : names ) { ret . add ( createDispatcher ( name , pConverters , pServerHandle , pRestrictor , pConfig ) ) ; } } return ret ; } | 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 IllegalArgumentException ( "Couldn't lookup dispatcher " + pDispatcherClass ) ; } try { Constructor constructor = clazz . getConstructor ( Converters . class , ServerHandle . class , Restrictor . class , Configuration . class ) ; return ( RequestDispatcher ) constructor . newInstance ( pConverters , pServerHandle , pRestrictor , pConfig ) ; } catch ( NoSuchMethodException exp ) { Constructor constructor = clazz . getConstructor ( Converters . class , ServerHandle . class , Restrictor . class ) ; return ( RequestDispatcher ) constructor . newInstance ( pConverters , pServerHandle , pRestrictor ) ; } } catch ( NoSuchMethodException e ) { throw new IllegalArgumentException ( "Class " + pDispatcherClass + " has invalid constructor: " + e , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( "Constructor of " + pDispatcherClass + " couldn't be accessed: " + e , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalArgumentException ( e ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( pDispatcherClass + " couldn't be instantiated: " + e , e ) ; } } | 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 dispatcher : requestDispatchers ) { if ( dispatcher . canHandle ( pJmxReq ) ) { retValue = dispatcher . dispatchRequest ( pJmxReq ) ; useValueWithPath = dispatcher . useReturnValueWithPath ( pJmxReq ) ; found = true ; break ; } } if ( ! found ) { throw new IllegalStateException ( "Internal error: No dispatcher found for handling " + pJmxReq ) ; } JsonConvertOptions opts = getJsonConvertOptions ( pJmxReq ) ; Object jsonResult = converters . getToJsonConverter ( ) . convertToJson ( retValue , useValueWithPath ? pJmxReq . getPathParts ( ) : null , opts ) ; JSONObject jsonObject = new JSONObject ( ) ; jsonObject . put ( "value" , jsonResult ) ; jsonObject . put ( "request" , pJmxReq . toJSON ( ) ) ; return jsonObject ; } | 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 { localDispatcher . initMBeans ( historyStore , debugStore ) ; } catch ( NotCompliantMBeanException e ) { intError ( "Error registering config MBean: " + e , e ) ; } catch ( MBeanRegistrationException e ) { intError ( "Cannot register MBean: " + e , e ) ; } catch ( MalformedObjectNameException e ) { intError ( "Invalid name for config MBean: " + e , e ) ; } } | 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 IllegalArgumentException ( "Unknown command '" + commandName + "'" ) ; } return command . execute ( options , pVm , pHandler ) ; } | 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 objNotFoundException = null ; for ( MBeanServerConnection conn : getMBeanServers ( ) ) { try { return pRequestHandler . handleRequest ( conn , pJmxReq ) ; } catch ( InstanceNotFoundException exp ) { objNotFoundException = exp ; } catch ( AttributeNotFoundException exp ) { attrException = exp ; } catch ( IOException exp ) { throw new IllegalStateException ( "I/O Error while dispatching" , exp ) ; } } if ( attrException != null ) { throw attrException ; } throw objNotFoundException ; } | 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 ) ; int len = encryptedBytes . length ; byte padLen = ( byte ) ( CHUNK_SIZE - ( SALT_SIZE + len + 1 ) % CHUNK_SIZE ) ; int totalLen = SALT_SIZE + len + padLen + 1 ; byte [ ] allEncryptedBytes = getSalt ( totalLen ) ; System . arraycopy ( salt , 0 , allEncryptedBytes , 0 , SALT_SIZE ) ; allEncryptedBytes [ SALT_SIZE ] = padLen ; System . arraycopy ( encryptedBytes , 0 , allEncryptedBytes , SALT_SIZE + 1 , len ) ; return Base64Util . encode ( allEncryptedBytes ) ; } | 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 = null ; } else { name = URLDecoder . decode ( pair . substring ( 0 , pos ) , "UTF-8" ) ; value = URLDecoder . decode ( pair . substring ( pos + 1 , pair . length ( ) ) , "UTF-8" ) ; } String [ ] values = ret . get ( name ) ; if ( values == null ) { values = new String [ ] { value } ; ret . put ( name , values ) ; } else { String [ ] newValues = new String [ values . length + 1 ] ; System . arraycopy ( values , 0 , newValues , 0 , values . length ) ; newValues [ values . length ] = value ; ret . put ( name , newValues ) ; } } return ret ; } catch ( UnsupportedEncodingException e ) { throw new IllegalArgumentException ( "Cannot decode to UTF-8. Should not happen, though." , e ) ; } } | 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 . getProcessPattern ( ) . pattern ( ) ) . append ( "\"" ) ; try { desc . append ( " (PID: " ) . append ( pHandler . findProcess ( pOpts . getProcessPattern ( ) ) . getId ( ) ) . append ( ")" ) ; } catch ( InvocationTargetException e ) { } catch ( NoSuchMethodException e ) { } catch ( IllegalAccessException e ) { } return desc . toString ( ) ; } else { return "(null)" ; } } | 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 = new ThreadGroup ( "jolokia" ) ; threadGroup . setDaemon ( false ) ; Thread starterThread = new Thread ( threadGroup , new Runnable ( ) { public void run ( ) { httpServer . start ( ) ; } } ) ; starterThread . start ( ) ; cleaner = new CleanupThread ( httpServer , threadGroup ) ; cleaner . start ( ) ; } } | 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 ( socketAddress , pConfig ) : HttpServer . create ( socketAddress , pConfig . getBacklog ( ) ) ; ThreadFactory daemonThreadFactory = new DaemonThreadFactory ( pConfig . getThreadNamePrefix ( ) ) ; Executor executor ; String mode = pConfig . getExecutor ( ) ; if ( "fixed" . equalsIgnoreCase ( mode ) ) { executor = Executors . newFixedThreadPool ( pConfig . getThreadNr ( ) , daemonThreadFactory ) ; } else if ( "cached" . equalsIgnoreCase ( mode ) ) { executor = Executors . newCachedThreadPool ( daemonThreadFactory ) ; } else { executor = Executors . newSingleThreadExecutor ( daemonThreadFactory ) ; } server . setExecutor ( executor ) ; return server ; } | 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 when extracting with path: " + vals ) ; } Object value = vals . iterator ( ) . next ( ) ; if ( size == 1 ) { return value ; } if ( ! ( value instanceof JSONObject ) ) { throw new IllegalStateException ( "Internal: Value within path extraction must be a Map, not " + value . getClass ( ) ) ; } innerMap = ( JSONObject ) value ; -- size ; } return innerMap ; } | 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" , pConfig . getPort ( ) ) ; newServer . setConnectors ( new Connector [ ] { connector } ) ; return newServer ; } | 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 , AGENT_VERSION , agentVersion ) ; add ( resp , AGENT_ID , agentId ) ; add ( resp , AGENT_DESCRIPTION , agentDescription ) ; return 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 result ; } | 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 ( method == null ) { method = doUseProxy ( pRequest ) ? HttpPost . METHOD_NAME : HttpGet . METHOD_NAME ; } String queryParams = prepareQueryParameters ( pProcessingOptions ) ; if ( method . equals ( HttpGet . METHOD_NAME ) ) { if ( doUseProxy ( pRequest ) ) { throw new IllegalArgumentException ( "Proxy mode can only be used with POST requests" ) ; } List < String > parts = pRequest . getRequestParts ( ) ; if ( parts != null ) { String base = prepareBaseUrl ( j4pServerUrl ) ; StringBuilder requestPath = new StringBuilder ( base ) ; requestPath . append ( pRequest . getType ( ) . getValue ( ) ) ; for ( String p : parts ) { requestPath . append ( "/" ) ; requestPath . append ( escape ( p ) ) ; } return new HttpGet ( createRequestURI ( requestPath . toString ( ) , queryParams ) ) ; } } JSONObject requestContent = getJsonRequestContent ( pRequest ) ; HttpPost postReq = new HttpPost ( createRequestURI ( j4pServerUrl . getPath ( ) , queryParams ) ) ; postReq . setEntity ( new StringEntity ( requestContent . toJSONString ( ) , "utf-8" ) ) ; return postReq ; } | 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 ) ; HttpPost postReq = new HttpPost ( createRequestURI ( j4pServerUrl . getPath ( ) , queryParams ) ) ; for ( T request : pRequests ) { JSONObject requestContent = getJsonRequestContent ( request ) ; bulkRequest . add ( requestContent ) ; } postReq . setEntity ( new StringEntity ( bulkRequest . toJSONString ( ) , "utf-8" ) ) ; return postReq ; } | 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 ( contentEncoding != null ) { return ( JSONAware ) parser . parse ( new InputStreamReader ( entity . getContent ( ) , Charset . forName ( contentEncoding . getValue ( ) ) ) ) ; } else { return ( JSONAware ) parser . parse ( new InputStreamReader ( entity . getContent ( ) ) ) ; } } finally { if ( entity != null ) { EntityUtils . consume ( entity ) ; } } } | 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 ( ) ) { queryParams . append ( entry . getKey ( ) . getParam ( ) ) . append ( "=" ) . append ( entry . getValue ( ) ) . append ( "&" ) ; } return queryParams . substring ( 0 , queryParams . length ( ) - 1 ) ; } else { return null ; } } | 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 ( pRequest ) ; } } | 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 Connector [ ] { connector } ) ; return newServer ; } | 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_ATTRIBUTE ) ; } catch ( InstanceNotFoundException exp ) { jolokiaMBeanServer = registerJolokiaMBeanServerHolderMBean ( server ) ; } catch ( JMException e ) { throw new IllegalStateException ( "Internal: Cannot get JolokiaMBean server via JMX lookup: " + e , e ) ; } return jolokiaMBeanServer ; } | 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 , holderName ) ; jolokiaMBeanServer = holder . getJolokiaMBeanServer ( ) ; } catch ( InstanceAlreadyExistsException e ) { try { jolokiaMBeanServer = ( MBeanServer ) pServer . getAttribute ( holderName , JOLOKIA_MBEAN_SERVER_ATTRIBUTE ) ; } catch ( JMException e1 ) { throw new IllegalStateException ( "Internal: Cannot get JolokiaMBean server in fallback JMX lookup " + "while trying to register the holder MBean: " + e1 , e1 ) ; } } catch ( JMException e ) { throw new IllegalStateException ( "Internal: JolokiaMBeanHolder cannot be registered to JMX: " + e , e ) ; } return jolokiaMBeanServer ; } | 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 " + request . getOperation ( ) + " on " + request . getObjectName ( ) + " requires " + pTypes . paramClasses . length + " parameters, not " + ( pArgs == null ? 0 : pArgs . size ( ) ) + " as given" ) ; } } | 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 " + pRequest . getObjectName ( ) ) ; } List < String > opArgs = splitOperation ( pRequest . getOperation ( ) ) ; String operation = opArgs . get ( 0 ) ; List < String > types ; if ( opArgs . size ( ) > 1 ) { if ( opArgs . size ( ) == 2 && opArgs . get ( 1 ) == null ) { types = Collections . emptyList ( ) ; } else { types = opArgs . subList ( 1 , opArgs . size ( ) ) ; } } else { List < MBeanParameterInfo [ ] > paramInfos = extractMBeanParameterInfos ( pServer , pRequest , operation ) ; if ( paramInfos . size ( ) == 1 ) { return new OperationAndParamType ( operation , paramInfos . get ( 0 ) ) ; } else { throw new IllegalArgumentException ( getErrorMessageForMissingSignature ( pRequest , operation , paramInfos ) ) ; } } List < MBeanParameterInfo [ ] > paramInfos = extractMBeanParameterInfos ( pServer , pRequest , operation ) ; MBeanParameterInfo [ ] matchingSignature = getMatchingSignature ( types , paramInfos ) ; if ( matchingSignature == null ) { throw new IllegalArgumentException ( "No operation " + pRequest . getOperation ( ) + " on MBean " + pRequest . getObjectNameAsString ( ) + " exists. " + "Known signatures: " + signatureToString ( paramInfos ) ) ; } return new OperationAndParamType ( operation , matchingSignature ) ; } | 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 < MBeanParameterInfo [ ] > paramInfos = new ArrayList < MBeanParameterInfo [ ] > ( ) ; for ( MBeanOperationInfo opInfo : mBeanInfo . getOperations ( ) ) { if ( opInfo . getName ( ) . equals ( pOperation ) ) { paramInfos . add ( opInfo . getSignature ( ) ) ; } } if ( paramInfos . size ( ) == 0 ) { throw new IllegalArgumentException ( "No operation " + pOperation + " found on MBean " + pRequest . getObjectNameAsString ( ) ) ; } return paramInfos ; } catch ( IntrospectionException e ) { throw new IllegalStateException ( "Cannot extract MBeanInfo for " + pRequest . getObjectNameAsString ( ) , e ) ; } } | 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 [ ] args = m . group ( 2 ) . split ( "\\s*,\\s*" ) ; ret . addAll ( Arrays . asList ( args ) ) ; } else { ret . add ( null ) ; } } else { ret . add ( pOperation ) ; } return ret ; } | 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 > substitutionMap = new HashMap < > ( ) ; for ( Map . Entry < Variable , ? extends ImmutableTerm > gEntry : f . getImmutableMap ( ) . entrySet ( ) ) { substitutionMap . put ( gEntry . getKey ( ) , apply ( gEntry . getValue ( ) ) ) ; } for ( Map . Entry < Variable , ? extends ImmutableTerm > localEntry : getImmutableMap ( ) . entrySet ( ) ) { Variable localVariable = localEntry . getKey ( ) ; if ( substitutionMap . containsKey ( localVariable ) ) continue ; substitutionMap . put ( localVariable , localEntry . getValue ( ) ) ; } return substitutionFactory . getSubstitution ( substitutionMap . entrySet ( ) . stream ( ) . filter ( entry -> ! entry . getKey ( ) . equals ( entry . getValue ( ) ) ) . collect ( ImmutableCollectors . toMap ( ) ) ) ; } | 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 . getImmutableMap ( ) ; for ( Variable otherVariable : otherMap . keySet ( ) ) { T otherTerm = otherMap . get ( otherVariable ) ; if ( isDefining ( otherVariable ) && ( ! get ( otherVariable ) . equals ( otherTerm ) ) ) { return Optional . empty ( ) ; } mapBuilder . put ( otherVariable , otherTerm ) ; } return Optional . of ( mapBuilder . build ( ) ) ; } | 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 ) value ) ; return newValue . equals ( value ) ? substitutionEntry : new AbstractMap . SimpleEntry < > ( substitutionEntry . getKey ( ) , newValue ) ; } return substitutionEntry ; } | 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 ) . getProperty ( ) . getIRI ( ) ) ; } return Optional . empty ( ) ; } | 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 ( ) ) { try { Class . forName ( settings . getJdbcDriver ( ) . get ( ) ) ; } catch ( ClassNotFoundException e ) { throw new SQLException ( "Cannot load the driver: " + e . getMessage ( ) ) ; } } return DriverManager . getConnection ( settings . getJdbcUrl ( ) , settings . getJdbcUser ( ) , settings . getJdbcPassword ( ) ) ; } } | Brings robustness to some Tomcat classloading issues . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.