_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q162700 | BeanExtractor.extractBeanAttributes | train | private List<String> extractBeanAttributes(Object pValue) {
List<String> attrs = new ArrayList<String>();
for (Method method : pValue.getClass().getMethods()) {
if (!Modifier.isStatic(method.getModifiers()) &&
!IGNORE_METHODS.contains(method.getName()) &&
!isIgnoredType(method.getReturnType()) &&
!hasAnnotation(method, "java.beans.Transient")) {
addAttributes(attrs, method);
}
}
return attrs;
} | java | {
"resource": ""
} |
q162701 | BeanExtractor.addAttributes | train | @SuppressWarnings("PMD.UnnecessaryCaseChange")
private void addAttributes(List<String> pAttrs, Method pMethod) {
String name = pMethod.getName();
for (String pref : GETTER_PREFIX) {
if (name.startsWith(pref) && name.length() > pref.length()
&& pMethod.getParameterTypes().length == 0) {
int len = pref.length();
String firstLetter = name.substring(len,len+1);
// Only for getter compliant to the beans conventions (first letter after prefix is upper case)
if (firstLetter.toUpperCase().equals(firstLetter)) {
String attribute =
new StringBuffer(firstLetter.toLowerCase()).
append(name.substring(len+1)).toString();
pAttrs.add(attribute);
}
}
}
} | java | {
"resource": ""
} |
q162702 | BeanExtractor.isIgnoredType | train | private boolean isIgnoredType(Class<?> pReturnType) {
for (Class<?> type : IGNORED_RETURN_TYPES) {
if (type.isAssignableFrom(pReturnType)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q162703 | SpringJolokiaAgent.afterPropertiesSet | train | public void afterPropertiesSet() throws IOException {
Map<String, String> finalConfig = new HashMap<String, String>();
if (systemPropertyMode == SystemPropertyMode.MODE_FALLBACK) {
finalConfig.putAll(lookupSystemProperties());
}
if (config != null) {
finalConfig.putAll(config.getConfig());
}
if (lookupConfig) {
// Merge all configs in the context in the reverse order
Map<String, SpringJolokiaConfigHolder> configsMap = context.getBeansOfType(SpringJolokiaConfigHolder.class);
List<SpringJolokiaConfigHolder> configs = new ArrayList<SpringJolokiaConfigHolder>(configsMap.values());
Collections.sort(configs, new OrderComparator());
for (SpringJolokiaConfigHolder c : configs) {
if (c != config) {
finalConfig.putAll(c.getConfig());
}
}
}
if (systemPropertyMode == SystemPropertyMode.MODE_OVERRIDE) {
finalConfig.putAll(lookupSystemProperties());
}
String autoStartS = finalConfig.remove("autoStart");
boolean autoStart = true;
if (autoStartS != null) {
autoStart = Boolean.parseBoolean(autoStartS);
}
init(new JolokiaServerConfig(finalConfig),false);
if (autoStart) {
start();
}
} | java | {
"resource": ""
} |
q162704 | SpringJolokiaAgent.lookupSystemProperties | train | private Map<String, String> lookupSystemProperties() {
Map<String,String> ret = new HashMap<String, String>();
Enumeration propEnum = System.getProperties().propertyNames();
while (propEnum.hasMoreElements()) {
String prop = (String) propEnum.nextElement();
if (prop.startsWith("jolokia.")) {
String key = prop.substring("jolokia.".length());
ret.put(key,System.getProperty(prop));
}
}
return ret;
} | java | {
"resource": ""
} |
q162705 | SpringJolokiaAgent.setSystemPropertiesMode | train | public void setSystemPropertiesMode(String pMode) {
systemPropertyMode = SystemPropertyMode.fromMode(pMode);
if (systemPropertyMode == null) {
systemPropertyMode = SystemPropertyMode.MODE_NEVER;
}
} | java | {
"resource": ""
} |
q162706 | JmxExecRequest.toJSON | train | public JSONObject toJSON() {
JSONObject ret = super.toJSON();
if (arguments != null && arguments.size() > 0) {
ret.put("arguments", arguments);
}
ret.put("operation", operation);
return ret;
} | java | {
"resource": ""
} |
q162707 | JmxExecRequest.convertSpecialStringTags | train | private static List<String> convertSpecialStringTags(List<String> extraArgs) {
if (extraArgs == null) {
return null;
}
List<String> args = new ArrayList<String>();
for (String arg : extraArgs) {
args.add(StringToObjectConverter.convertSpecialStringTags(arg));
}
return args;
} | java | {
"resource": ""
} |
q162708 | RequestHandlerManager.getRequestHandler | train | public JsonRequestHandler getRequestHandler(RequestType pType) {
JsonRequestHandler handler = requestHandlerMap.get(pType);
if (handler == null) {
throw new UnsupportedOperationException("Unsupported operation '" + pType + "'");
}
return handler;
} | java | {
"resource": ""
} |
q162709 | AgentServlet.addJsr160DispatcherIfExternallyConfigured | train | private void addJsr160DispatcherIfExternallyConfigured(Configuration pConfig) {
String dispatchers = pConfig.get(ConfigKey.DISPATCHER_CLASSES);
String jsr160DispatcherClass = "org.jolokia.jsr160.Jsr160RequestDispatcher";
if (dispatchers == null || !dispatchers.contains(jsr160DispatcherClass)) {
for (String param : new String[]{
System.getProperty("org.jolokia.jsr160ProxyEnabled"),
System.getenv("JOLOKIA_JSR160_PROXY_ENABLED")
}) {
if (param != null && (param.isEmpty() || Boolean.parseBoolean(param))) {
{
pConfig.updateGlobalConfiguration(
Collections.singletonMap(
ConfigKey.DISPATCHER_CLASSES.getKeyValue(),
(dispatchers != null ? dispatchers + "," : "") + jsr160DispatcherClass));
}
return;
}
}
if (dispatchers == null) {
// We add a breaking dispatcher to avoid silently ignoring a JSR160 proxy request
// when it is now enabled
pConfig.updateGlobalConfiguration(Collections.singletonMap(
ConfigKey.DISPATCHER_CLASSES.getKeyValue(),
Jsr160ProxyNotEnabledByDefaultAnymoreDispatcher.class.getCanonicalName()));
}
}
} | java | {
"resource": ""
} |
q162710 | AgentServlet.findAgentUrl | train | private String findAgentUrl(Configuration pConfig) {
// System property has precedence
String url = System.getProperty("jolokia." + ConfigKey.DISCOVERY_AGENT_URL.getKeyValue());
if (url == null) {
url = System.getenv("JOLOKIA_DISCOVERY_AGENT_URL");
if (url == null) {
url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL);
}
}
return NetworkUtil.replaceExpression(url);
} | java | {
"resource": ""
} |
q162711 | AgentServlet.listenForDiscoveryMcRequests | train | private boolean listenForDiscoveryMcRequests(Configuration pConfig) {
// Check for system props, system env and agent config
boolean sysProp = System.getProperty("jolokia." + ConfigKey.DISCOVERY_ENABLED.getKeyValue()) != null;
boolean env = System.getenv("JOLOKIA_DISCOVERY") != null;
boolean config = pConfig.getAsBoolean(ConfigKey.DISCOVERY_ENABLED);
return sysProp || env || config;
} | java | {
"resource": ""
} |
q162712 | AgentServlet.doOptions | train | @Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map<String,String> responseHeaders =
requestHandler.handleCorsPreflightRequest(
getOriginOrReferer(req),
req.getHeader("Access-Control-Request-Headers"));
for (Map.Entry<String,String> entry : responseHeaders.entrySet()) {
resp.setHeader(entry.getKey(),entry.getValue());
}
} | java | {
"resource": ""
} |
q162713 | AgentServlet.updateAgentDetailsIfNeeded | train | private void updateAgentDetailsIfNeeded(HttpServletRequest pReq) {
// Lookup the Agent URL if needed
AgentDetails details = backendManager.getAgentDetails();
if (details.isInitRequired()) {
synchronized (details) {
if (details.isInitRequired()) {
if (details.isUrlMissing()) {
String url = getBaseUrl(NetworkUtil.sanitizeLocalUrl(pReq.getRequestURL().toString()),
extractServletPath(pReq));
details.setUrl(url);
}
if (details.isSecuredMissing()) {
details.setSecured(pReq.getAuthType() != null);
}
details.seal();
}
}
}
} | java | {
"resource": ""
} |
q162714 | AgentServlet.getBaseUrl | train | private String getBaseUrl(String pUrl, String pServletPath) {
String sUrl;
try {
URL url = new URL(pUrl);
String host = getIpIfPossible(url.getHost());
sUrl = new URL(url.getProtocol(),host,url.getPort(),pServletPath).toExternalForm();
} catch (MalformedURLException exp) {
sUrl = plainReplacement(pUrl, pServletPath);
}
return sUrl;
} | java | {
"resource": ""
} |
q162715 | AgentServlet.getIpIfPossible | train | private String getIpIfPossible(String pHost) {
try {
InetAddress address = InetAddress.getByName(pHost);
return address.getHostAddress();
} catch (UnknownHostException e) {
return pHost;
}
} | java | {
"resource": ""
} |
q162716 | AgentServlet.plainReplacement | train | private String plainReplacement(String pUrl, String pServletPath) {
int idx = pUrl.lastIndexOf(pServletPath);
String url;
if (idx != -1) {
url = pUrl.substring(0,idx) + pServletPath;
} else {
url = pUrl;
}
return url;
} | java | {
"resource": ""
} |
q162717 | AgentServlet.setCorsHeader | train | private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) {
String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin"));
if (origin != null) {
pResp.setHeader("Access-Control-Allow-Origin", origin);
pResp.setHeader("Access-Control-Allow-Credentials","true");
}
} | java | {
"resource": ""
} |
q162718 | AgentServlet.newPostHttpRequestHandler | train | private ServletRequestHandler newPostHttpRequestHandler() {
return new ServletRequestHandler() {
/** {@inheritDoc} */
public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp)
throws IOException {
String encoding = pReq.getCharacterEncoding();
InputStream is = pReq.getInputStream();
return requestHandler.handlePostRequest(pReq.getRequestURI(),is, encoding, getParameterMap(pReq));
}
};
} | java | {
"resource": ""
} |
q162719 | AgentServlet.newGetHttpRequestHandler | train | private ServletRequestHandler newGetHttpRequestHandler() {
return new ServletRequestHandler() {
/** {@inheritDoc} */
public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) {
return requestHandler.handleGetRequest(pReq.getRequestURI(),pReq.getPathInfo(), getParameterMap(pReq));
}
};
} | java | {
"resource": ""
} |
q162720 | AgentServlet.initConfig | train | Configuration initConfig(ServletConfig pConfig) {
Configuration config = new Configuration(
ConfigKey.AGENT_ID, NetworkUtil.getAgentId(hashCode(),"servlet"));
// From ServletContext ....
config.updateGlobalConfiguration(new ServletConfigFacade(pConfig));
// ... and ServletConfig
config.updateGlobalConfiguration(new ServletContextFacade(getServletContext()));
// Set type last and overwrite anything written
config.updateGlobalConfiguration(Collections.singletonMap(ConfigKey.AGENT_TYPE.getKeyValue(),"servlet"));
return config;
} | java | {
"resource": ""
} |
q162721 | ArrayExtractor.setObjectValue | train | public Object setObjectValue(StringToObjectConverter pConverter, Object pInner, String pIndex, Object pValue)
throws IllegalAccessException, InvocationTargetException {
Class clazz = pInner.getClass();
if (!clazz.isArray()) {
throw new IllegalArgumentException("Not an array to set a value, but " + clazz +
". (index = " + pIndex + ", value = " + pValue + ")");
}
int idx;
try {
idx = Integer.parseInt(pIndex);
} catch (NumberFormatException exp) {
throw new IllegalArgumentException("Non-numeric index for accessing array " + pInner +
". (index = " + pIndex + ", value to set = " + pValue + ")",exp);
}
Class type = clazz.getComponentType();
Object value = pConverter.prepareValue(type.getName(), pValue);
Object oldValue = Array.get(pInner, idx);
Array.set(pInner, idx, value);
return oldValue;
} | java | {
"resource": ""
} |
q162722 | VirtualMachineHandler.detachAgent | train | public void detachAgent(Object pVm) {
try {
if (pVm != null) {
Class clazz = pVm.getClass();
Method method = clazz.getMethod("detach");
method.setAccessible(true); // on J9 you get IllegalAccessException otherwise.
method.invoke(pVm);
}
} catch (InvocationTargetException e) {
throw new ProcessingException("Error while detaching",e, options);
} catch (NoSuchMethodException e) {
throw new ProcessingException("Error while detaching",e, options);
} catch (IllegalAccessException e) {
throw new ProcessingException("Error while detaching",e, options);
}
} | java | {
"resource": ""
} |
q162723 | VirtualMachineHandler.listProcesses | train | public List<ProcessDescription> listProcesses() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
List<ProcessDescription> ret = new ArrayList<ProcessDescription>();
Class vmClass = lookupVirtualMachineClass();
Method method = vmClass.getMethod("list");
List vmDescriptors = (List) method.invoke(null);
for (Object descriptor : vmDescriptors) {
Method idMethod = descriptor.getClass().getMethod("id");
String id = (String) idMethod.invoke(descriptor);
Method displayMethod = descriptor.getClass().getMethod("displayName");
String display = (String) displayMethod.invoke(descriptor);
ret.add(new ProcessDescription(id, display));
}
return ret;
} | java | {
"resource": ""
} |
q162724 | VirtualMachineHandler.findProcess | train | public ProcessDescription findProcess(Pattern pPattern)
throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
List<ProcessDescription> ret = new ArrayList<ProcessDescription>();
String ownId = getOwnProcessId();
for (ProcessDescription desc : listProcesses()) {
Matcher matcher = pPattern.matcher(desc.getDisplay());
if (!desc.getId().equals(ownId) && matcher.find()) {
ret.add(desc);
}
}
if (ret.size() == 1) {
return ret.get(0);
} else if (ret.size() == 0) {
throw new IllegalArgumentException("No attachable process found matching \"" + pPattern.pattern() + "\"");
} else {
StringBuilder buf = new StringBuilder();
for (ProcessDescription desc : ret) {
buf.append(desc.getId()).append(" (").append(desc.getDisplay()).append("),");
}
throw new IllegalArgumentException("More than one attachable process found matching \"" +
pPattern.pattern() + "\": " + buf.substring(0,buf.length()-1));
}
} | java | {
"resource": ""
} |
q162725 | VirtualMachineHandler.getOwnProcessId | train | private String getOwnProcessId() {
// Format of name is : <pid>@<host>
String name = ManagementFactory.getRuntimeMXBean().getName();
int endIdx = name.indexOf('@');
return endIdx != -1 ? name.substring(0,endIdx) : name;
} | java | {
"resource": ""
} |
q162726 | VirtualMachineHandler.lookupVirtualMachineClass | train | private Class lookupVirtualMachineClass() {
try {
return ToolsClassFinder.lookupClass("com.sun.tools.attach.VirtualMachine");
} catch (ClassNotFoundException exp) {
throw new ProcessingException(
"Cannot find classes from tools.jar. The heuristics for loading tools.jar which contains\n" +
"essential classes for attaching to a running JVM could locate the necessary jar file.\n" +
"\n" +
"Please call this launcher with a qualified classpath on the command line like\n" +
"\n" +
" java -cp path/to/tools.jar:" + options.getJarFileName() + " org.jolokia.jvmagent.client.AgentLauncher [options] <command> <ppid>\n",
exp,
options);
}
} | java | {
"resource": ""
} |
q162727 | MBeanServers.handleNotification | train | public synchronized void handleNotification(Notification notification, Object handback) {
String type = notification.getType();
if (REGISTRATION_NOTIFICATION.equals(type)) {
jolokiaMBeanServer = lookupJolokiaMBeanServer();
// We need to add the listener provided during construction time to add the Jolokia MBeanServer
// so that it is kept updated, too.
if (jolokiaMBeanServerListener != null) {
JmxUtil.addMBeanRegistrationListener(jolokiaMBeanServer, jolokiaMBeanServerListener, null);
}
} else if (UNREGISTRATION_NOTIFICATION.equals(type)) {
jolokiaMBeanServer = null;
}
allMBeanServers.clear();
if (jolokiaMBeanServer != null) {
allMBeanServers.add(jolokiaMBeanServer);
}
allMBeanServers.addAll(detectedMBeanServers);
} | java | {
"resource": ""
} |
q162728 | MBeanServers.lookupJolokiaMBeanServer | train | private MBeanServer lookupJolokiaMBeanServer() {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
return server.isRegistered(JOLOKIA_MBEAN_SERVER_ONAME) ?
(MBeanServer) server.getAttribute(JOLOKIA_MBEAN_SERVER_ONAME, "JolokiaMBeanServer") :
null;
} catch (JMException e) {
throw new IllegalStateException("Internal: Cannot get Jolokia MBeanServer via JMX lookup: " + e, e);
}
} | java | {
"resource": ""
} |
q162729 | AbstractChecker.assertNodeName | train | protected void assertNodeName(Node pNode, String ... pExpected) {
for (String expected : pExpected) {
if (pNode.getNodeName().equals(expected)) {
return;
}
}
StringBuilder buffer = new StringBuilder();
for (int i=0; i < pExpected.length; i++) {
buffer.append(pExpected[i]);
if (i < pExpected.length-1) {
buffer.append(",");
}
}
throw new SecurityException(
"Expected element " + buffer.toString() + " but got " + pNode.getNodeName());
} | java | {
"resource": ""
} |
q162730 | JolokiaMBeanServer.extractJsonMBeanAnnotation | train | private JsonMBean extractJsonMBeanAnnotation(Object object) {
// Try directly
Class<?> clazz = object.getClass();
JsonMBean anno = clazz.getAnnotation(JsonMBean.class);
if (anno == null && ModelMBean.class.isAssignableFrom(object.getClass())) {
// For ModelMBean we try some heuristic to get to the managed resource
// This works for all subclasses of RequiredModelMBean as provided by the JDK
// but maybe for other ModelMBean classes as well
Boolean isAccessible = null;
Field field = null;
try {
field = findField(clazz, "managedResource");
if (field != null) {
isAccessible = field.isAccessible();
field.setAccessible(true);
Object managedResource = field.get(object);
anno = managedResource.getClass().getAnnotation(JsonMBean.class);
}
} catch (IllegalAccessException e) {
// Ignored silently, but we tried it at least
} finally {
if (isAccessible != null) {
field.setAccessible(isAccessible);
}
}
}
return anno;
} | java | {
"resource": ""
} |
q162731 | JolokiaMBeanServer.findField | train | private Field findField(Class<?> pClazz, String pField) {
Class c = pClazz;
do {
try {
return c.getDeclaredField(pField);
} catch (NoSuchFieldException e) {
c = pClazz.getSuperclass();
}
} while (c != null);
return null;
} | java | {
"resource": ""
} |
q162732 | JolokiaMBeanServer.toJson | train | String toJson(Object object, JsonConvertOptions pConvertOptions) {
try {
Object ret = converters.getToJsonConverter().convertToJson(object,null,pConvertOptions);
return ret.toString();
} catch (AttributeNotFoundException exp) {
// Cannot happen, since we dont use a path
return "";
}
} | java | {
"resource": ""
} |
q162733 | JolokiaMBeanServer.getJsonConverterOptions | train | private JsonConvertOptions getJsonConverterOptions(JsonMBean pAnno) {
// Extract conversion options from the annotation
if (pAnno == null) {
return JsonConvertOptions.DEFAULT;
} else {
ValueFaultHandler faultHandler =
pAnno.faultHandling() == JsonMBean.FaultHandler.IGNORE_ERRORS ?
ValueFaultHandler.IGNORING_VALUE_FAULT_HANDLER :
ValueFaultHandler.THROWING_VALUE_FAULT_HANDLER;
return new JsonConvertOptions.Builder()
.maxCollectionSize(pAnno.maxCollectionSize())
.maxDepth(pAnno.maxDepth())
.maxObjects(pAnno.maxObjects())
.faultHandler(faultHandler)
.build();
}
} | java | {
"resource": ""
} |
q162734 | JolokiaServerConfig.init | train | protected void init(Map<String, String> pConfig) {
Map<String, String> finalCfg = getDefaultConfig(pConfig);
finalCfg.putAll(pConfig);
prepareDetectorOptions(finalCfg);
addJolokiaId(finalCfg);
jolokiaConfig = new Configuration();
jolokiaConfig.updateGlobalConfiguration(finalCfg);
initConfigAndValidate(finalCfg);
} | java | {
"resource": ""
} |
q162735 | JolokiaServerConfig.addJolokiaId | train | private void addJolokiaId(Map<String, String> pFinalCfg) {
if (!pFinalCfg.containsKey(ConfigKey.AGENT_ID.getKeyValue())) {
pFinalCfg.put(ConfigKey.AGENT_ID.getKeyValue(), NetworkUtil.getAgentId(hashCode(),"jvm"));
}
pFinalCfg.put(ConfigKey.AGENT_TYPE.getKeyValue(), "jvm");
} | java | {
"resource": ""
} |
q162736 | JolokiaServerConfig.updateHTTPSSettingsFromContext | train | public void updateHTTPSSettingsFromContext(SSLContext sslContext) {
SSLParameters parameters = sslContext.getSupportedSSLParameters();
// Protocols
if (sslProtocols == null) {
sslProtocols = parameters.getProtocols();
} else {
List<String> supportedProtocols = Arrays.asList(parameters.getProtocols());
List<String> sslProtocolsList = new ArrayList<String>(Arrays.asList(sslProtocols));
Iterator<String> pit = sslProtocolsList.iterator();
while (pit.hasNext()) {
String protocol = pit.next();
if (!supportedProtocols.contains(protocol)) {
System.out.println("Jolokia: Discarding unsupported protocol: " + protocol);
pit.remove();
}
}
sslProtocols = sslProtocolsList.toArray(new String[0]);
}
// Cipher Suites
if (sslCipherSuites == null) {
sslCipherSuites = parameters.getCipherSuites();
} else {
List<String> supportedCipherSuites = Arrays.asList(parameters.getCipherSuites());
List<String> sslCipherSuitesList = new ArrayList<String>(Arrays.asList(sslCipherSuites));
Iterator<String> cit = sslCipherSuitesList.iterator();
while (cit.hasNext()) {
String cipher = cit.next();
if (!supportedCipherSuites.contains(cipher)) {
System.out.println("Jolokia: Discarding unsupported cipher suite: " + cipher);
cit.remove();
}
}
sslCipherSuites = sslCipherSuitesList.toArray(new String[0]);
}
} | java | {
"resource": ""
} |
q162737 | JolokiaServerConfig.initConfigAndValidate | train | protected void initConfigAndValidate(Map<String,String> agentConfig) {
initContext();
initProtocol(agentConfig);
initAddress(agentConfig);
port = Integer.parseInt(agentConfig.get("port"));
backlog = Integer.parseInt(agentConfig.get("backlog"));
initExecutor(agentConfig);
initThreadNamePrefix(agentConfig);
initThreadNr(agentConfig);
initHttpsRelatedSettings(agentConfig);
initAuthenticator();
} | java | {
"resource": ""
} |
q162738 | JolokiaServerConfig.extractList | train | private List<String> extractList(Map<String, String> pAgentConfig, String pKey) {
List<String> ret = new ArrayList<String>();
if (pAgentConfig.containsKey(pKey)) {
ret.add(pAgentConfig.get(pKey));
}
int idx = 1;
String keyIdx = pKey + "." + idx;
while (pAgentConfig.containsKey(keyIdx)) {
ret.add(pAgentConfig.get(keyIdx));
keyIdx = pKey + "." + ++idx;
}
return ret.size() > 0 ? ret : null;
} | java | {
"resource": ""
} |
q162739 | JolokiaServerConfig.prepareDetectorOptions | train | protected void prepareDetectorOptions(Map<String, String> pConfig) {
StringBuffer detectorOpts = new StringBuffer("{");
if (pConfig.containsKey("bootAmx") && Boolean.parseBoolean(pConfig.get("bootAmx"))) {
detectorOpts.append("\"glassfish\" : { \"bootAmx\" : true }");
}
if (detectorOpts.length() > 1) {
detectorOpts.append("}");
pConfig.put(ConfigKey.DETECTOR_OPTIONS.getKeyValue(),detectorOpts.toString());
}
} | java | {
"resource": ""
} |
q162740 | ServerHandle.registerMBeanAtServer | train | public ObjectName registerMBeanAtServer(MBeanServer pServer, Object pMBean, String pName)
throws MBeanRegistrationException, InstanceAlreadyExistsException, NotCompliantMBeanException, MalformedObjectNameException {
if (pName != null) {
ObjectName oName = new ObjectName(pName);
return pServer.registerMBean(pMBean,oName).getObjectName();
} else {
// Needs to implement MBeanRegistration interface
return pServer.registerMBean(pMBean,null).getObjectName();
}
} | java | {
"resource": ""
} |
q162741 | ServerHandle.toJSONObject | train | public JSONObject toJSONObject(MBeanServerExecutor pServerManager) {
JSONObject ret = new JSONObject();
addNullSafe(ret, "vendor", vendor);
addNullSafe(ret, "product", product);
addNullSafe(ret, "version", version);
Map<String,String> extra = getExtraInfo(pServerManager);
if (extra != null) {
JSONObject jsonExtra = new JSONObject();
for (Map.Entry<String,String> entry : extra.entrySet()) {
jsonExtra.put(entry.getKey(),entry.getValue());
}
ret.put("extraInfo", jsonExtra);
}
return ret;
} | java | {
"resource": ""
} |
q162742 | ServerHandle.getDetectorOptions | train | protected JSONObject getDetectorOptions(Configuration pConfig, LogHandler pLogHandler) {
String options = pConfig.get(ConfigKey.DETECTOR_OPTIONS);
try {
if (options != null) {
JSONObject opts = (JSONObject) new JSONParser().parse(options);
return (JSONObject) opts.get(getProduct());
}
return null;
} catch (ParseException e) {
pLogHandler.error("Could not parse detector options '" + options + "' as JSON object: " + e,e);
}
return null;
} | java | {
"resource": ""
} |
q162743 | JvmAgentConfig.getDefaultConfig | train | @Override
protected Map<String, String> getDefaultConfig(Map<String,String> pConfig) {
Map<String,String> config = super.getDefaultConfig(pConfig);
if (pConfig.containsKey("config")) {
config.putAll(readConfig(pConfig.get("config")));
}
return config;
} | java | {
"resource": ""
} |
q162744 | JvmAgentConfig.split | train | private static Map<String, String> split(String pAgentArgs) {
Map<String,String> ret = new HashMap<String, String>();
if (pAgentArgs != null && pAgentArgs.length() > 0) {
for (String arg : EscapeUtil.splitAsArray(pAgentArgs, EscapeUtil.CSV_ESCAPE, ",")) {
String[] prop = arg.split("=",2);
if (prop == null || prop.length != 2) {
throw new IllegalArgumentException("jolokia: Invalid option '" + arg + "'");
} else {
ret.put(prop[0],prop[1]);
}
}
}
return ret;
} | java | {
"resource": ""
} |
q162745 | ServiceObjectFactory.createServiceObjects | train | public static <T> List<T> createServiceObjects(String... pDescriptorPaths) {
try {
ServiceEntry.initDefaultOrder();
TreeMap<ServiceEntry,T> extractorMap = new TreeMap<ServiceEntry,T>();
for (String descriptor : pDescriptorPaths) {
readServiceDefinitions(extractorMap, descriptor);
}
ArrayList<T> ret = new ArrayList<T>();
for (T service : extractorMap.values()) {
ret.add(service);
}
return ret;
} finally {
ServiceEntry.removeDefaultOrder();
}
} | java | {
"resource": ""
} |
q162746 | J4pReadResponse.getObjectNames | train | public Collection<ObjectName> getObjectNames() throws MalformedObjectNameException {
ObjectName mBean = getRequest().getObjectName();
if (mBean.isPattern()) {
// The result value contains the list of fetched object names
JSONObject values = getValue();
Set<ObjectName> ret = new HashSet<ObjectName>();
for (Object name : values.keySet()) {
ret.add(new ObjectName((String) name));
}
return ret;
} else {
return Arrays.asList(mBean);
}
} | java | {
"resource": ""
} |
q162747 | J4pTargetConfig.toJson | train | public JSONObject toJson() {
JSONObject ret = new JSONObject();
ret.put("url",url);
if (user != null) {
ret.put("user",user);
ret.put("password",password);
}
return ret;
} | java | {
"resource": ""
} |
q162748 | HistoryEntry.add | train | public void add(Object pObject, long pTime) {
values.addFirst(new ValueEntry(pObject,pTime));
trim();
} | java | {
"resource": ""
} |
q162749 | HistoryEntry.trim | train | private void trim() {
// Trim
while (values.size() > limit.getMaxEntries()) {
values.removeLast();
}
// Trim according to duration
if (limit.getMaxDuration() > 0 && !values.isEmpty()) {
long duration = limit.getMaxDuration();
long start = values.getFirst().getTimestamp();
while (start - values.getLast().getTimestamp() > duration) {
values.removeLast();
}
}
} | java | {
"resource": ""
} |
q162750 | Config.limitOrNull | train | private HistoryLimit limitOrNull(int pMaxEntries, long pMaxDuration) {
return pMaxEntries != 0 || pMaxDuration != 0 ? new HistoryLimit(pMaxEntries, pMaxDuration) : null;
} | java | {
"resource": ""
} |
q162751 | IpChecker.matches | train | public static boolean matches(String pExpected, String pToCheck) {
String[] parts = pExpected.split("/",2);
if (parts.length == 1) {
// No Net part given, check for equality ...
// Check for valid ips
convertToIntTuple(pExpected);
convertToIntTuple(pToCheck);
return pExpected.equals(pToCheck);
} else if (parts.length == 2) {
int ipToCheck[] = convertToIntTuple(pToCheck);
int ipPattern[] = convertToIntTuple(parts[0]);
int netmask[];
if (parts[1].length() <= 2) {
netmask = transformCidrToNetmask(parts[1]);
} else {
netmask = convertToIntTuple(parts[1]);
}
for (int i = 0; i<ipToCheck.length; i++) {
if ((ipPattern[i] & netmask[i]) != (ipToCheck[i] & netmask[i])) {
return false;
}
}
return true;
} else {
throw new IllegalArgumentException("Invalid IP adress specification " + pExpected);
}
} | java | {
"resource": ""
} |
q162752 | ProxyTargetConfig.toJSON | train | public JSONObject toJSON() {
JSONObject ret = new JSONObject();
ret.put("url", url);
if (env != null) {
ret.put("env", env);
}
return ret;
} | java | {
"resource": ""
} |
q162753 | JmxUtil.addMBeanRegistrationListener | train | public static void addMBeanRegistrationListener(MBeanServerConnection pServer, NotificationListener pListener,
ObjectName pObjectNameToFilter) {
MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter();
if (pObjectNameToFilter == null) {
filter.enableAllObjectNames();
} else {
filter.enableObjectName(pObjectNameToFilter);
}
try {
pServer.addNotificationListener(getMBeanServerDelegateName(), pListener, filter, null);
} catch (InstanceNotFoundException e) {
throw new IllegalStateException("Cannot find " + getMBeanServerDelegateName() + " in server " + pServer,e);
} catch (IOException e) {
throw new IllegalStateException("IOException while registering notification listener for " + getMBeanServerDelegateName(),e);
}
} | java | {
"resource": ""
} |
q162754 | JmxUtil.removeMBeanRegistrationListener | train | public static void removeMBeanRegistrationListener(MBeanServerConnection pServer,NotificationListener pListener) {
try {
pServer.removeNotificationListener(JmxUtil.getMBeanServerDelegateName(), pListener);
} catch (ListenerNotFoundException e) {
// We silently ignore listeners not found, they might have been deregistered previously
} catch (InstanceNotFoundException e) {
throw new IllegalStateException("Cannot find " + getMBeanServerDelegateName() + " in server " + pServer,e);
} catch (IOException e) {
throw new IllegalStateException("IOException while registering notification listener for " + getMBeanServerDelegateName(),e);
}
} | java | {
"resource": ""
} |
q162755 | ObjectToJsonConverter.convertToJson | train | public Object convertToJson(Object pValue, List<String> pPathParts, JsonConvertOptions pOptions)
throws AttributeNotFoundException {
Stack<String> extraStack = pPathParts != null ? EscapeUtil.reversePath(pPathParts) : new Stack<String>();
return extractObjectWithContext(pValue, extraStack, pOptions, true);
} | java | {
"resource": ""
} |
q162756 | ObjectToJsonConverter.setObjectValue | train | private Object setObjectValue(Object pInner, String pAttribute, Object pValue)
throws IllegalAccessException, InvocationTargetException {
// Call various handlers depending on the type of the inner object, as is extract Object
Class clazz = pInner.getClass();
if (clazz.isArray()) {
return arrayExtractor.setObjectValue(stringToObjectConverter,pInner,pAttribute,pValue);
}
Extractor handler = getExtractor(clazz);
if (handler != null) {
return handler.setObjectValue(stringToObjectConverter,pInner,pAttribute,pValue);
} else {
throw new IllegalStateException(
"Internal error: No handler found for class " + clazz + " for setting object value." +
" (object: " + pInner + ", attribute: " + pAttribute + ", value: " + pValue + ")");
}
} | java | {
"resource": ""
} |
q162757 | ObjectToJsonConverter.setupContext | train | void setupContext(JsonConvertOptions pOpts) {
ObjectSerializationContext stackContext = new ObjectSerializationContext(pOpts);
stackContextLocal.set(stackContext);
} | java | {
"resource": ""
} |
q162758 | ObjectToJsonConverter.getExtractor | train | private Extractor getExtractor(Class pClazz) {
for (Extractor handler : handlers) {
if (handler.canSetValue() && handler.getType() != null && handler.getType().isAssignableFrom(pClazz)) {
return handler;
}
}
return null;
} | java | {
"resource": ""
} |
q162759 | ObjectToJsonConverter.addSimplifiers | train | private void addSimplifiers(List<Extractor> pHandlers, Extractor[] pSimplifyHandlers) {
if (pSimplifyHandlers != null && pSimplifyHandlers.length > 0) {
pHandlers.addAll(Arrays.asList(pSimplifyHandlers));
} else {
// Add all
pHandlers.addAll(ServiceObjectFactory.<Extractor>createServiceObjects(SIMPLIFIERS_DEFAULT_DEF, SIMPLIFIERS_DEF));
}
} | java | {
"resource": ""
} |
q162760 | J4pRequest.toJson | train | JSONObject toJson() {
JSONObject ret = new JSONObject();
ret.put("type",type.name());
if (targetConfig != null) {
ret.put("target",targetConfig.toJson());
}
return ret;
} | java | {
"resource": ""
} |
q162761 | J4pRequest.nullEscape | train | private String nullEscape(Object pArg) {
if (pArg == null) {
return "[null]";
} else if (pArg instanceof String && ((String) pArg).length() == 0) {
return "\"\"";
} else if (pArg instanceof JSONAware) {
return ((JSONAware) pArg).toJSONString();
} else {
return pArg.toString();
}
} | java | {
"resource": ""
} |
q162762 | MulticastUtil.sendQueryAndCollectAnswers | train | public static List<DiscoveryIncomingMessage> sendQueryAndCollectAnswers(DiscoveryOutgoingMessage pOutMsg,
int pTimeout,
LogHandler pLogHandler) throws IOException {
final List<Future<List<DiscoveryIncomingMessage>>> futures = sendDiscoveryRequests(pOutMsg, pTimeout, pLogHandler);
return collectIncomingMessages(pTimeout, futures, pLogHandler);
} | java | {
"resource": ""
} |
q162763 | MulticastUtil.sendDiscoveryRequests | train | private static List<Future<List<DiscoveryIncomingMessage>>> sendDiscoveryRequests(DiscoveryOutgoingMessage pOutMsg,
int pTimeout,
LogHandler pLogHandler) throws SocketException, UnknownHostException {
// Note for Ipv6 support: If there are two local addresses, one with IpV6 and one with IpV4 then two discovery request
// should be sent, on each interface respectively. Currently, only IpV4 is supported.
List<InetAddress> addresses = getMulticastAddresses();
ExecutorService executor = Executors.newFixedThreadPool(addresses.size());
final List<Future<List<DiscoveryIncomingMessage>>> futures = new ArrayList<Future<List<DiscoveryIncomingMessage>>>(addresses.size());
for (InetAddress address : addresses) {
// Discover UDP packet send to multicast address
DatagramPacket out = pOutMsg.createDatagramPacket(InetAddress.getByName(JOLOKIA_MULTICAST_GROUP), JOLOKIA_MULTICAST_PORT);
Callable<List<DiscoveryIncomingMessage>> findAgentsCallable = new FindAgentsCallable(address, out, pTimeout, pLogHandler);
futures.add(executor.submit(findAgentsCallable));
}
executor.shutdownNow();
return futures;
} | java | {
"resource": ""
} |
q162764 | MulticastUtil.getMulticastAddresses | train | private static List<InetAddress> getMulticastAddresses() throws SocketException, UnknownHostException {
List<InetAddress> addresses = NetworkUtil.getMulticastAddresses();
if (addresses.size() == 0) {
throw new UnknownHostException("Cannot find address of local host which can be used for sending discovery request");
}
return addresses;
} | java | {
"resource": ""
} |
q162765 | MulticastUtil.collectIncomingMessages | train | private static List<DiscoveryIncomingMessage> collectIncomingMessages(int pTimeout, List<Future<List<DiscoveryIncomingMessage>>> pFutures, LogHandler pLogHandler) throws UnknownHostException {
List<DiscoveryIncomingMessage> ret = new ArrayList<DiscoveryIncomingMessage>();
Set<String> seen = new HashSet<String>();
int nrCouldntSend = 0;
for (Future<List<DiscoveryIncomingMessage>> future : pFutures) {
try {
List<DiscoveryIncomingMessage> inMsgs = future.get(pTimeout + 500 /* some additional buffer */, TimeUnit.MILLISECONDS);
for (DiscoveryIncomingMessage inMsg : inMsgs) {
AgentDetails details = inMsg.getAgentDetails();
String id = details.getAgentId();
// There can be multiples answers with the same message id
if (!seen.contains(id)) {
ret.add(inMsg);
seen.add(id);
}
}
} catch (InterruptedException exp) {
// Try next one ...
} catch (ExecutionException e) {
Throwable exp = e.getCause();
if (exp instanceof CouldntSendDiscoveryPacketException) {
nrCouldntSend++;
pLogHandler.debug("--> Couldnt send discovery message from " +
((CouldntSendDiscoveryPacketException) exp).getAddress() + ": " + exp.getCause());
}
// Didn't worked a given address, which can happen e.g. when multicast is not routed or in other cases
// throw new IOException("Error while performing a discovery call " + e,e);
pLogHandler.debug("--> Exception during lookup: " + e);
} catch (TimeoutException e) {
// Timeout occurred while waiting for the results. So we go to the next one ...
}
}
if (nrCouldntSend == pFutures.size()) {
// No a single discovery message could be send out
throw new UnknownHostException("Cannot send a single multicast recovery request on any multicast enabled interface");
}
return ret;
} | java | {
"resource": ""
} |
q162766 | MulticastUtil.joinMcGroupsOnAllNetworkInterfaces | train | private static int joinMcGroupsOnAllNetworkInterfaces(MulticastSocket pSocket, InetSocketAddress pSocketAddress, LogHandler pLogHandler) throws IOException {
// V6: ffx8::/16
Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
int interfacesJoined = 0;
while (nifs.hasMoreElements()) {
NetworkInterface n = nifs.nextElement();
if (NetworkUtil.isMulticastSupported(n)) {
try {
pSocket.joinGroup(pSocketAddress, n);
interfacesJoined++;
} catch (IOException exp) {
pLogHandler.info("Cannot join multicast group on NIF " + n.getDisplayName() + ": " + exp.getMessage());
}
}
}
return interfacesJoined;
} | java | {
"resource": ""
} |
q162767 | NetworkChecker.check | train | @Override
public boolean check(String[] pHostOrAddresses) {
if (allowedHostsSet == null) {
return true;
}
for (String addr : pHostOrAddresses) {
if (allowedHostsSet.contains(addr)) {
return true;
}
if (allowedSubnetsSet != null && IP_PATTERN.matcher(addr).matches()) {
for (String subnet : allowedSubnetsSet) {
if (IpChecker.matches(subnet, addr)) {
return true;
}
}
}
}
return false;
} | java | {
"resource": ""
} |
q162768 | MapExtractor.setObjectValue | train | public Object setObjectValue(StringToObjectConverter pConverter, Object pMap, String pKey, Object pValue)
throws IllegalAccessException, InvocationTargetException {
Map<Object,Object> map = (Map<Object,Object>) pMap;
Object oldValue = null;
Object oldKey = pKey;
for (Map.Entry entry : map.entrySet()) {
// We dont access the map via a lookup since the key
// are potentially object but we have to deal with string
// representations
if(pKey.equals(entry.getKey().toString())) {
oldValue = entry.getValue();
oldKey = entry.getKey();
break;
}
}
Object value =
oldValue != null ?
pConverter.prepareValue(oldValue.getClass().getName(), pValue) :
pValue;
map.put(oldKey,value);
return oldValue;
} | java | {
"resource": ""
} |
q162769 | ProcessingParameters.get | train | public String get(ConfigKey pKey) {
String value = params.get(pKey);
if (value != null) {
return value;
} else {
return pKey.getDefaultValue();
}
} | java | {
"resource": ""
} |
q162770 | ProcessingParameters.mergedParams | train | public ProcessingParameters mergedParams(Map<String, String> pConfig) {
if (pConfig == null) {
return this;
} else {
Map<ConfigKey,String> newParams = new HashMap<ConfigKey, String>();
newParams.putAll(params);
newParams.putAll(convertToConfigMap(pConfig));
return new ProcessingParameters(newParams, pathInfo);
}
} | java | {
"resource": ""
} |
q162771 | ProcessingParameters.convertToConfigMap | train | static Map<ConfigKey, String> convertToConfigMap(Map<String, String> pParams) {
Map<ConfigKey,String> config = new HashMap<ConfigKey, String>();
if (pParams != null) {
for (Map.Entry<String,?> entry : pParams.entrySet()) {
ConfigKey cKey = ConfigKey.getRequestConfigKey(entry.getKey());
if (cKey != null) {
Object value = entry.getValue();
config.put(cKey, value != null ? value.toString() : null);
}
}
}
return config;
} | java | {
"resource": ""
} |
q162772 | HttpRequestHandler.handleGetRequest | train | public JSONAware handleGetRequest(String pUri, String pPathInfo, Map<String, String[]> pParameterMap) {
String pathInfo = extractPathInfo(pUri, pPathInfo);
JmxRequest jmxReq =
JmxRequestFactory.createGetRequest(pathInfo,getProcessingParameter(pParameterMap));
if (backendManager.isDebug()) {
logHandler.debug("URI: " + pUri);
logHandler.debug("Path-Info: " + pathInfo);
logHandler.debug("Request: " + jmxReq.toString());
}
return executeRequest(jmxReq);
} | java | {
"resource": ""
} |
q162773 | HttpRequestHandler.handlePostRequest | train | public JSONAware handlePostRequest(String pUri, InputStream pInputStream, String pEncoding, Map<String, String[]> pParameterMap)
throws IOException {
if (backendManager.isDebug()) {
logHandler.debug("URI: " + pUri);
}
Object jsonRequest = extractJsonRequest(pInputStream,pEncoding);
if (jsonRequest instanceof JSONArray) {
List<JmxRequest> jmxRequests = JmxRequestFactory.createPostRequests((List) jsonRequest,getProcessingParameter(pParameterMap));
JSONArray responseList = new JSONArray();
for (JmxRequest jmxReq : jmxRequests) {
if (backendManager.isDebug()) {
logHandler.debug("Request: " + jmxReq.toString());
}
// Call handler and retrieve return value
JSONObject resp = executeRequest(jmxReq);
responseList.add(resp);
}
return responseList;
} else if (jsonRequest instanceof JSONObject) {
JmxRequest jmxReq = JmxRequestFactory.createPostRequest((Map<String, ?>) jsonRequest,getProcessingParameter(pParameterMap));
return executeRequest(jmxReq);
} else {
throw new IllegalArgumentException("Invalid JSON Request " + jsonRequest);
}
} | java | {
"resource": ""
} |
q162774 | HttpRequestHandler.getErrorJSON | train | public JSONObject getErrorJSON(int pErrorCode, Throwable pExp, JmxRequest pJmxReq) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("status",pErrorCode);
jsonObject.put("error",getExceptionMessage(pExp));
jsonObject.put("error_type", pExp.getClass().getName());
addErrorInfo(jsonObject, pExp, pJmxReq);
if (backendManager.isDebug()) {
backendManager.error("Error " + pErrorCode,pExp);
}
if (pJmxReq != null) {
jsonObject.put("request",pJmxReq.toJSON());
}
return jsonObject;
} | java | {
"resource": ""
} |
q162775 | HttpRequestHandler.extractCorsOrigin | train | public String extractCorsOrigin(String pOrigin) {
if (pOrigin != null) {
// Prevent HTTP response splitting attacks
String origin = pOrigin.replaceAll("[\\n\\r]*","");
if (backendManager.isOriginAllowed(origin,false)) {
return "null".equals(origin) ? "*" : origin;
} else {
return null;
}
}
return null;
} | java | {
"resource": ""
} |
q162776 | HttpRequestHandler.getExceptionMessage | train | private String getExceptionMessage(Throwable pException) {
String message = pException.getLocalizedMessage();
return pException.getClass().getName() + (message != null ? " : " + message : "");
} | java | {
"resource": ""
} |
q162777 | HttpRequestHandler.errorForUnwrappedException | train | private JSONObject errorForUnwrappedException(Exception e, JmxRequest pJmxReq) {
Throwable cause = e.getCause();
int code = cause instanceof IllegalArgumentException ? 400 : cause instanceof SecurityException ? 403 : 500;
return getErrorJSON(code,cause, pJmxReq);
} | java | {
"resource": ""
} |
q162778 | AbstractServerDetector.searchMBeans | train | protected Set<ObjectName> searchMBeans(MBeanServerExecutor pMBeanServerExecutor, String pMbeanPattern) {
try {
ObjectName oName = new ObjectName(pMbeanPattern);
return pMBeanServerExecutor.queryNames(oName);
} catch (MalformedObjectNameException e) {
return new HashSet<ObjectName>();
} catch (IOException e) {
return new HashSet<ObjectName>();
}
} | java | {
"resource": ""
} |
q162779 | AbstractServerDetector.getSingleStringAttribute | train | protected String getSingleStringAttribute(MBeanServerExecutor pMBeanServerExecutor, String pMBeanName, String pAttribute) {
Set<ObjectName> serverMBeanNames = searchMBeans(pMBeanServerExecutor, pMBeanName);
if (serverMBeanNames.size() == 0) {
return null;
}
Set<String> attributeValues = new HashSet<String>();
for (ObjectName oName : serverMBeanNames) {
String val = getAttributeValue(pMBeanServerExecutor, oName, pAttribute);
if (val != null) {
attributeValues.add(val);
}
}
if (attributeValues.size() == 0 || attributeValues.size() > 1) {
return null;
}
return attributeValues.iterator().next();
} | java | {
"resource": ""
} |
q162780 | AbstractServerDetector.getVersionFromJsr77 | train | protected String getVersionFromJsr77(MBeanServerExecutor pMbeanServers) {
Set<ObjectName> names = searchMBeans(pMbeanServers, "*:j2eeType=J2EEServer,*");
// Take the first one
if (names.size() > 0) {
return getAttributeValue(pMbeanServers, names.iterator().next(), "serverVersion");
}
return null;
} | java | {
"resource": ""
} |
q162781 | AbstractServerDetector.isClassLoaded | train | protected boolean isClassLoaded(String className, Instrumentation instrumentation) {
if (instrumentation == null || className == null) {
throw new IllegalArgumentException("instrumentation and className must not be null");
}
Class<?>[] classes = instrumentation.getAllLoadedClasses();
for (Class<?> c : classes) {
if (className.equals(c.getName())) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q162782 | J4pClientBuilder.proxy | train | public final J4pClientBuilder proxy(String pProxyHost, int pProxyPort, String pProxyUser, String pProxyPass) {
httpProxy = new Proxy(pProxyHost,pProxyPort, pProxyUser,pProxyPass);
return this;
} | java | {
"resource": ""
} |
q162783 | J4pClientBuilder.useProxyFromEnvironment | train | public final J4pClientBuilder useProxyFromEnvironment(){
Map<String, String> env = System.getenv();
for (String key : env.keySet()) {
if (key.equalsIgnoreCase("http_proxy")){
httpProxy = parseProxySettings(env.get(key));
break;
}
}
return this;
} | java | {
"resource": ""
} |
q162784 | J4pClientBuilder.build | train | public J4pClient build() {
return new J4pClient(url,createHttpClient(),
targetUrl != null ? new J4pTargetConfig(targetUrl,targetUser,targetPassword) : null,
responseExtractor);
} | java | {
"resource": ""
} |
q162785 | J4pClientBuilder.parseProxySettings | train | static Proxy parseProxySettings(String spec) {
try {
if (spec == null || spec.length() == 0) {
return null;
}
return new Proxy(spec);
} catch (URISyntaxException e) {
return null;
}
} | java | {
"resource": ""
} |
q162786 | ClassUtil.newInstance | train | public static <T> T newInstance(String pClassName, Object ... pArguments) {
Class<T> clazz = classForName(pClassName);
if (clazz == null) {
throw new IllegalArgumentException("Cannot find " + pClassName);
}
return newInstance(clazz, pArguments);
} | java | {
"resource": ""
} |
q162787 | ClassUtil.newInstance | train | public static <T> T newInstance(Class<T> pClass, Object ... pArguments) {
try {
if (pClass != null) {
if (pArguments.length == 0) {
return pClass.newInstance();
} else {
Constructor<T> ctr = lookupConstructor(pClass, pArguments);
return ctr.newInstance(pArguments);
}
} else {
throw new IllegalArgumentException("Given class must not be null");
}
} catch (InstantiationException e) {
throw new IllegalArgumentException("Cannot instantiate " + pClass + ": " + e,e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Cannot instantiate " + pClass + ": " + e,e);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Cannot instantiate " + pClass + ": " + e,e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Cannot instantiate " + pClass + ": " + e,e);
}
} | java | {
"resource": ""
} |
q162788 | ClassUtil.applyMethod | train | 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);
}
} | java | {
"resource": ""
} |
q162789 | ClassUtil.getResources | train | 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));
}
} | java | {
"resource": ""
} |
q162790 | ClassUtil.lookupConstructor | train | private static <T> Constructor<T> lookupConstructor(Class<T> clazz, Object[] pArguments) throws NoSuchMethodException {
Class[] argTypes = extractArgumentTypes(pArguments);
return clazz.getConstructor(argTypes);
} | java | {
"resource": ""
} |
q162791 | DateUtil.fromISO8601 | train | public static Date fromISO8601(String pDateString) {
if (datatypeFactory != null) {
return datatypeFactory.newXMLGregorianCalendar(pDateString.trim()).toGregorianCalendar().getTime();
} else {
try {
// Try on our own, works for most cases
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);
}
}
} | java | {
"resource": ""
} |
q162792 | DateUtil.toISO8601 | train | 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");
} | java | {
"resource": ""
} |
q162793 | IoUtil.streamResponseAndClose | train | 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(");");
}
// Writer end marker for chunked responses
pWriter.write(STREAM_END_MARKER);
} finally {
// Flush and close, even on an exception to avoid locks in the thread
pWriter.flush();
pWriter.close();
}
} | java | {
"resource": ""
} |
q162794 | JmxRequest.getParameterAsInt | train | public int getParameterAsInt(ConfigKey pConfigKey) {
String intValueS = processingConfig.get(pConfigKey);
if (intValueS != null) {
return Integer.parseInt(intValueS);
} else {
return 0;
}
} | java | {
"resource": ""
} |
q162795 | JmxRequest.getParameterAsBool | train | public Boolean getParameterAsBool(ConfigKey pConfigKey) {
String booleanS = getParameter(pConfigKey);
return Boolean.parseBoolean(booleanS != null ? booleanS : pConfigKey.getDefaultValue());
} | java | {
"resource": ""
} |
q162796 | JmxRequest.toJSON | train | 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) {
// Happens when request doesnt support paths
}
}
return ret;
} | java | {
"resource": ""
} |
q162797 | JmxRequest.initParameters | train | 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;
}
} | java | {
"resource": ""
} |
q162798 | RequestCreator.prepareExtraArgs | train | 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;
} | java | {
"resource": ""
} |
q162799 | JmxRequestFactory.extractPathInfo | train | private static String extractPathInfo(String pPathInfo, ProcessingParameters pProcessingParams) {
String pathInfo = pPathInfo;
// If no pathinfo is given directly, we look for a query parameter named 'p'.
// This variant is helpful, if there are problems with the server mangling
// up the pathinfo (e.g. for security concerns, often '/','\',';' and other are not
// allowed in encoded form within the pathinfo)
if (pProcessingParams != null && (pPathInfo == null || pPathInfo.length() == 0 || pathInfo.matches("^/+$"))) {
pathInfo = pProcessingParams.getPathInfo();
}
return normalizePathInfo(pathInfo);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.