_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q162600
SingularityClient.browseTaskSandBox
train
public Optional<SingularitySandbox> browseTaskSandBox(String taskId, String path) { final Function<String, String> requestUrl = (host) -> String.format(SANDBOX_BROWSE_FORMAT, getApiBase(host), taskId); return getSingleWithParams(requestUrl, "browse sandbox for task", taskId, Optional.of(ImmutableMap.of("path", path)), SingularitySandbox.class); }
java
{ "resource": "" }
q162601
SingularityClient.readSandBoxFile
train
public Optional<MesosFileChunkObject> readSandBoxFile(String taskId, String path, Optional<String> grep, Optional<Long> offset, Optional<Long> length) { final Function<String, String> requestUrl = (host) -> String.format(SANDBOX_READ_FILE_FORMAT, getApiBase(host), taskId); Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("path", path); if (grep.isPresent()) { queryParamBuider.put("grep", grep.get()); } if (offset.isPresent()) { queryParamBuider.put("offset", offset.get()); } if (length.isPresent()) { queryParamBuider.put("length", length.get()); } return getSingleWithParams(requestUrl, "Read sandbox file for task", taskId, Optional.of(queryParamBuider.build()), MesosFileChunkObject.class); }
java
{ "resource": "" }
q162602
SingularityClient.getTaskLogs
train
public Collection<SingularityS3Log> getTaskLogs(String taskId) { final Function<String, String> requestUri = (host) -> String.format(S3_LOG_GET_TASK_LOGS, getApiBase(host), taskId); final String type = String.format("S3 logs for task %s", taskId); return getCollection(requestUri, type, S3_LOG_COLLECTION); }
java
{ "resource": "" }
q162603
SingularityClient.getRequestLogs
train
public Collection<SingularityS3Log> getRequestLogs(String requestId) { final Function<String, String> requestUri = (host) -> String.format(S3_LOG_GET_REQUEST_LOGS, getApiBase(host), requestId); final String type = String.format("S3 logs for request %s", requestId); return getCollection(requestUri, type, S3_LOG_COLLECTION); }
java
{ "resource": "" }
q162604
SingularityClient.getDeployLogs
train
public Collection<SingularityS3Log> getDeployLogs(String requestId, String deployId) { final Function<String, String> requestUri = (host) -> String.format(S3_LOG_GET_DEPLOY_LOGS, getApiBase(host), requestId, deployId); final String type = String.format("S3 logs for deploy %s of request %s", deployId, requestId); return getCollection(requestUri, type, S3_LOG_COLLECTION); }
java
{ "resource": "" }
q162605
SingularityClient.getRequestGroups
train
public Collection<SingularityRequestGroup> getRequestGroups() { final Function<String, String> requestUri = (host) -> String.format(REQUEST_GROUPS_FORMAT, getApiBase(host)); return getCollection(requestUri, "request groups", REQUEST_GROUP_COLLECTION); }
java
{ "resource": "" }
q162606
SingularityClient.getRequestGroup
train
public Optional<SingularityRequestGroup> getRequestGroup(String requestGroupId) { final Function<String, String> requestUri = (host) -> String.format(REQUEST_GROUP_FORMAT, getApiBase(host), requestGroupId); return getSingle(requestUri, "request group", requestGroupId, SingularityRequestGroup.class); }
java
{ "resource": "" }
q162607
SingularityClient.isUserAuthorized
train
public boolean isUserAuthorized(String requestId, String userId, SingularityAuthorizationScope scope) { final Function<String, String> requestUri = (host) -> String.format(AUTH_CHECK_USER_FORMAT, getApiBase(host), requestId, userId); Map<String, Object> params = Collections.singletonMap("scope", scope.name()); HttpResponse response = executeGetSingleWithParams(requestUri, "auth check", "", Optional.of(params)); return response.isSuccess(); }
java
{ "resource": "" }
q162608
SingularityClient.getTaskState
train
public Optional<SingularityTaskState> getTaskState(String requestId, String runId) { final Function<String, String> requestUri = (host) -> String.format(TRACK_BY_RUN_ID_FORMAT, getApiBase(host), requestId, runId); return getSingle(requestUri, "track by task id", String.format("%s-%s", requestId, runId), SingularityTaskState.class); }
java
{ "resource": "" }
q162609
SingularityMesosTaskBuilder.prepareCommand
train
private void prepareCommand(final TaskInfo.Builder bldr, final SingularityTaskId taskId, final SingularityTaskRequest task, final SingularityOfferHolder offerHolder, final Optional<long[]> ports) { CommandInfo.Builder commandBldr = CommandInfo.newBuilder(); Optional<String> specifiedUser = task.getPendingTask().getRunAsUserOverride().or(task.getDeploy().getUser()); if (specifiedUser.isPresent()) { commandBldr.setUser(specifiedUser.get()); } if (task.getDeploy().getCommand().isPresent()) { commandBldr.setValue(task.getDeploy().getCommand().get()); } if (task.getDeploy().getArguments().isPresent()) { commandBldr.addAllArguments(task.getDeploy().getArguments().get()); } if (task.getPendingTask().getCmdLineArgsList().isPresent()) { commandBldr.addAllArguments(task.getPendingTask().getCmdLineArgsList().get()); } if (task.getDeploy().getShell().isPresent()){ commandBldr.setShell(task.getDeploy().getShell().get()); } else if ((task.getDeploy().getArguments().isPresent() && !task.getDeploy().getArguments().get().isEmpty()) || // Hopefully temporary workaround for // http://www.mail-archive.com/user@mesos.apache.org/msg01449.html task.getDeploy().getContainerInfo().isPresent() || (task.getPendingTask().getCmdLineArgsList().isPresent() && !task.getPendingTask().getCmdLineArgsList().get().isEmpty())) { commandBldr.setShell(false); } List<SingularityMesosArtifact> combinedArtifacts = new ArrayList<>(); combinedArtifacts.addAll(task.getDeploy().getUris().or(Collections.emptyList())); combinedArtifacts.addAll(task.getPendingTask().getExtraArtifacts()); prepareMesosUriDownloads(combinedArtifacts, commandBldr); prepareEnvironment(task, taskId, commandBldr, offerHolder, ports); bldr.setCommand(commandBldr); }
java
{ "resource": "" }
q162610
AsyncSemaphore.newBuilder
train
public static AsyncSemaphoreBuilder newBuilder(Supplier<Integer> concurrentRequestLimit, ScheduledExecutorService flushingExecutor) { return new AsyncSemaphoreBuilder(new PermitSource(concurrentRequestLimit), flushingExecutor); }
java
{ "resource": "" }
q162611
AsyncSemaphore.tryEnqueueAttempt
train
private boolean tryEnqueueAttempt(DelayedExecution<T> delayedExecution) { int rejectionThreshold = queueRejectionThreshold.get(); if (rejectionThreshold < 0) { return requestQueue.offer(delayedExecution); } long stamp = stampedLock.readLock(); try { while (requestQueue.size() < rejectionThreshold) { long writeStamp = stampedLock.tryConvertToWriteLock(stamp); if (writeStamp != 0L) { stamp = writeStamp; return requestQueue.offer(delayedExecution); } else { stampedLock.unlock(stamp); stamp = stampedLock.writeLock(); } } return false; } finally { stampedLock.unlock(stamp); } }
java
{ "resource": "" }
q162612
AuthTokenManager.validateToken
train
private static boolean validateToken(String originalToken, String storedToken) throws NoSuchAlgorithmException, InvalidKeySpecException { String[] parts = storedToken.split(":"); int iterations = Integer.parseInt(parts[0]); byte[] salt = fromHex(parts[1]); byte[] hash = fromHex(parts[2]); PBEKeySpec spec = new PBEKeySpec(originalToken.toCharArray(), salt, iterations, hash.length * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] testHash = skf.generateSecret(spec).getEncoded(); int diff = hash.length ^ testHash.length; for (int i = 0; i < hash.length && i < testHash.length; i++) { diff |= hash[i] ^ testHash[i]; } return diff == 0; }
java
{ "resource": "" }
q162613
SingularityExecutor.registered
train
@Override public void registered(ExecutorDriver executorDriver, Protos.ExecutorInfo executorInfo, Protos.FrameworkInfo frameworkInfo, Protos.SlaveInfo slaveInfo) { LOG.debug("Registered {} with Mesos slave {} for framework {}", executorInfo.getExecutorId().getValue(), slaveInfo.getId().getValue(), frameworkInfo.getId().getValue()); LOG.trace("Registered {} with Mesos slave {} for framework {}", MesosUtils.formatForLogging(executorInfo), MesosUtils.formatForLogging(slaveInfo), MesosUtils.formatForLogging(frameworkInfo)); }
java
{ "resource": "" }
q162614
SingularityExecutor.reregistered
train
@Override public void reregistered(ExecutorDriver executorDriver, Protos.SlaveInfo slaveInfo) { LOG.debug("Re-registered with Mesos slave {}", slaveInfo.getId().getValue()); LOG.info("Re-registered with Mesos slave {}", MesosUtils.formatForLogging(slaveInfo)); }
java
{ "resource": "" }
q162615
SingularityMesosSchedulerClient.subscribe
train
public void subscribe(URI mesosMasterURI, SingularityMesosScheduler scheduler) throws URISyntaxException { FrameworkInfo frameworkInfo = buildFrameworkInfo(); if (mesosMasterURI == null || mesosMasterURI.getScheme().contains("zk")) { throw new IllegalArgumentException(String.format("Must use master address for http api (e.g. http://localhost:5050/api/v1/scheduler) was %s", mesosMasterURI)); } if (openStream == null || openStream.isUnsubscribed()) { // Do we get here ever? if (subscriberThread != null) { subscriberThread.interrupt(); } subscriberThread = new Thread() { public void run() { try { connect(mesosMasterURI, frameworkInfo, scheduler); } catch (RuntimeException|URISyntaxException e) { LOG.error("Could not connect: ", e); scheduler.onConnectException(e); } } }; subscriberThread.start(); } }
java
{ "resource": "" }
q162616
SingularityMesosSchedulerClient.acknowledge
train
public void acknowledge(AgentID agentId, TaskID taskId, ByteString uuid) { Builder acknowledge = build() .setAcknowledge(Acknowledge.newBuilder().setAgentId(agentId).setTaskId(taskId).setUuid(uuid)); sendCall(acknowledge, Type.ACKNOWLEDGE); }
java
{ "resource": "" }
q162617
SingularityMesosSchedulerClient.reconcile
train
public void reconcile(List<Reconcile.Task> tasks) { Builder reconsile = build().setReconcile(Reconcile.newBuilder().addAllTasks(tasks)); sendCall(reconsile, Type.RECONCILE); }
java
{ "resource": "" }
q162618
SingularityMesosSchedulerClient.frameworkMessage
train
public void frameworkMessage(ExecutorID executorId, AgentID agentId, byte[] data) { Builder message = build() .setMessage(Message.newBuilder().setAgentId(agentId).setExecutorId(executorId).setData(ByteString.copyFrom(data))); sendCall(message, Type.MESSAGE); }
java
{ "resource": "" }
q162619
CompletableFutures.timeoutFuture
train
public static CompletableFuture<Timeout> timeoutFuture(HashedWheelTimer hwt, long delay, TimeUnit timeUnit) { try { CompletableFuture<Timeout> future = new CompletableFuture<>(); hwt.newTimeout(future::complete, delay, timeUnit); return future; } catch (Throwable t) { return exceptionalFuture(t); } }
java
{ "resource": "" }
q162620
S3LogResource.getS3PrefixesForTask
train
private Collection<String> getS3PrefixesForTask(S3Configuration s3Configuration, SingularityTaskId taskId, Optional<Long> startArg, Optional<Long> endArg, String group, SingularityUser user) { Optional<SingularityTaskHistory> history = getTaskHistory(taskId, user); long start = taskId.getStartedAt(); if (startArg.isPresent()) { start = Math.max(startArg.get(), start); } long end = start + s3Configuration.getMissingTaskDefaultS3SearchPeriodMillis(); if (history.isPresent()) { SimplifiedTaskState taskState = SingularityTaskHistoryUpdate.getCurrentState(history.get().getTaskUpdates()); if (taskState == SimplifiedTaskState.DONE) { end = Iterables.getLast(history.get().getTaskUpdates()).getTimestamp(); } else { end = System.currentTimeMillis(); } } if (endArg.isPresent()) { end = Math.min(endArg.get(), end); } Optional<String> tag = Optional.absent(); if (history.isPresent() && history.get().getTask().getTaskRequest().getDeploy().getExecutorData().isPresent()) { tag = history.get().getTask().getTaskRequest().getDeploy().getExecutorData().get().getLoggingTag(); } Collection<String> prefixes = SingularityS3FormatHelper.getS3KeyPrefixes(s3Configuration.getS3KeyFormat(), taskId, tag, start, end, group); for (SingularityS3UploaderFile additionalFile : s3Configuration.getS3UploaderAdditionalFiles()) { if (additionalFile.getS3UploaderKeyPattern().isPresent() && !additionalFile.getS3UploaderKeyPattern().get().equals(s3Configuration.getS3KeyFormat())) { prefixes.addAll(SingularityS3FormatHelper.getS3KeyPrefixes(additionalFile.getS3UploaderKeyPattern().get(), taskId, tag, start, end, group)); } } LOG.trace("Task {} got S3 prefixes {} for start {}, end {}, tag {}", taskId, prefixes, start, end, tag); return prefixes; }
java
{ "resource": "" }
q162621
S3LogResource.getRequestGroupForTask
train
private Optional<String> getRequestGroupForTask(final SingularityTaskId taskId, SingularityUser user) { Optional<SingularityTaskHistory> maybeTaskHistory = getTaskHistory(taskId, user); if (maybeTaskHistory.isPresent()) { SingularityRequest request = maybeTaskHistory.get().getTask().getTaskRequest().getRequest(); authorizationHelper.checkForAuthorization(request, user, SingularityAuthorizationScope.READ); return request.getGroup(); } else { return getRequestGroup(taskId.getRequestId(), user); } }
java
{ "resource": "" }
q162622
WebhookManager.saveTaskUpdateForRetry
train
public void saveTaskUpdateForRetry(SingularityTaskHistoryUpdate taskHistoryUpdate) { String parentPath = ZKPaths.makePath(SNS_TASK_RETRY_ROOT, taskHistoryUpdate.getTaskId().getRequestId()); if (!isChildNodeCountSafe(parentPath)) { LOG.warn("Too many queued webhooks for path {}, dropping", parentPath); return; } String updatePath = ZKPaths.makePath(SNS_TASK_RETRY_ROOT, taskHistoryUpdate.getTaskId().getRequestId(), getTaskHistoryUpdateId(taskHistoryUpdate)); save(updatePath, taskHistoryUpdate, taskHistoryUpdateTranscoder); }
java
{ "resource": "" }
q162623
MailTemplateHelpers.getMaybeTaskLogReadOffset
train
private Optional<Long> getMaybeTaskLogReadOffset(final String slaveHostname, final String fullPath, final Long logLength, Optional<SingularityTask> task) { long offset = 0; long maxOffset = smtpConfiguration.get().getMaxTaskLogSearchOffset(); Optional<Pattern> maybePattern = getLogErrorRegex(task); Pattern pattern; if (maybePattern.isPresent()) { pattern = maybePattern.get(); } else { LOG.trace("Could not get regex pattern. Reading from bottom of file instead."); return getMaybeTaskLogEndOfFileOffset(slaveHostname, fullPath, logLength); } long length = logLength + pattern.toString().length(); // Get extra so that we can be sure to find the error Optional<MesosFileChunkObject> logChunkObject; Optional<MesosFileChunkObject> previous = Optional.absent(); while (offset <= maxOffset) { try { logChunkObject = sandboxManager.read(slaveHostname, fullPath, Optional.of(offset), Optional.of(length)); } catch (RuntimeException e) { LOG.error("Sandboxmanager failed to read {} on slave {}", fullPath, slaveHostname, e); return Optional.absent(); } if (logChunkObject.isPresent()) { if (logChunkObject.get().getData().equals("")) { // Passed end of file if (previous.isPresent()) { // If there was any log, get the bottom bytes of it long end = previous.get().getOffset() + previous.get().getData().length(); return Optional.of(end - logLength); } return Optional.absent(); } Matcher matcher = pattern.matcher(logChunkObject.get().getData()); if (matcher.find()) { return Optional.of(offset + matcher.start()); } else { offset += logLength; } } else { // Couldn't read anything LOG.error("Failed to read log file {}", fullPath); return Optional.absent(); } previous = logChunkObject; } LOG.trace("Searched through the first {} bytes of file {} and didn't find an error. Tailing bottom of file instead", maxOffset, fullPath); return getMaybeTaskLogEndOfFileOffset(slaveHostname, fullPath, logLength); }
java
{ "resource": "" }
q162624
MBeanServerHandler.createMBeanPluginContext
train
private MBeanPluginContext createMBeanPluginContext() { return new MBeanPluginContext() { public ObjectName registerMBean(Object pMBean, String... pOptionalName) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException { return MBeanServerHandler.this.registerMBean(pMBean, pOptionalName); } public void each(ObjectName pObjectName, MBeanEachCallback pCallback) throws IOException, ReflectionException, MBeanException { mBeanServerManager.each(pObjectName,pCallback); } public <R> R call(ObjectName pObjectName, MBeanAction<R> pMBeanAction, Object... pExtraArgs) throws IOException, ReflectionException, MBeanException, AttributeNotFoundException, InstanceNotFoundException { return mBeanServerManager.call(pObjectName,pMBeanAction,pExtraArgs); } public Set<ObjectName> queryNames(ObjectName pObjectName) throws IOException { return mBeanServerManager.queryNames(pObjectName); } public boolean hasMBeansListChangedSince(long pTimestamp) { return mBeanServerManager.hasMBeansListChangedSince(pTimestamp); } }; }
java
{ "resource": "" }
q162625
MBeanServerHandler.initServerHandle
train
private void initServerHandle(Configuration pConfig, LogHandler pLogHandler, List<ServerDetector> pDetectors) { serverHandle = detectServers(pDetectors, pLogHandler); if (serverHandle != null) { serverHandle.postDetect(mBeanServerManager, pConfig, pLogHandler); } }
java
{ "resource": "" }
q162626
MBeanServerHandler.dispatchRequest
train
public Object dispatchRequest(JsonRequestHandler pRequestHandler, JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, NotChangedException { serverHandle.preDispatch(mBeanServerManager,pJmxReq); if (pRequestHandler.handleAllServersAtOnce(pJmxReq)) { try { return pRequestHandler.handleRequest(mBeanServerManager,pJmxReq); } catch (IOException e) { throw new IllegalStateException("Internal: IOException " + e + ". Shouldn't happen.",e); } } else { return mBeanServerManager.handleRequest(pRequestHandler, pJmxReq); } }
java
{ "resource": "" }
q162627
MBeanServerHandler.registerMBean
train
public final ObjectName registerMBean(Object pMBean,String ... pOptionalName) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException { synchronized (mBeanHandles) { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { String name = pOptionalName != null && pOptionalName.length > 0 ? pOptionalName[0] : null; ObjectName registeredName = serverHandle.registerMBeanAtServer(server, pMBean, name); mBeanHandles.add(new MBeanHandle(server,registeredName)); return registeredName; } catch (RuntimeException exp) { throw new IllegalStateException("Could not register " + pMBean + ": " + exp, exp); } catch (MBeanRegistrationException exp) { throw new IllegalStateException("Could not register " + pMBean + ": " + exp, exp); } } }
java
{ "resource": "" }
q162628
MBeanServerHandler.destroy
train
public final void destroy() throws JMException { synchronized (mBeanHandles) { List<JMException> exceptions = new ArrayList<JMException>(); List<MBeanHandle> unregistered = new ArrayList<MBeanHandle>(); for (MBeanHandle handle : mBeanHandles) { try { unregistered.add(handle); handle.server.unregisterMBean(handle.objectName); } catch (InstanceNotFoundException e) { exceptions.add(e); } catch (MBeanRegistrationException e) { exceptions.add(e); } } // Remove all successfully unregistered handles mBeanHandles.removeAll(unregistered); // Throw error if any exception occured during unregistration if (exceptions.size() == 1) { throw exceptions.get(0); } else if (exceptions.size() > 1) { StringBuilder ret = new StringBuilder(); for (JMException e : exceptions) { ret.append(e.getMessage()).append(", "); } throw new JMException(ret.substring(0, ret.length() - 2)); } } // Unregister any notification listener mBeanServerManager.destroy(); }
java
{ "resource": "" }
q162629
MBeanServerHandler.initMBean
train
private void initMBean() { try { registerMBean(this,getObjectName()); } catch (InstanceAlreadyExistsException exp) { // This is no problem, since this MBeanServerHandlerMBean holds only global information // with no special state (so all instances of this MBean behave similar) // This exception can happen, when multiple servlets get registered within the same JVM } catch (MalformedObjectNameException e) { // Cannot happen, otherwise this is a bug. We should be always provide our own name in correct // form. throw new IllegalStateException("Internal Error: Own ObjectName " + getObjectName() + " is malformed",e); } catch (NotCompliantMBeanException e) { // Same here throw new IllegalStateException("Internal Error: " + this.getClass().getName() + " is not a compliant MBean",e); } }
java
{ "resource": "" }
q162630
MBeanServerHandler.lookupDetectors
train
public static List<ServerDetector> lookupDetectors() { List<ServerDetector> detectors = ServiceObjectFactory.createServiceObjects("META-INF/detectors-default", "META-INF/detectors"); // An detector at the end of the chain in order to get a default handle detectors.add(new FallbackServerDetector()); return detectors; }
java
{ "resource": "" }
q162631
MBeanServerHandler.detectServers
train
private ServerHandle detectServers(List<ServerDetector> pDetectors, LogHandler pLogHandler) { // Now detect the server for (ServerDetector detector : pDetectors) { try { ServerHandle info = detector.detect(mBeanServerManager); if (info != null) { return info; } } catch (Exception exp) { // We are defensive here and wont stop the servlet because // there is a problem with the server detection. A error will be logged // nevertheless, though. pLogHandler.error("Error while using detector " + detector.getClass().getSimpleName() + ": " + exp,exp); } } return null; }
java
{ "resource": "" }
q162632
TabularDataExtractor.hasComplexKeys
train
private boolean hasComplexKeys(TabularType pType) { List<String> indexes = pType.getIndexNames(); CompositeType rowType = pType.getRowType(); for (String index : indexes) { if ( ! (rowType.getType(index) instanceof SimpleType)) { return true; } } return false; }
java
{ "resource": "" }
q162633
TabularDataExtractor.convertTabularDataDirectly
train
private Object convertTabularDataDirectly(TabularData pTd, Stack<String> pExtraArgs, ObjectToJsonConverter pConverter) throws AttributeNotFoundException { if (!pExtraArgs.empty()) { throw new IllegalArgumentException("Cannot use a path for converting tabular data with complex keys (" + pTd.getTabularType().getRowType() + ")"); } JSONObject ret = new JSONObject(); JSONArray indexNames = new JSONArray(); TabularType type = pTd.getTabularType(); for (String index : type.getIndexNames()) { indexNames.add(index); } ret.put("indexNames",indexNames); JSONArray values = new JSONArray(); // Here no special handling for wildcard pathes since pathes are not supported for this use case (yet) for (CompositeData cd : (Collection<CompositeData>) pTd.values()) { values.add(pConverter.extractObject(cd, pExtraArgs, true)); } ret.put("values",values); return ret; }
java
{ "resource": "" }
q162634
MBeanPolicyConfig.findMatchingMBeanPattern
train
ObjectName findMatchingMBeanPattern(ObjectName pName) { // Check all stored patterns for a match and return the pattern if one is found for (ObjectName pattern : patterns) { if (pattern.apply(pName)) { return pattern; } } return null; }
java
{ "resource": "" }
q162635
ToolsClassFinder.createClassLoader
train
private static ClassLoader createClassLoader(File toolsJar) throws MalformedURLException { final URL urls[] = new URL[] {toolsJar.toURI().toURL() }; if (System.getSecurityManager() == null) { return new URLClassLoader(urls, getParentClassLoader()); } else { return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { /** {@inheritDoc} */ public ClassLoader run() { return new URLClassLoader(urls, getParentClassLoader()); } }); } }
java
{ "resource": "" }
q162636
BaseAuthenticator.authenticate
train
public boolean authenticate(HttpServletRequest pRequest) { String auth = pRequest.getHeader("Authorization"); if (auth == null) { return false; } AuthorizationHeaderParser.Result authInfo = AuthorizationHeaderParser.parse(auth); return authInfo.isValid() && doAuthenticate(pRequest, authInfo); }
java
{ "resource": "" }
q162637
AuthorizationHeaderParser.parse
train
public static Result parse(String pAuthInfo) { StringTokenizer stok = new StringTokenizer(pAuthInfo); String method = stok.nextToken(); if (!HttpServletRequest.BASIC_AUTH.equalsIgnoreCase(method)) { throw new IllegalArgumentException("Only BasicAuthentication is supported"); } String b64Auth = stok.nextToken(); String auth = new String(Base64Util.decode(b64Auth)); int p = auth.indexOf(':'); String user; String password; boolean valid; if (p != -1) { user = auth.substring(0, p); password = auth.substring(p+1); valid = true; } else { valid = false; user = null; password = null; } return new Result(method,user,password,valid); }
java
{ "resource": "" }
q162638
ReadHandler.doHandleRequest
train
@Override public Object doHandleRequest(MBeanServerConnection pServer, JmxReadRequest pRequest) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException { checkRestriction(pRequest.getObjectName(), pRequest.getAttributeName()); return pServer.getAttribute(pRequest.getObjectName(), pRequest.getAttributeName()); }
java
{ "resource": "" }
q162639
ReadHandler.filterAttributeNames
train
private List<String> filterAttributeNames(MBeanServerExecutor pSeverManager,ObjectName pName, List<String> pNames) throws IOException, ReflectionException, MBeanException, AttributeNotFoundException, InstanceNotFoundException { Set<String> attrs = new HashSet<String>(getAllAttributesNames(pSeverManager,pName)); List<String> ret = new ArrayList<String>(); for (String name : pNames) { if (attrs.contains(name)) { ret.add(name); } } return ret; }
java
{ "resource": "" }
q162640
ReadHandler.resolveAttributes
train
private List<String> resolveAttributes(MBeanServerExecutor pServers, ObjectName pMBeanName, List<String> pAttributeNames) throws IOException, ReflectionException, MBeanException, AttributeNotFoundException, InstanceNotFoundException { List<String> attributes = pAttributeNames; if (shouldAllAttributesBeFetched(pAttributeNames)) { // All attributes are requested, we look them up now attributes = getAllAttributesNames(pServers,pMBeanName); } return attributes; }
java
{ "resource": "" }
q162641
ReadHandler.getMBeanInfo
train
private MBeanInfo getMBeanInfo(MBeanServerExecutor pServerManager, ObjectName pObjectName) throws IOException, ReflectionException, MBeanException, AttributeNotFoundException, InstanceNotFoundException { return pServerManager.call(pObjectName, MBEAN_INFO_HANDLER); }
java
{ "resource": "" }
q162642
ReadHandler.getAttribute
train
private Object getAttribute(MBeanServerExecutor pServerManager, ObjectName pMBeanName, String attribute) throws MBeanException, ReflectionException, IOException, AttributeNotFoundException, InstanceNotFoundException { return pServerManager.call(pMBeanName, MBEAN_ATTRIBUTE_READ_HANDLER, attribute); }
java
{ "resource": "" }
q162643
ReadHandler.getAllAttributesNames
train
private List<String> getAllAttributesNames(MBeanServerExecutor pServerManager, ObjectName pObjectName) throws IOException, ReflectionException, MBeanException, AttributeNotFoundException, InstanceNotFoundException { MBeanInfo mBeanInfo = getMBeanInfo(pServerManager, pObjectName); List<String> ret = new ArrayList<String>(); for (MBeanAttributeInfo attrInfo : mBeanInfo.getAttributes()) { if (attrInfo.isReadable()) { ret.add(attrInfo.getName()); } } return ret; }
java
{ "resource": "" }
q162644
JmxReadRequest.getAttributeName
train
public String getAttributeName() { if (attributeNames == null) { return null; } if (isMultiAttributeMode()) { throw new IllegalStateException("Request contains more than one attribute (attrs = " + "" + attributeNames + "). Use getAttributeNames() instead."); } return attributeNames.get(0); }
java
{ "resource": "" }
q162645
JmxReadRequest.initAttribute
train
private void initAttribute(Object pAttrval) { if (pAttrval instanceof String) { attributeNames = EscapeUtil.split((String) pAttrval,EscapeUtil.CSV_ESCAPE,","); multiAttributeMode = attributeNames.size() > 1; } else if (pAttrval instanceof Collection) { Collection<String> attributes = (Collection<String>) pAttrval; if (attributes.size() == 1 && attributes.iterator().next() == null) { attributeNames = null; multiAttributeMode = false; } else { attributeNames = new ArrayList<String>(attributes); multiAttributeMode = true; } } else if (pAttrval == null) { attributeNames = null; multiAttributeMode = false; } else { throw new IllegalArgumentException("Attribute names must be either a String, Collection or null (and not " + pAttrval.getClass() + ")"); } }
java
{ "resource": "" }
q162646
EscapeUtil.combineToPath
train
public static String combineToPath(List<String> pParts) { if (pParts != null && pParts.size() > 0) { StringBuilder buf = new StringBuilder(); Iterator<String> it = pParts.iterator(); while (it.hasNext()) { String part = it.next(); buf.append(escapePart(part != null ? part : "*")); if (it.hasNext()) { buf.append("/"); } } return buf.toString(); } else { return null; } }
java
{ "resource": "" }
q162647
EscapeUtil.parsePath
train
public static List<String> parsePath(String pPath) { // Special cases which simply implies 'no path' if (pPath == null || pPath.equals("") || pPath.equals("/")) { return null; } return replaceWildcardsWithNull(split(pPath, PATH_ESCAPE, "/")); }
java
{ "resource": "" }
q162648
EscapeUtil.reversePath
train
public static Stack<String> reversePath(List<String> pathParts) { Stack<String> pathStack = new Stack<String>(); if (pathParts != null) { // Needs first extra argument at top of the stack for (int i = pathParts.size() - 1;i >=0;i--) { pathStack.push(pathParts.get(i)); } } return pathStack; }
java
{ "resource": "" }
q162649
EscapeUtil.escape
train
public static String escape(String pArg, String pEscape, String pDelimiter) { return pArg.replaceAll(pEscape, pEscape + pEscape).replaceAll(pDelimiter, pEscape + pDelimiter); }
java
{ "resource": "" }
q162650
EscapeUtil.createSplitPatterns
train
private static Pattern[] createSplitPatterns(String pEscape, String pDel) { return new Pattern[] { // Escape ($1: Everything before the delimiter, $2: Trailing escaped values (optional) Pattern.compile("(.*?)" + // Any chars "(?:" + // The delimiter not preceded by an escape (but pairs of escape & value can be in // are allowed before nevertheless). A negative-look-before (?<!) is used for this // purpose "(?<!" + pEscape + ")((?:" + pEscape + ".)*)" + pDel + "|" + "$" + // or end-of-line ")",Pattern.DOTALL), // Unescape, group must match unescaped value Pattern.compile(pEscape + "(.)",Pattern.DOTALL) }; }
java
{ "resource": "" }
q162651
AgentLauncher.main
train
@SuppressWarnings("PMD.ExceptionAsFlowControl") public static void main(String... args) { OptionsAndArgs options; try { options = new OptionsAndArgs(CommandDispatcher.getAvailableCommands(),args); VirtualMachineHandler vmHandler = new VirtualMachineHandler(options); CommandDispatcher dispatcher = new CommandDispatcher(options); // Attach a VirtualMachine to a given PID (if PID is given) Object vm = options.needsVm() ? vmHandler.attachVirtualMachine() : null; // Dispatch command int exitCode = 0; try { exitCode = dispatcher.dispatchCommand(vm,vmHandler); } catch (InvocationTargetException e) { throw new ProcessingException("InvocationTargetException",e,options); } catch (NoSuchMethodException e) { throw new ProcessingException("Internal: NoSuchMethod",e,options); } catch (IllegalAccessException e) { throw new ProcessingException("IllegalAccess",e,options); } finally { if (vm != null) { vmHandler.detachAgent(vm); } } System.exit(exitCode); } catch (IllegalArgumentException exp) { System.err.println("Error: " + exp.getMessage() + "\n"); CommandDispatcher.printHelp(); System.exit(1); } catch (ProcessingException exp) { exp.printErrorMessage(); System.exit(1); } }
java
{ "resource": "" }
q162652
StringToObjectConverter.prepareValue
train
public Object prepareValue(String pExpectedClassName, Object pValue) { if (pValue == null) { return null; } else { Class expectedClass = ClassUtil.classForName(pExpectedClassName); Object param = null; if (expectedClass != null) { param = prepareValue(expectedClass,pValue); } if (param == null) { // Ok, we try to convert it from a string // If expectedClass is null, it is probably a native type, so we // let happen the string conversion // later on (e.g. conversion of pArgument.toString()) which will throw // an exception at this point if conversion can not be done return convertFromString(pExpectedClassName, pValue.toString()); } return param; } }
java
{ "resource": "" }
q162653
StringToObjectConverter.prepareForDirectUsage
train
private Object prepareForDirectUsage(Class expectedClass, Object pArgument) { Class givenClass = pArgument.getClass(); if (expectedClass.isArray() && List.class.isAssignableFrom(givenClass)) { return convertListToArray(expectedClass, (List) pArgument); } else { return expectedClass.isAssignableFrom(givenClass) ? pArgument : null; } }
java
{ "resource": "" }
q162654
StringToObjectConverter.convertFromString
train
public Object convertFromString(String pType, String pValue) { String value = convertSpecialStringTags(pValue); if (value == null) { return null; } if (pType.startsWith("[") && pType.length() >= 2) { return convertToArray(pType, value); } Parser parser = PARSER_MAP.get(pType); if (parser != null) { return parser.extract(value); } Object cValue = convertByConstructor(pType, pValue); if (cValue != null) { return cValue; } throw new IllegalArgumentException( "Cannot convert string " + value + " to type " + pType + " because no converter could be found"); }
java
{ "resource": "" }
q162655
StringToObjectConverter.convertToArray
train
private Object convertToArray(String pType, String pValue) { // It's an array String t = pType.substring(1,2); Class valueType; if (t.equals("L")) { // It's an object-type String oType = pType.substring(2,pType.length()-1).replace('/','.'); valueType = ClassUtil.classForName(oType); if (valueType == null) { throw new IllegalArgumentException("No class of type " + oType + "found"); } } else { valueType = TYPE_SIGNATURE_MAP.get(t); if (valueType == null) { throw new IllegalArgumentException("Cannot convert to unknown array type " + t); } } String[] values = EscapeUtil.splitAsArray(pValue, EscapeUtil.PATH_ESCAPE, ","); Object ret = Array.newInstance(valueType,values.length); int i = 0; for (String value : values) { Array.set(ret,i++,value.equals("[null]") ? null : convertFromString(valueType.getCanonicalName(),value)); } return ret; }
java
{ "resource": "" }
q162656
StringToObjectConverter.convertListToArray
train
private Object convertListToArray(Class pType, List pList) { Class valueType = pType.getComponentType(); Object ret = Array.newInstance(valueType, pList.size()); int i = 0; for (Object value : pList) { if (value == null) { if (!valueType.isPrimitive()) { Array.set(ret,i++,null); } else { throw new IllegalArgumentException("Cannot use a null value in an array of type " + valueType.getSimpleName()); } } else { if (valueType.isAssignableFrom(value.getClass())) { // Can be set directly Array.set(ret,i++,value); } else { // Try to convert from string Array.set(ret,i++,convertFromString(valueType.getCanonicalName(), value.toString())); } } } return ret; }
java
{ "resource": "" }
q162657
Jsr160RequestDispatcher.dispatchRequest
train
public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException { JsonRequestHandler handler = requestHandlerManager.getRequestHandler(pJmxReq.getType()); JMXConnector connector = null; try { connector = createConnector(pJmxReq); connector.connect(); MBeanServerConnection connection = connector.getMBeanServerConnection(); if (handler.handleAllServersAtOnce(pJmxReq)) { // There is no way to get remotely all MBeanServers ... MBeanServerExecutor manager = new MBeanServerExecutorRemote(connection); return handler.handleRequest(manager, pJmxReq); } else { return handler.handleRequest(connection, pJmxReq); } } finally { releaseConnector(connector); } }
java
{ "resource": "" }
q162658
Jsr160RequestDispatcher.prepareEnv
train
protected Map<String,Object> prepareEnv(Map<String, String> pTargetConfig) { if (pTargetConfig == null || pTargetConfig.size() == 0) { return null; } Map<String,Object> ret = new HashMap<String, Object>(pTargetConfig); String user = (String) ret.remove("user"); String password = (String) ret.remove("password"); if (user != null && password != null) { ret.put(Context.SECURITY_PRINCIPAL, user); ret.put(Context.SECURITY_CREDENTIALS, password); ret.put("jmx.remote.credentials",new String[] { user, password }); } return ret; }
java
{ "resource": "" }
q162659
Jsr160RequestDispatcher.acceptTargetUrl
train
private boolean acceptTargetUrl(String urlS) { // Whitelist has precedence. Only patterns on the white list are allowed if (whiteList != null) { return checkPattern(whiteList, urlS, true); } // Then blacklist: Everything on this list is forbidden if (blackList != null) { return checkPattern(blackList, urlS, false); } // If no list is configured, then everything is allowed return true; }
java
{ "resource": "" }
q162660
J4pBulkRemoteException.getResponses
train
public <T extends J4pResponse> List<T> getResponses() { List<T> ret = new ArrayList<T>(); for (Object entry : results) { if (entry instanceof J4pResponse) { ret.add((T) entry); } } return ret; }
java
{ "resource": "" }
q162661
JBossDetector.addMBeanServers
train
@Override /** {@inheritDoc} */ public void addMBeanServers(Set<MBeanServerConnection> servers) { try { Class locatorClass = Class.forName("org.jboss.mx.util.MBeanServerLocator"); Method method = locatorClass.getMethod("locateJBoss"); servers.add((MBeanServer) method.invoke(null)); } catch (ClassNotFoundException e) { /* Ok, its *not* JBoss 4,5 or 6, continue with search ... */ } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } }
java
{ "resource": "" }
q162662
Base64Util.decodeBytes
train
private static byte[] decodeBytes(byte[] pInBytes) { byte[] decodabet = DECODABET; int len34 = pInBytes.length * 3 / 4; // Estimate on array size byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; // Keep track of where we're writing byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space int b4Posn = 0; // Keep track of four byte input buffer int i = 0; // Source array counter byte sbiCrop = 0; // Low seven bits (ASCII) of input byte sbiDecode = 0; // Special value from DECODABET for( i = 0; i < 0 + pInBytes.length; i++ ) { // Loop through source sbiCrop = (byte)(pInBytes[i] & 0x7f); // Only the low seven bits sbiDecode = decodabet[ sbiCrop ]; // Special value // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if( sbiDecode >= WHITE_SPACE_ENC ) { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = sbiCrop; // Save non-whitespace if( b4Posn > 3 ) { // Time to decode? outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( sbiCrop == EQUALS_SIGN ) { break; } } } } else { // There's a bad input character in the Base64 stream. throw new IllegalArgumentException(String.format( "Bad Base64 input character '%d' in array position %d", pInBytes[i], i ) ); } } byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; }
java
{ "resource": "" }
q162663
Base64Util.verifyArguments
train
private static void verifyArguments(byte[] source, int srcOffset, byte[] destination, int destOffset) { // Lots of error checking and exception throwing if( source == null ){ throw new IllegalArgumentException( "Source array was null." ); } // end if if( destination == null ){ throw new IllegalArgumentException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); } // end if }
java
{ "resource": "" }
q162664
ServiceAuthenticationHttpContext.shouldBeUsed
train
public static boolean shouldBeUsed(String authMode) { return authMode != null && (authMode.equalsIgnoreCase(AUTHMODE_SERVICE_ALL) || authMode.equalsIgnoreCase(AUTHMODE_SERVICE_ANY)); }
java
{ "resource": "" }
q162665
TabularDataConverter.checkForMapKey
train
private boolean checkForMapKey(TabularType pType) { List<String> indexNames = pType.getIndexNames(); return // Single index named "key" indexNames.size() == 1 && indexNames.contains(TD_KEY_KEY) && // Only convert to map for simple types for all others use normal conversion. See #105 for details. pType.getRowType().getType(TD_KEY_KEY) instanceof SimpleType; }
java
{ "resource": "" }
q162666
TabularDataConverter.checkForFullTabularDataRepresentation
train
private boolean checkForFullTabularDataRepresentation(JSONObject pValue, TabularType pType) { if (pValue.containsKey("indexNames") && pValue.containsKey("values") && pValue.size() == 2) { Object jsonVal = pValue.get("indexNames"); if (!(jsonVal instanceof JSONArray)) { throw new IllegalArgumentException("Index names for tabular data must given as JSON array, not " + jsonVal.getClass()); } JSONArray indexNames = (JSONArray) jsonVal; List<String> tabularIndexNames = pType.getIndexNames(); if (indexNames.size() != tabularIndexNames.size()) { throw new IllegalArgumentException("Given array with index names must have " + tabularIndexNames.size() + " entries " + "(given: " + indexNames + ", required: " + tabularIndexNames + ")"); } for (Object index : indexNames) { if (!tabularIndexNames.contains(index.toString())) { throw new IllegalArgumentException("No index with name '" + index + "' known " + "(given: " + indexNames + ", required: " + tabularIndexNames + ")"); } } return true; } return false; }
java
{ "resource": "" }
q162667
TabularDataConverter.convertTabularDataFromFullRepresentation
train
private TabularData convertTabularDataFromFullRepresentation(JSONObject pValue, TabularType pType) { JSONAware jsonVal; jsonVal = (JSONAware) pValue.get("values"); if (!(jsonVal instanceof JSONArray)) { throw new IllegalArgumentException("Values for tabular data of type " + pType + " must given as JSON array, not " + jsonVal.getClass()); } TabularDataSupport tabularData = new TabularDataSupport(pType); for (Object val : (JSONArray) jsonVal) { if (!(val instanceof JSONObject)) { throw new IllegalArgumentException("Tabular-Data values must be given as JSON objects, not " + val.getClass()); } tabularData.put((CompositeData) getDispatcher().convertToObject(pType.getRowType(), val)); } return tabularData; }
java
{ "resource": "" }
q162668
NetworkUtil.getLocalAddress
train
public static InetAddress getLocalAddress() throws UnknownHostException, SocketException { InetAddress addr = InetAddress.getLocalHost(); NetworkInterface nif = NetworkInterface.getByInetAddress(addr); if (addr.isLoopbackAddress() || addr instanceof Inet6Address || nif == null) { // Find local address that isn't a loopback address InetAddress lookedUpAddr = findLocalAddressViaNetworkInterface(); // If a local, multicast enabled address can be found, use it. Otherwise // we are using the local address, which might not be what you want addr = lookedUpAddr != null ? lookedUpAddr : InetAddress.getByName("127.0.0.1"); } return addr; }
java
{ "resource": "" }
q162669
NetworkUtil.findLocalAddressViaNetworkInterface
train
public static InetAddress findLocalAddressViaNetworkInterface() { Enumeration<NetworkInterface> networkInterfaces; try { networkInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { return null; } while (networkInterfaces.hasMoreElements()) { NetworkInterface nif = networkInterfaces.nextElement(); for (Enumeration<InetAddress> addrEnum = nif.getInetAddresses(); addrEnum.hasMoreElements(); ) { InetAddress interfaceAddress = addrEnum.nextElement(); if (useInetAddress(nif, interfaceAddress)) { return interfaceAddress; } } } return null; }
java
{ "resource": "" }
q162670
NetworkUtil.isMulticastSupported
train
public static boolean isMulticastSupported(NetworkInterface pNif) { return pNif != null && checkMethod(pNif, isUp) && checkMethod(pNif, supportsMulticast); }
java
{ "resource": "" }
q162671
NetworkUtil.getMulticastAddresses
train
public static List<InetAddress> getMulticastAddresses() throws SocketException { Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); List<InetAddress> ret = new ArrayList<InetAddress>(); while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); if (checkMethod(nif, supportsMulticast) && checkMethod(nif, isUp)) { Enumeration<InetAddress> addresses = nif.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); // TODO: IpV6 support if (!(addr instanceof Inet6Address)) { ret.add(addr); } } } } return ret; }
java
{ "resource": "" }
q162672
NetworkUtil.useInetAddress
train
private static boolean useInetAddress(NetworkInterface networkInterface, InetAddress interfaceAddress) { return checkMethod(networkInterface, isUp) && checkMethod(networkInterface, supportsMulticast) && // TODO: IpV6 support !(interfaceAddress instanceof Inet6Address) && !interfaceAddress.isLoopbackAddress(); }
java
{ "resource": "" }
q162673
NetworkUtil.checkMethod
train
private static Boolean checkMethod(NetworkInterface iface, Method toCheck) { if (toCheck != null) { try { return (Boolean) toCheck.invoke(iface, (Object[]) null); } catch (IllegalAccessException e) { return false; } catch (InvocationTargetException e) { return false; } } // Cannot check, hence we assume that is true return true; }
java
{ "resource": "" }
q162674
NetworkUtil.findLocalAddressListeningOnPort
train
private static InetAddress findLocalAddressListeningOnPort(String pHost, int pPort) throws UnknownHostException, SocketException { InetAddress address = InetAddress.getByName(pHost); if (address.isLoopbackAddress()) { // First check local address InetAddress localAddress = getLocalAddress(); if (!localAddress.isLoopbackAddress() && isPortOpen(localAddress, pPort)) { return localAddress; } // Then try all addresses attache to all interfaces localAddress = getLocalAddressFromNetworkInterfacesListeningOnPort(pPort); if (localAddress != null) { return localAddress; } } return address; }
java
{ "resource": "" }
q162675
NetworkUtil.isPortOpen
train
private static boolean isPortOpen(InetAddress pAddress, int pPort) { Socket socket = null; try { socket = new Socket(); socket.setReuseAddress(true); SocketAddress sa = new InetSocketAddress(pAddress, pPort); socket.connect(sa, 200); return socket.isConnected(); } catch (IOException e) { return false; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // Best effort. Hate that close throws an IOException, btw. Never saw a real use case for that. } } } }
java
{ "resource": "" }
q162676
NetworkUtil.getProcessId
train
private static String getProcessId() { // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); final int index = jvmName.indexOf('@'); return index < 0 ? jvmName : jvmName.substring(0, index); }
java
{ "resource": "" }
q162677
NetworkUtil.dumpLocalNetworkInfo
train
public static String dumpLocalNetworkInfo() throws UnknownHostException, SocketException { StringBuffer buffer = new StringBuffer(); InetAddress addr = InetAddress.getLocalHost(); buffer.append("Localhost: " + getAddrInfo(addr) + "\n"); Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); buffer.append("Network interfaces:\n"); while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); buffer.append(" - " + getNetworkInterfaceInfo(nif) + "\n"); Enumeration<InetAddress> addresses = nif.getInetAddresses(); while (addresses.hasMoreElements()) { addr = addresses.nextElement(); buffer.append(" " + getAddrInfo(addr) + "\n"); } } return buffer.toString(); }
java
{ "resource": "" }
q162678
AbstractMBeanServerExecutor.registerForMBeanNotifications
train
protected void registerForMBeanNotifications() { Set<MBeanServerConnection> servers = getMBeanServers(); Exception lastExp = null; StringBuilder errors = new StringBuilder(); for (MBeanServerConnection server : servers) { try { JmxUtil.addMBeanRegistrationListener(server,this,null); } catch (IllegalStateException e) { lastExp = updateErrorMsg(errors,e); } } if (lastExp != null) { throw new IllegalStateException(errors.substring(0,errors.length()-1),lastExp); } }
java
{ "resource": "" }
q162679
AbstractMBeanServerExecutor.updateErrorMsg
train
private Exception updateErrorMsg(StringBuilder pErrors, Exception exp) { pErrors.append(exp.getClass()).append(": ").append(exp.getMessage()).append("\n"); return exp; }
java
{ "resource": "" }
q162680
KeyStoreUtil.updateWithCaPem
train
public static void updateWithCaPem(KeyStore pTrustStore, File pCaCert) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { InputStream is = new FileInputStream(pCaCert); try { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is); String alias = cert.getSubjectX500Principal().getName(); pTrustStore.setCertificateEntry(alias, cert); } finally { is.close(); } }
java
{ "resource": "" }
q162681
KeyStoreUtil.updateWithServerPems
train
public static void updateWithServerPems(KeyStore pKeyStore, File pServerCert, File pServerKey, String pKeyAlgo, char[] pPassword) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException { InputStream is = new FileInputStream(pServerCert); try { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is); byte[] keyBytes = decodePem(pServerKey); PrivateKey privateKey; KeyFactory keyFactory = KeyFactory.getInstance(pKeyAlgo); try { // First let's try PKCS8 privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); } catch (InvalidKeySpecException e) { // Otherwise try PKCS1 RSAPrivateCrtKeySpec keySpec = PKCS1Util.decodePKCS1(keyBytes); privateKey = keyFactory.generatePrivate(keySpec); } String alias = cert.getSubjectX500Principal().getName(); pKeyStore.setKeyEntry(alias, privateKey, pPassword, new Certificate[]{cert}); } finally { is.close(); } }
java
{ "resource": "" }
q162682
KeyStoreUtil.updateWithSelfSignedServerCertificate
train
public static void updateWithSelfSignedServerCertificate(KeyStore pKeyStore) throws NoSuchProviderException, NoSuchAlgorithmException, IOException, InvalidKeyException, CertificateException, SignatureException, KeyStoreException { final Object x500Name; final Object[] certAttributes = { "Jolokia Agent " + Version.getAgentVersion(), // CN "JVM", // OU "jolokia.org", // O "Pegnitz", // L "Franconia", // ST "DE" }; if (ClassUtil.checkForClass(X500_NAME_SUN)) { x500Name = ClassUtil.newInstance(X500_NAME_SUN, certAttributes); } else if (ClassUtil.checkForClass(X500_NAME_IBM)) { x500Name = ClassUtil.newInstance(X500_NAME_IBM, certAttributes); } else { throw new IllegalStateException("Neither Sun- nor IBM-style JVM found."); } // Need to do it via reflection because Java8 moved class to a different package Object keypair = createKeyPair(); PrivateKey privKey = getPrivateKey(keypair); X509Certificate[] chain = new X509Certificate[1]; chain[0] = getSelfCertificate(keypair, x500Name, new Date(), (long) 3650 * 24 * 60 * 60); pKeyStore.setKeyEntry("jolokia-agent", privKey, new char[0], chain); }
java
{ "resource": "" }
q162683
ListExtractor.setObjectValue
train
public Object setObjectValue(StringToObjectConverter pConverter, Object pInner, String pIndex, Object pValue) throws IllegalAccessException, InvocationTargetException { List list = (List) pInner; int idx; try { idx = Integer.parseInt(pIndex); } catch (NumberFormatException exp) { throw new IllegalArgumentException("Non-numeric index for accessing collection " + pInner + ". (index = " + pIndex + ", value to set = " + pValue + ")",exp); } // For a collection, we can infer the type within the collection. We are trying to fetch // the old value, and if set, we use its type. Otherwise, we simply use string as value. Object oldValue = list.get(idx); Object value = oldValue != null ? pConverter.prepareValue(oldValue.getClass().getName(), pValue) : pValue; list.set(idx,value); return oldValue; }
java
{ "resource": "" }
q162684
JmxListRequest.newCreator
train
static RequestCreator<JmxListRequest> newCreator() { return new RequestCreator<JmxListRequest>() { /** {@inheritDoc} */ public JmxListRequest create(Stack<String> pStack, ProcessingParameters pParams) throws MalformedObjectNameException { return new JmxListRequest( prepareExtraArgs(pStack), // path pParams); } /** {@inheritDoc} */ public JmxListRequest create(Map<String, ?> requestMap, ProcessingParameters pParams) throws MalformedObjectNameException { return new JmxListRequest(requestMap,pParams); } }; }
java
{ "resource": "" }
q162685
JvmAgent.awaitServerInitialization
train
private static void awaitServerInitialization(JvmAgentConfig pConfig, final Instrumentation instrumentation) { List<ServerDetector> detectors = MBeanServerHandler.lookupDetectors(); for (ServerDetector detector : detectors) { detector.jvmAgentStartup(instrumentation); } }
java
{ "resource": "" }
q162686
JolokiaHttpHandler.start
train
public void start(boolean pLazy) { Restrictor restrictor = createRestrictor(); backendManager = new BackendManager(configuration, logHandler, restrictor, pLazy); requestHandler = new HttpRequestHandler(configuration, backendManager, logHandler); if (listenForDiscoveryMcRequests(configuration)) { try { discoveryMulticastResponder = new DiscoveryMulticastResponder(backendManager, restrictor, logHandler); discoveryMulticastResponder.start(); } catch (IOException e) { logHandler.error("Cannot start discovery multicast handler: " + e, e); } } }
java
{ "resource": "" }
q162687
JolokiaHttpHandler.start
train
public void start(boolean pLazy, String pUrl, boolean pSecured) { start(pLazy); AgentDetails details = backendManager.getAgentDetails(); details.setUrl(pUrl); details.setSecured(pSecured); }
java
{ "resource": "" }
q162688
JolokiaHttpHandler.stop
train
public void stop() { if (discoveryMulticastResponder != null) { discoveryMulticastResponder.stop(); discoveryMulticastResponder = null; } backendManager.destroy(); backendManager = null; requestHandler = null; }
java
{ "resource": "" }
q162689
JolokiaHttpHandler.handle
train
public void handle(final HttpExchange pHttpExchange) throws IOException { try { checkAuthentication(pHttpExchange); Subject subject = (Subject) pHttpExchange.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE); if (subject != null) { doHandleAs(subject, pHttpExchange); } else { doHandle(pHttpExchange); } } catch (SecurityException exp) { sendForbidden(pHttpExchange,exp); } }
java
{ "resource": "" }
q162690
JolokiaHttpHandler.doHandleAs
train
private void doHandleAs(Subject subject, final HttpExchange pHttpExchange) { try { Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { public Void run() throws IOException { doHandle(pHttpExchange); return null; } }); } catch (PrivilegedActionException e) { throw new SecurityException("Security exception: " + e.getCause(),e.getCause()); } }
java
{ "resource": "" }
q162691
JolokiaHttpHandler.extractOriginOrReferer
train
private String extractOriginOrReferer(HttpExchange pExchange) { Headers headers = pExchange.getRequestHeaders(); String origin = headers.getFirst("Origin"); if (origin == null) { origin = headers.getFirst("Referer"); } return origin != null ? origin.replaceAll("[\\n\\r]*","") : null; }
java
{ "resource": "" }
q162692
JolokiaHttpHandler.getHostName
train
private String getHostName(InetSocketAddress address) { return configuration.getAsBoolean(ConfigKey.ALLOW_DNS_REVERSE_LOOKUP) ? address.getHostName() : null; }
java
{ "resource": "" }
q162693
JolokiaHttpHandler.getMimeType
train
private String getMimeType(ParsedUri pParsedUri) { return MimeTypeUtil.getResponseMimeType( pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue()), configuration.get(ConfigKey.MIME_TYPE), pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue())); }
java
{ "resource": "" }
q162694
JolokiaHttpHandler.createLogHandler
train
private LogHandler createLogHandler(String pLogHandlerClass, String pDebug) { if (pLogHandlerClass != null) { return ClassUtil.newInstance(pLogHandlerClass); } else { final boolean debug = Boolean.valueOf(pDebug); return new LogHandler.StdoutLogHandler(debug); } }
java
{ "resource": "" }
q162695
MuleAgentHttpServerFactory.create
train
public static MuleAgentHttpServer create(Agent pParent, MuleAgentConfig pConfig) { if (ClassUtil.checkForClass("org.mortbay.jetty.Server")) { return new MortbayMuleAgentHttpServer(pParent, pConfig); } else if (ClassUtil.checkForClass("org.eclipse.jetty.server.ServerConnector")) { return new Jetty9MuleAgentHttpServer(pParent, pConfig); } else if (ClassUtil.checkForClass("org.eclipse.jetty.server.Server")) { return new Jetty7And8MuleAgentHttpServer(pParent, pConfig); } throw new IllegalStateException("Cannot detect Jetty version (tried 6,7,8,9)"); }
java
{ "resource": "" }
q162696
ServersInfo.dump
train
public static String dump(Set<MBeanServerConnection> servers) { StringBuffer ret = new StringBuffer(); ret.append("Found ").append(servers.size()).append(" MBeanServers\n"); for (MBeanServerConnection c : servers) { MBeanServer s = (MBeanServer) c; ret.append(" ") .append("++ ") .append(s.toString()) .append(": default domain = ") .append(s.getDefaultDomain()) .append(", ") .append(s.getMBeanCount()) .append(" MBeans\n"); ret.append(" Domains:\n"); for (String d : s.getDomains()) { appendDomainInfo(ret, s, d); } } ret.append("\n"); ret.append("Platform MBeanServer: ") .append(ManagementFactory.getPlatformMBeanServer()) .append("\n"); return ret.toString(); }
java
{ "resource": "" }
q162697
JsonDynamicMBeanImpl.mapAndInvoke
train
private Object mapAndInvoke(String pOperation, Object[] pParams, String[] pSignature, OperationMapInfo pOpMapInfo) throws InstanceNotFoundException, MBeanException, ReflectionException { // Map parameters Object realParams[] = new Object[pSignature.length]; String realSignature[] = new String[pSignature.length]; for (int i = 0; i < pSignature.length; i++) { if (pOpMapInfo.isParamMapped(i)) { String origType = pOpMapInfo.getOriginalType(i); OpenType openType = pOpMapInfo.getOpenMBeanType(i); if (openType != null) { realParams[i] = fromJson(openType, (String) pParams[i]); } else { realParams[i] = fromJson(origType, (String) pParams[i]); } realSignature[i] = origType; } else { realParams[i] = pParams[i]; realSignature[i] = pSignature[i]; } } Object ret = jolokiaMBeanServer.invoke(objectName, pOperation, realParams, realSignature); return pOpMapInfo.isRetTypeMapped() ? toJson(ret) : ret; }
java
{ "resource": "" }
q162698
JsonDynamicMBeanImpl.getOperationMapInfo
train
private OperationMapInfo getOperationMapInfo(String pOperation, String[] pSignature) { List<OperationMapInfo> opMapInfoList = operationInfoMap.get(pOperation); OperationMapInfo opMapInfo = null; if (opMapInfoList != null) { for (OperationMapInfo i : opMapInfoList) { if (i.matchSignature(pSignature)) { opMapInfo = i; break; } } } return opMapInfo; }
java
{ "resource": "" }
q162699
JsonDynamicMBeanImpl.getWrappedInfo
train
private MBeanInfo getWrappedInfo(MBeanInfo pMBeanInfo) { MBeanAttributeInfo[] attrInfo = getWrappedAttributeInfo(pMBeanInfo); MBeanOperationInfo[] opInfo = getWrappedOperationInfo(pMBeanInfo); return new MBeanInfo(pMBeanInfo.getClassName(), pMBeanInfo.getDescription(), attrInfo, null, /* We dont allow construction of this MBean, hence null-constructors */ opInfo, pMBeanInfo.getNotifications() ); }
java
{ "resource": "" }