_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q162800
JmxRequestFactory.normalizePathInfo
train
private static String normalizePathInfo(String pPathInfo) { if (pPathInfo != null && pPathInfo.length() > 0) { return pPathInfo.startsWith("/") ? pPathInfo.substring(1) : pPathInfo; } else { return ""; } }
java
{ "resource": "" }
q162801
JmxRequestFactory.getCreator
train
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; }
java
{ "resource": "" }
q162802
MimeTypeUtil.isValidCallback
train
public static boolean isValidCallback(String pCallback) { Pattern validJavaScriptFunctionNamePattern = Pattern.compile("^[$A-Z_][0-9A-Z_$]*$", Pattern.CASE_INSENSITIVE); return validJavaScriptFunctionNamePattern.matcher(pCallback).matches(); }
java
{ "resource": "" }
q162803
RestrictorFactory.lookupPolicyRestrictor
train
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; }
java
{ "resource": "" }
q162804
DataUpdater.update
train
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"); } }
java
{ "resource": "" }
q162805
DataUpdater.verifyThatPathIsEmpty
train
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); } }
java
{ "resource": "" }
q162806
ClientCertAuthenticator.checkCertForClientUsage
train
private void checkCertForClientUsage(X509Certificate clientCert) { try { // We required that the extended key usage must be present if we are using // client cert authentication 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"); } }
java
{ "resource": "" }
q162807
DelegatingRestrictor.checkRestrictorService
train
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) { // Will not happen, since we dont use a filter here throw new IllegalArgumentException("Impossible exception (we don't use a filter for fetching the services)",e); } }
java
{ "resource": "" }
q162808
DebugStore.log
train
public void log(String pMessage, Throwable pThrowable) { add(System.currentTimeMillis() / 1000,pMessage,pThrowable); }
java
{ "resource": "" }
q162809
DebugStore.debugInfo
train
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(); }
java
{ "resource": "" }
q162810
DebugStore.add
train
private synchronized void add(long pTime,String message) { debugEntries.addFirst(new Entry(pTime,message)); trim(); }
java
{ "resource": "" }
q162811
Configuration.updateGlobalConfiguration
train
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)); } } }
java
{ "resource": "" }
q162812
Configuration.updateGlobalConfiguration
train
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); } } } }
java
{ "resource": "" }
q162813
Configuration.get
train
public String get(ConfigKey pKey) { String value = globalConfig.get(pKey); if (value == null) { value = pKey.getDefaultValue(); } return value; }
java
{ "resource": "" }
q162814
Configuration.getAsInt
train
public int getAsInt(ConfigKey pKey) { int ret; try { ret = Integer.parseInt(get(pKey)); } catch (NumberFormatException exp) { ret = Integer.parseInt(pKey.getDefaultValue()); } return ret; }
java
{ "resource": "" }
q162815
Configuration.getProcessingParameters
train
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)); }
java
{ "resource": "" }
q162816
CleanupThread.enumerateThreads
train
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; } } // Trim array Thread ret[] = new Thread[nrThreads]; System.arraycopy(threads,0,ret,0,nrThreads); return ret; }
java
{ "resource": "" }
q162817
CleanupThread.joinThreads
train
private boolean joinThreads(Thread pThreads[]) { for (int i=0;i< pThreads.length;i++) { final Thread t = pThreads[i]; if (t.isDaemon() || t.getThreadGroup() == null || // has died on us t.getThreadGroup().equals(threadGroup) || checkExcludedNames(t.getName())) { // These are threads which should not prevent the server from stopping. continue; } try { t.join(); } catch (Exception ex) { // Ignore that one. } finally { // We just joined a 'foreign' thread, so we redo the loop return true; } } // All 'foreign' threads has finished, hence we are prepared to stop return false; }
java
{ "resource": "" }
q162818
JolokiaActivator.getHttpContext
train
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; }
java
{ "resource": "" }
q162819
JolokiaActivator.getConfiguration
train
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; }
java
{ "resource": "" }
q162820
ObjectSerializationContext.push
train
void push(Object object) { callStack.push(object); if (object != null && !SIMPLE_TYPES.contains(object.getClass())) { objectsInCallStack.add(object); } objectCount++; }
java
{ "resource": "" }
q162821
ObjectSerializationContext.pop
train
Object pop() { Object ret = callStack.pop(); if (ret != null && !SIMPLE_TYPES.contains(ret.getClass())) { objectsInCallStack.remove(ret); } return ret; }
java
{ "resource": "" }
q162822
MBeanAccessChecker.extractMbeanConfiguration
train
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()); } }
java
{ "resource": "" }
q162823
MBeanAccessChecker.wildcardMatch
train
private boolean wildcardMatch(Set<String> pValues, String pValue) { for (String pattern : pValues) { if (pattern.contains("*") && pValue.matches(pattern.replaceAll("\\*",".*"))) { return true; } } return false; }
java
{ "resource": "" }
q162824
GlassfishDetector.extractVersionFromFullVersion
train
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; }
java
{ "resource": "" }
q162825
GlassfishDetector.bootAmx
train
private synchronized boolean bootAmx(MBeanServerExecutor pServers, final LogHandler pLoghandler) { ObjectName bootMBean = null; try { bootMBean = new ObjectName("amx-support:type=boot-amx"); } catch (MalformedObjectNameException e) { // Cannot happen .... } try { pServers.call(bootMBean, new MBeanServerExecutor.MBeanAction<Void>() { /** {@inheritDoc} */ 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); // Can happen, when a call to bootAmx comes to early before the bean // is registered return false; } catch (IllegalArgumentException e) { pLoghandler.error("Exception while booting AMX: " + e,e); // We dont try it again return true; } catch (Exception e) { pLoghandler.error("Exception while executing bootAmx: " + e, e); // dito return true; } }
java
{ "resource": "" }
q162826
SimplifierExtractor.addExtractor
train
protected final void addExtractor(String pName, AttributeExtractor<T> pExtractor) { extractorMap.put(pName,pExtractor); }
java
{ "resource": "" }
q162827
HistoryStore.setGlobalMaxEntries
train
public synchronized void setGlobalMaxEntries(int pGlobalMaxEntries) { globalMaxEntries = pGlobalMaxEntries; // Refresh all entries for (HistoryEntry entry : historyStore.values()) { entry.setMaxEntries(globalMaxEntries); } }
java
{ "resource": "" }
q162828
HistoryStore.configure
train
public synchronized void configure(HistoryKey pKey, HistoryLimit pHistoryLimit) { // Remove entries if set to null if (pHistoryLimit == null) { removeEntries(pKey); return; } HistoryLimit limit = pHistoryLimit.respectGlobalMaxEntries(globalMaxEntries); if (pKey.isMBeanPattern()) { patterns.put(pKey,limit); // Trim all already stored keys 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); } } }
java
{ "resource": "" }
q162829
HistoryStore.updateAndAdd
train
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); } }
java
{ "resource": "" }
q162830
HistoryStore.getSize
train
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); } }
java
{ "resource": "" }
q162831
HistoryStore.initHistoryUpdaters
train
private void initHistoryUpdaters() { historyUpdaters.put(RequestType.EXEC, new HistoryUpdater<JmxExecRequest>() { /** {@inheritDoc} */ 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>() { /** {@inheritDoc} */ 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>() { /** {@inheritDoc} */ public void updateHistory(JSONObject pJson,JmxReadRequest request, long pTimestamp) { updateReadHistory(request,pJson,pTimestamp); } }); }
java
{ "resource": "" }
q162832
HistoryStore.updateReadHistory
train
private void updateReadHistory(JmxReadRequest pJmxReq, JSONObject pJson, long pTimestamp) { ObjectName name = pJmxReq.getObjectName(); if (name.isPattern()) { // We have a pattern and hence a value structure // of bean -> attribute_key -> attribute_value Map<String,Object> values = (Map<String, Object>) pJson.get(KEY_VALUE); // Can be null if used with path and no single match occurred if (values != null) { JSONObject history = updateHistoryForPatternRead(pJmxReq, pTimestamp, values); if (history.size() > 0) { pJson.put(KEY_HISTORY,history); } } } else if (pJmxReq.isMultiAttributeMode() || !pJmxReq.hasAttribute()) { // Multiple attributes, but a single bean. // Value has the following structure: // attribute_key -> attribute_value JSONObject history = addMultipleAttributeValues( pJmxReq, ((Map<String, Object>) pJson.get(KEY_VALUE)), pJmxReq.getObjectNameAsString(), pTimestamp); if (history.size() > 0) { pJson.put(KEY_HISTORY,history); } } else { // Single attribute, single bean. Value is the attribute_value // itself. addAttributeFromSingleValue(pJson, new HistoryKey(pJmxReq), KEY_HISTORY, pJson.get(KEY_VALUE), pTimestamp); } }
java
{ "resource": "" }
q162833
HistoryStore.addAttributeFromSingleValue
train
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; }
java
{ "resource": "" }
q162834
J4pClient.extractResponses
train
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(); // Merge partial results and exceptions in a single list 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; }
java
{ "resource": "" }
q162835
J4pClient.mapException
train
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); } }
java
{ "resource": "" }
q162836
J4pClient.verifyBulkJsonResponse
train
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() + ")"); } }
java
{ "resource": "" }
q162837
BackendManager.handleRequest
train
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); // Update global history store, add timestamp and possibly history information to the request historyStore.updateAndAdd(pJmxReq,json); json.put("status",200 /* success */); } catch (NotChangedException exp) { // A handled indicates that its value hasn't changed. We return an status with //"304 Not Modified" similar to the HTTP status code (http://en.wikipedia.org/wiki/HTTP_status) 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; }
java
{ "resource": "" }
q162838
BackendManager.convertExceptionToJson
train
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) { // Cannot happen, since we dont use a path return null; } }
java
{ "resource": "" }
q162839
BackendManager.isRemoteAccessAllowed
train
public boolean isRemoteAccessAllowed(String pRemoteHost, String pRemoteAddr) { return restrictor.isRemoteAccessAllowed(pRemoteHost != null ? new String[] { pRemoteHost, pRemoteAddr } : new String[] { pRemoteAddr }); }
java
{ "resource": "" }
q162840
BackendManager.info
train
public void info(String msg) { logHandler.info(msg); if (debugStore != null) { debugStore.log(msg); } }
java
{ "resource": "" }
q162841
BackendManager.debug
train
public void debug(String msg) { logHandler.debug(msg); if (debugStore != null) { debugStore.log(msg); } }
java
{ "resource": "" }
q162842
BackendManager.init
train
private void init(Configuration pConfig) { // Central objects converters = new Converters(); initLimits(pConfig); // Create and remember request dispatchers localDispatcher = new LocalRequestDispatcher(converters, restrictor, pConfig, logHandler); ServerHandle serverHandle = localDispatcher.getServerHandle(); requestDispatchers = createRequestDispatchers(pConfig, converters,serverHandle,restrictor); requestDispatchers.add(localDispatcher); // Backendstore for remembering agent state initMBeans(pConfig); agentDetails.setServerInfo(serverHandle.getVendor(),serverHandle.getProduct(),serverHandle.getVersion()); }
java
{ "resource": "" }
q162843
BackendManager.createRequestDispatchers
train
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; }
java
{ "resource": "" }
q162844
BackendManager.createDispatcher
train
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) { // Try without configuration as fourth parameter 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); } }
java
{ "resource": "" }
q162845
BackendManager.callRequestDispatcher
train
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; }
java
{ "resource": "" }
q162846
BackendManager.initMBeans
train
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); } }
java
{ "resource": "" }
q162847
BackendManager.intError
train
private void intError(String message,Throwable t) { logHandler.error(message, t); debugStore.log(message, t); }
java
{ "resource": "" }
q162848
OptionsAndArgs.lookupJarFile
train
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); } }
java
{ "resource": "" }
q162849
OptionsAndArgs.getNextListIndexSuffix
train
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; } }
java
{ "resource": "" }
q162850
OptionsAndArgs.init
train
private void init(Set<String> pCommands, String ... pArgs) { quiet = options.containsKey("quiet"); verbose = options.containsKey("verbose"); jarFile = lookupJarFile(); // Special cases first extraArgs = checkCommandAndArgs(pCommands, pArgs); }
java
{ "resource": "" }
q162851
CommandDispatcher.dispatchCommand
train
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); }
java
{ "resource": "" }
q162852
MBeanServerExecutorLocal.handleRequest
train
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) { // Remember exceptions for later use objNotFoundException = exp; } catch (AttributeNotFoundException exp) { attrException = exp; } catch (IOException exp) { throw new IllegalStateException("I/O Error while dispatching",exp); } } if (attrException != null) { throw attrException; } // Must be there, otherwise we would not have left the loop throw objNotFoundException; }
java
{ "resource": "" }
q162853
JolokiaCipher.encrypt
train
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); }
java
{ "resource": "" }
q162854
ParsedUri.getParameter
train
public String getParameter(String name) { String[] values = parameters.get(name); if (values == null) { return null; } if (values.length == 0) { return ""; } return values[0]; }
java
{ "resource": "" }
q162855
ParsedUri.parseQuery
train
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('='); // for "name=", the value is "", for "name" alone, the value is null 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 { // That's not a very cheap algorithm to create new arrays on the fly, // but it is expected that there will be only a handful of array parameters // in an URL anyway. So, let us be dirty here ... 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); } }
java
{ "resource": "" }
q162856
AbstractBaseCommand.getProcessDescription
train
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) { // ignored } catch (NoSuchMethodException e) { // ignored } catch (IllegalAccessException e) { // ignored } return desc.toString(); } else { return "(null)"; } }
java
{ "resource": "" }
q162857
JolokiaServer.start
train
public void start() { // URL as configured takes precedence String configUrl = NetworkUtil.replaceExpression(config.getJolokiaConfig().get(ConfigKey.DISCOVERY_AGENT_URL)); jolokiaHttpHandler.start(lazy,configUrl != null ? configUrl : url, config.getAuthenticator() != null); if (httpServer != null) { // Starting our own server in an own thread group with a fixed name // so that the cleanup thread can recognize it. ThreadGroup threadGroup = new ThreadGroup("jolokia"); threadGroup.setDaemon(false); Thread starterThread = new Thread(threadGroup,new Runnable() { @Override public void run() { httpServer.start(); } }); starterThread.start(); cleaner = new CleanupThread(httpServer,threadGroup); cleaner.start(); } }
java
{ "resource": "" }
q162858
JolokiaServer.init
train
protected final void init(JolokiaServerConfig pConfig, boolean pLazy) throws IOException { // We manage it on our own httpServer = createHttpServer(pConfig); init(httpServer, pConfig, pLazy); }
java
{ "resource": "" }
q162859
JolokiaServer.createHttpServer
train
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()); // Thread factory which creates only daemon threads ThreadFactory daemonThreadFactory = new DaemonThreadFactory(pConfig.getThreadNamePrefix()); // Prepare executor pool 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; }
java
{ "resource": "" }
q162860
MBeanInfoData.addException
train
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()); }
java
{ "resource": "" }
q162861
MBeanInfoData.truncatePathStack
train
private Stack<String> truncatePathStack(int pLevel) { if (pathStack.size() < pLevel) { return new Stack<String>(); } else { // Trim of domain and MBean properties // pathStack gets cloned here since the processing will eat it up Stack<String> ret = (Stack<String>) pathStack.clone(); for (int i = 0;i < pLevel;i++) { ret.pop(); } return ret; } }
java
{ "resource": "" }
q162862
MBeanInfoData.navigatePath
train
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(); // End leaf, return it .... if (size == 1) { return value; } // Dive in deeper ... 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; }
java
{ "resource": "" }
q162863
EclipseMuleAgentHttpServer.getServer
train
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; }
java
{ "resource": "" }
q162864
AgentDetails.setServerInfo
train
public void setServerInfo(String pVendor, String pProduct, String pVersion) { checkSeal(); serverVendor = pVendor; serverProduct = pProduct; serverVersion = pVersion; }
java
{ "resource": "" }
q162865
AgentDetails.toJSONObject
train
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; }
java
{ "resource": "" }
q162866
MultiAuthenticator.authenticate
train
@Override 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 last result, which is either SUCCESS for mode.ALL or FAILURE for mode.ANY return result; }
java
{ "resource": "" }
q162867
J4pRequestHandler.getHttpRequest
train
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); // GET request 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 the request decides, that POST *must* be used 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)); } } // We are using a post method as fallback JSONObject requestContent = getJsonRequestContent(pRequest); HttpPost postReq = new HttpPost(createRequestURI(j4pServerUrl.getPath(),queryParams)); postReq.setEntity(new StringEntity(requestContent.toJSONString(),"utf-8")); return postReq; }
java
{ "resource": "" }
q162868
J4pRequestHandler.getHttpRequest
train
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; }
java
{ "resource": "" }
q162869
J4pRequestHandler.extractJsonResponse
train
@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); } } }
java
{ "resource": "" }
q162870
J4pRequestHandler.createRequestURI
train
private URI createRequestURI(String path,String queryParams) throws URISyntaxException { return new URI(j4pServerUrl.getScheme(), j4pServerUrl.getUserInfo(), j4pServerUrl.getHost(), j4pServerUrl.getPort(), path, queryParams,null); }
java
{ "resource": "" }
q162871
J4pRequestHandler.prepareQueryParameters
train
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; } }
java
{ "resource": "" }
q162872
JsonRequestHandler.checkHttpMethod
train
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"); } }
java
{ "resource": "" }
q162873
JsonRequestHandler.checkForModifiedSince
train
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); } }
java
{ "resource": "" }
q162874
MortbayMuleAgentHttpServer.getServer
train
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; }
java
{ "resource": "" }
q162875
WeblogicDetector.addMBeanServers
train
@Override public void addMBeanServers(Set<MBeanServerConnection> servers) { // Weblogic stores the MBeanServer in a JNDI context // Workaround for broken JBoss 4.2.3 which doesn't like JNDI lookups. See #123 for details. 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) { // expected and can happen on non-Weblogic platforms } } }
java
{ "resource": "" }
q162876
JolokiaMuleAgent.getDescription
train
@Override 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"; }
java
{ "resource": "" }
q162877
JolokiaMBeanServerUtil.getJolokiaMBeanServer
train
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) { // should be probably locked, but for simplicity reasons and because // the probability of a clash is fairly low (can happen only once), it's omitted // here. Note, that server.getAttribute() itself is threadsafe. jolokiaMBeanServer = registerJolokiaMBeanServerHolderMBean(server); } catch (JMException e) { throw new IllegalStateException("Internal: Cannot get JolokiaMBean server via JMX lookup: " + e,e); } return jolokiaMBeanServer; }
java
{ "resource": "" }
q162878
JolokiaMBeanServerUtil.registerJolokiaMBeanServerHolderMBean
train
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) { // If the instance already exist, we look it up and fetch the MBeanServerHolder from there. // Might happen in race conditions. 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; }
java
{ "resource": "" }
q162879
ExecHandler.verifyArguments
train
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"); } }
java
{ "resource": "" }
q162880
ExecHandler.extractOperationTypes
train
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) { // Empty signature requested 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 { // type requested from the operation 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); }
java
{ "resource": "" }
q162881
ExecHandler.extractMBeanParameterInfos
train
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); } }
java
{ "resource": "" }
q162882
ExecHandler.splitOperation
train
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) { // No escaping required since the parts a Java types which does not // allow for commas String[] args = m.group(2).split("\\s*,\\s*"); ret.addAll(Arrays.asList(args)); } else { // It's "()" which means a no-arg method ret.add(null); } } else { ret.add(pOperation); } return ret; }
java
{ "resource": "" }
q162883
AbstractImmutableSubstitutionImpl.composeWith
train
@Override 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 all variables in the domain of f */ for (Map.Entry<Variable, ? extends ImmutableTerm> gEntry : f.getImmutableMap().entrySet()) { substitutionMap.put(gEntry.getKey(), apply(gEntry.getValue())); } /** * For the other variables (in the local domain but not in f) */ 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() // Clean out entries like t/t .filter(entry -> !entry.getKey().equals(entry.getValue())) .collect(ImmutableCollectors.toMap())); }
java
{ "resource": "" }
q162884
AbstractImmutableSubstitutionImpl.computeUnionMap
train
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); /** * TODO: explain */ if (isDefining(otherVariable) && (!get(otherVariable).equals(otherTerm))) { return Optional.empty(); } mapBuilder.put(otherVariable, otherTerm); } return Optional.of(mapBuilder.build()); }
java
{ "resource": "" }
q162885
AbstractImmutableSubstitutionImpl.applyNullNormalization
train
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; }
java
{ "resource": "" }
q162886
MappingOntologyComplianceValidatorImpl.getPredicateIRI
train
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(); }
java
{ "resource": "" }
q162887
LocalJDBCConnectionUtils.createConnection
train
public static Connection createConnection(OntopSQLCredentialSettings settings) throws SQLException { try { // This should work in most cases (e.g. from CLI, Protege, or Jetty) return DriverManager.getConnection(settings.getJdbcUrl(), settings.getJdbcUser(), settings.getJdbcPassword()); } catch (SQLException ex) { // HACKY(xiao): This part is still necessary for Tomcat. // Otherwise, JDBC drivers are not initialized by default. 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()); } }
java
{ "resource": "" }
q162888
DatabaseRelationDefinition.addAttribute
train
public Attribute addAttribute(QuotedID id, int type, String typeName, boolean canNull) { Attribute att = new Attribute(this, new QualifiedAttributeID(getID(), id), attributes.size() + 1, type, typeName, canNull, typeMapper.getTermType(type, typeName)); //check for duplicate names (put returns the previous value) Attribute prev = attributeMap.put(id, att); if (prev != null) throw new IllegalArgumentException("Duplicate attribute names"); attributes.add(att); return att; }
java
{ "resource": "" }
q162889
DatabaseRelationDefinition.getAttribute
train
@Override public Attribute getAttribute(int index) { Attribute attribute = attributes.get(index - 1); return attribute; }
java
{ "resource": "" }
q162890
IndempotentVar2VarSubstitutionImpl.isIndempotent
train
public static boolean isIndempotent(Map<Variable, Variable> substitutionMap) { if (substitutionMap.isEmpty()) return true; Set<Variable> valueSet = new HashSet<>(substitutionMap.values()); valueSet.retainAll(substitutionMap.entrySet()); return valueSet.isEmpty(); }
java
{ "resource": "" }
q162891
SparqlAlgebraToDatalogTranslator.translate
train
public InternalSparqlQuery translate(ParsedQuery pq) throws OntopUnsupportedInputQueryException, OntopInvalidInputQueryException { if (predicateIdx != 0 || !program.getRules().isEmpty()) throw new IllegalStateException("SparqlAlgebraToDatalogTranslator.translate can only be called once."); TupleExpr te = pq.getTupleExpr(); log.debug("SPARQL algebra: \n{}", te); //System.out.println("SPARQL algebra: \n" + te); TranslationResult body = translate(te); List<Variable> answerVariables; if (pq instanceof ParsedTupleQuery || pq instanceof ParsedGraphQuery) { // order elements of the set in some way by converting it into the list answerVariables = new ArrayList<>(body.variables); } else { // ASK queries have no answer variables answerVariables = Collections.emptyList(); } AtomPredicate pred = atomFactory.getRDFAnswerPredicate(answerVariables.size()); Function head = termFactory.getFunction(pred, (List<Term>)(List<?>)answerVariables); appendRule(head, body.atoms); //System.out.println("PROGRAM\n" + program.program); return new InternalSparqlQuery(program, ImmutableList.copyOf(answerVariables)); }
java
{ "resource": "" }
q162892
QueryGroupTreeElement.removeQuery
train
public QueryTreeElement removeQuery(String query_id) { for (QueryTreeElement query : queries) { if (query.getID().equals(query_id)) { queries.remove(query); return query; } } return null; }
java
{ "resource": "" }
q162893
QueryGroupTreeElement.getQuery
train
public QueryTreeElement getQuery(String id) { for (QueryTreeElement query : queries) { if (query.getID().equals(id)) { return query; } } return null; }
java
{ "resource": "" }
q162894
DefaultTree.getParentTreeNode
train
private TreeNode getParentTreeNode(TreeNode child) { TreeNode parentTreeNode = parentIndex.get(child); if (parentTreeNode == null) return null; // Makes sure the parent node is still present in the tree else if (contains(parentTreeNode.getQueryNode())) return parentTreeNode; else throw new RuntimeException("Internal error: points to a parent that is not (anymore) in the tree"); }
java
{ "resource": "" }
q162895
AbstractOntopQuery.getQueryString
train
protected String getQueryString() { if (bindings.size() == 0) return queryString; String qry = queryString; int b = qry.indexOf('{'); String select = qry.substring(0, b); String where = qry.substring(b); for (String name : bindings.getBindingNames()) { String replacement = getReplacement(bindings.getValue(name)); if (replacement != null) { String pattern = "[\\?\\$]" + name + "(?=\\W)"; select = select.replaceAll(pattern, ""); where = where.replaceAll(pattern, replacement); } } return select + where; }
java
{ "resource": "" }
q162896
OneShotSQLGeneratorEngine.getBooleanConditions
train
private Set<String> getBooleanConditions(List<Function> atoms, AliasIndex index) { Set<String> conditions = new LinkedHashSet<>(); for (Function atom : atoms) { if (atom.isOperation()) { // Boolean expression if (atom.getFunctionSymbol() == ExpressionOperation.AND) { // flatten ANDs for (Term t : atom.getTerms()) { Set<String> arg = getBooleanConditions(ImmutableList.of((Function)t), index); conditions.addAll(arg); } } else { String condition = getSQLCondition(atom, index); conditions.add(condition); } } else if (atom.isDataTypeFunction()) { String condition = getSQLString(atom, index, false); conditions.add(condition); } } return conditions; }
java
{ "resource": "" }
q162897
OneShotSQLGeneratorEngine.getTableDefinitions
train
private String getTableDefinitions(List<Function> atoms, AliasIndex index, String JOIN_KEYWORD, boolean parenthesis, String indent) { List<String> tables = getTableDefs(atoms, index, INDENT + indent); switch (tables.size()) { case 0: throw new RuntimeException("Cannot generate definition for empty data"); case 1: return tables.get(0); default: String JOIN = "%s\n" + indent + JOIN_KEYWORD + "\n" + INDENT + indent + "%s"; /* * Now we generate the table definition: Join/LeftJoin * (possibly nested if there are more than 2 table definitions in the * current list) in case this method was called recursively. * * To form the JOIN we will cycle through each data definition, * nesting the JOINs as we go. The conditions in the ON clause will * go on the TOP level only. */ int size = tables.size(); String currentJoin = tables.get(size - 1); currentJoin = String.format(JOIN, tables.get(size - 2), parenthesis ? inBrackets(currentJoin) : currentJoin); for (int i = size - 3; i >= 0; i--) { currentJoin = String.format(JOIN, tables.get(i), inBrackets(currentJoin)); } Set<String> on = getConditionsSet(atoms, index, true); if (on.isEmpty()) return currentJoin; StringBuilder sb = new StringBuilder(); sb.append(currentJoin).append("\n").append(indent).append("ON "); Joiner.on(" AND\n" + indent).appendTo(sb, on); return sb.toString(); } }
java
{ "resource": "" }
q162898
OneShotSQLGeneratorEngine.getTableDefinition
train
private String getTableDefinition(Function atom, AliasIndex index, String indent) { if (atom.isAlgebraFunction()) { Predicate functionSymbol = atom.getFunctionSymbol(); ImmutableList<Function> joinAtoms = convert(atom.getTerms()); if (functionSymbol.equals(datalogFactory.getSparqlJoinPredicate())) { // nested joins we need to add parenthesis later boolean parenthesis = joinAtoms.get(0).isAlgebraFunction() || joinAtoms.get(1).isAlgebraFunction(); return getTableDefinitions(joinAtoms, index, "JOIN", parenthesis, indent + INDENT); } else if (functionSymbol.equals(datalogFactory.getSparqlLeftJoinPredicate())) { // in case of left join we want to add the parenthesis only for the right tables // we ignore nested joins from the left tables boolean parenthesis = joinAtoms.get(1).isAlgebraFunction(); return getTableDefinitions(joinAtoms, index, "LEFT OUTER JOIN", parenthesis, indent + INDENT); } } else if (!atom.isOperation() && !atom.isDataTypeFunction()) { return index.getViewDefinition(atom); // a database atom } return null; }
java
{ "resource": "" }
q162899
OneShotSQLGeneratorEngine.getDataType
train
private int getDataType(Term term) { /* * TODO: refactor! */ if (term instanceof Function){ Function f = (Function) term; Predicate p = f.getFunctionSymbol(); if (p instanceof DatatypePredicate) { RDFDatatype type = ((DatatypePredicate) p).getReturnedType(); return jdbcTypeMapper.getSQLType(type); } // return varchar for unknown return Types.VARCHAR; } else if (term instanceof Variable) { throw new RuntimeException("Cannot return the SQL type for: " + term); } /* * Boolean constant */ else if (term.equals(termFactory.getBooleanConstant(false)) || term.equals(termFactory.getBooleanConstant(true))) { return Types.BOOLEAN; } return Types.VARCHAR; }
java
{ "resource": "" }