_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q5600
StepFinder.prioritise
train
public List<StepCandidate> prioritise(String stepAsText, List<StepCandidate> candidates) { return prioritisingStrategy.prioritise(stepAsText, candidates); }
java
{ "resource": "" }
q5601
PrintStreamOutput.format
train
protected String format(String key, String defaultPattern, Object... args) { String escape = escape(defaultPattern); String s = lookupPattern(key, escape); Object[] objects = escapeAll(args); return MessageFormat.format(s, objects); }
java
{ "resource": "" }
q5602
PrintStreamOutput.escape
train
protected Object[] escape(final Format format, Object... args) { // Transformer that escapes HTML,XML,JSON strings Transformer<Object, Object> escapingTransformer = new Transformer<Object, Object>() { @Override public Object transform(Object object) { return format.escapeValue(object); } }; List<Object> list = Arrays.asList(ArrayUtils.clone(args)); CollectionUtils.transform(list, escapingTransformer); return list.toArray(); }
java
{ "resource": "" }
q5603
PrintStreamOutput.print
train
protected void print(String text) { String tableStart = format(PARAMETER_TABLE_START, PARAMETER_TABLE_START); String tableEnd = format(PARAMETER_TABLE_END, PARAMETER_TABLE_END); boolean containsTable = text.contains(tableStart) && text.contains(tableEnd); String textToPrint = containsTable ? transformPrintingTable(text, tableStart, tableEnd) : text; print(output, textToPrint .replace(format(PARAMETER_VALUE_START, PARAMETER_VALUE_START), format("parameterValueStart", EMPTY)) .replace(format(PARAMETER_VALUE_END, PARAMETER_VALUE_END), format("parameterValueEnd", EMPTY)) .replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE), format("parameterValueNewline", NL))); }
java
{ "resource": "" }
q5604
NeedleStepsFactory.methodReturningConverters
train
private List<ParameterConverter> methodReturningConverters(final Class<?> type) { final List<ParameterConverter> converters = new ArrayList<>(); for (final Method method : type.getMethods()) { if (method.isAnnotationPresent(AsParameterConverter.class)) { converters.add(new MethodReturningConverter(method, type, this)); } } return converters; }
java
{ "resource": "" }
q5605
NeedleStepsFactory.toArray
train
static InjectionProvider<?>[] toArray(final Set<InjectionProvider<?>> injectionProviders) { return injectionProviders.toArray(new InjectionProvider<?>[injectionProviders.size()]); }
java
{ "resource": "" }
q5606
TraderSteps.retrieveTrader
train
@AsParameterConverter public Trader retrieveTrader(String name) { for (Trader trader : traders) { if (trader.getName().equals(name)) { return trader; } } return mockTradePersister().retrieveTrader(name); }
java
{ "resource": "" }
q5607
SpringStepsFactory.beanType
train
private Class<?> beanType(String name) { Class<?> type = context.getType(name); if (ClassUtils.isCglibProxyClass(type)) { return AopProxyUtils.ultimateTargetClass(context.getBean(name)); } return type; }
java
{ "resource": "" }
q5608
GuiceAnnotationBuilder.findBinding
train
private boolean findBinding(Injector injector, Class<?> type) { boolean found = false; for (Key<?> key : injector.getBindings().keySet()) { if (key.getTypeLiteral().getRawType().equals(type)) { found = true; break; } } if (!found && injector.getParent() != null) { return findBinding(injector.getParent(), type); } return found; }
java
{ "resource": "" }
q5609
JarFileScanner.scan
train
public List<String> scan() { try { JarFile jar = new JarFile(jarURL.getFile()); try { List<String> result = new ArrayList<>(); Enumeration<JarEntry> en = jar.entries(); while (en.hasMoreElements()) { JarEntry entry = en.nextElement(); String path = entry.getName(); boolean match = includes.size() == 0; if (!match) { for (String pattern : includes) { if ( patternMatches(pattern, path)) { match = true; break; } } } if (match) { for (String pattern : excludes) { if ( patternMatches(pattern, path)) { match = false; break; } } } if (match) { result.add(path); } } return result; } finally { jar.close(); } } catch (IOException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q5610
Stepdoc.getMethodSignature
train
public String getMethodSignature() { if (method != null) { String methodSignature = method.toString(); return methodSignature.replaceFirst("public void ", ""); } return null; }
java
{ "resource": "" }
q5611
GridStory.configuration
train
@Override public Configuration configuration() { return new MostUsefulConfiguration() // where to find the stories .useStoryLoader(new LoadFromClasspath(this.getClass())) // CONSOLE and TXT reporting .useStoryReporterBuilder(new StoryReporterBuilder().withDefaultFormats().withFormats(Format.CONSOLE, Format.TXT)); }
java
{ "resource": "" }
q5612
GetAssignmentGroupOptions.includes
train
public GetAssignmentGroupOptions includes(List<Include> includes) { List<Include> assignmentDependents = Arrays.asList(Include.DISCUSSION_TOPIC, Include.ASSIGNMENT_VISIBILITY, Include.SUBMISSION); if(includes.stream().anyMatch(assignmentDependents::contains) && !includes.contains(Include.ASSIGNMENTS)) { throw new IllegalArgumentException("Including discussion topics, all dates, assignment visibility or submissions is only valid if you also include submissions"); } addEnumList("include[]", includes); return this; }
java
{ "resource": "" }
q5613
ExternalToolImpl.ensureToolValidForCreation
train
private void ensureToolValidForCreation(ExternalTool tool) { //check for the unconditionally required fields if(StringUtils.isAnyBlank(tool.getName(), tool.getPrivacyLevel(), tool.getConsumerKey(), tool.getSharedSecret())) { throw new IllegalArgumentException("External tool requires all of the following for creation: name, privacy level, consumer key, shared secret"); } //check that there is either a URL or a domain. One or the other is required if(StringUtils.isBlank(tool.getUrl()) && StringUtils.isBlank(tool.getDomain())) { throw new IllegalArgumentException("External tool requires either a URL or domain for creation"); } }
java
{ "resource": "" }
q5614
GetSingleConversationOptions.filters
train
public GetSingleConversationOptions filters(List<String> filters) { if(filters.size() == 1) { //Canvas API doesn't want the [] if it is only one value addSingleItem("filter", filters.get(0)); } else { optionsMap.put("filter[]", filters); } return this; }
java
{ "resource": "" }
q5615
CanvasApiFactory.getReader
train
public <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken) { return getReader(type, oauthToken, null); }
java
{ "resource": "" }
q5616
CanvasApiFactory.getReader
train
public <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken, Integer paginationPageSize) { LOG.debug("Factory call to instantiate class: " + type.getName()); RestClient restClient = new RefreshingRestClient(); @SuppressWarnings("unchecked") Class<T> concreteClass = (Class<T>)readerMap.get(type); if (concreteClass == null) { throw new UnsupportedOperationException("No implementation for requested interface found: " + type.getName()); } LOG.debug("got class: " + concreteClass); try { Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class, OauthToken.class, RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class); return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient, connectTimeout, readTimeout, paginationPageSize, false); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { throw new UnsupportedOperationException("Unknown error instantiating the concrete API class: " + type.getName(), e); } }
java
{ "resource": "" }
q5617
CanvasApiFactory.getWriter
train
public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken) { return getWriter(type, oauthToken, false); }
java
{ "resource": "" }
q5618
CanvasApiFactory.getWriter
train
public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken, Boolean serializeNulls) { LOG.debug("Factory call to instantiate class: " + type.getName()); RestClient restClient = new RefreshingRestClient(); @SuppressWarnings("unchecked") Class<T> concreteClass = (Class<T>) writerMap.get(type); if (concreteClass == null) { throw new UnsupportedOperationException("No implementation for requested interface found: " + type.getName()); } LOG.debug("got writer class: " + concreteClass); try { Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class, OauthToken.class, RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class); return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient, connectTimeout, readTimeout, null, serializeNulls); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { throw new UnsupportedOperationException("Unknown error instantiating the concrete API class: " + type.getName(), e); } }
java
{ "resource": "" }
q5619
ListActiveCoursesInAccountOptions.searchTerm
train
public ListActiveCoursesInAccountOptions searchTerm(String searchTerm) { if(searchTerm == null || searchTerm.length() < 3) { throw new IllegalArgumentException("Search term must be at least 3 characters"); } addSingleItem("search_term", searchTerm); return this; }
java
{ "resource": "" }
q5620
ListExternalToolsOptions.searchTerm
train
public ListExternalToolsOptions searchTerm(String searchTerm) { if(searchTerm == null || searchTerm.length() < 3) { throw new IllegalArgumentException("Search term must be at least 3 characters"); } addSingleItem("search_term", searchTerm); return this; }
java
{ "resource": "" }
q5621
EnrollmentTermImpl.parseEnrollmentTermList
train
private List<EnrollmentTerm> parseEnrollmentTermList(final List<Response> responses) { return responses.stream(). map(this::parseEnrollmentTermList). flatMap(Collection::stream). collect(Collectors.toList()); }
java
{ "resource": "" }
q5622
SimpleRestClient.sendJsonPostOrPut
train
private Response sendJsonPostOrPut(OauthToken token, String url, String json, int connectTimeout, int readTimeout, String method) throws IOException { LOG.debug("Sending JSON " + method + " to URL: " + url); Response response = new Response(); HttpClient httpClient = createHttpClient(connectTimeout, readTimeout); HttpEntityEnclosingRequestBase action; if("POST".equals(method)) { action = new HttpPost(url); } else if("PUT".equals(method)) { action = new HttpPut(url); } else { throw new IllegalArgumentException("Method must be either POST or PUT"); } Long beginTime = System.currentTimeMillis(); action.setHeader("Authorization", "Bearer" + " " + token.getAccessToken()); StringEntity requestBody = new StringEntity(json, ContentType.APPLICATION_JSON); action.setEntity(requestBody); try { HttpResponse httpResponse = httpClient.execute(action); String content = handleResponse(httpResponse, action); response.setContent(content); response.setResponseCode(httpResponse.getStatusLine().getStatusCode()); Long endTime = System.currentTimeMillis(); LOG.debug("POST call took: " + (endTime - beginTime) + "ms"); } finally { action.releaseConnection(); } return response; }
java
{ "resource": "" }
q5623
BaseOptions.addEnumList
train
protected void addEnumList(String key, List<? extends Enum> list) { optionsMap.put(key, list.stream().map(i -> i.toString()).collect(Collectors.toList())); }
java
{ "resource": "" }
q5624
ExtendedClientConfiguration.setLargePayloadSupportEnabled
train
public void setLargePayloadSupportEnabled(AmazonS3 s3, String s3BucketName) { if (s3 == null || s3BucketName == null) { String errorMessage = "S3 client and/or S3 bucket name cannot be null."; LOG.error(errorMessage); throw new AmazonClientException(errorMessage); } if (isLargePayloadSupportEnabled()) { LOG.warn("Large-payload support is already enabled. Overwriting AmazonS3Client and S3BucketName."); } this.s3 = s3; this.s3BucketName = s3BucketName; largePayloadSupport = true; LOG.info("Large-payload support enabled."); }
java
{ "resource": "" }
q5625
DelimitedStreamReader.readLine
train
private String readLine(boolean trim) throws IOException { boolean done = false; boolean sawCarriage = false; // bytes to trim (the \r and the \n) int removalBytes = 0; while (!done) { if (isReadBufferEmpty()) { offset = 0; end = 0; int bytesRead = inputStream.read(buffer, end, Math.min(DEFAULT_READ_COUNT, buffer.length - end)); if (bytesRead < 0) { // we failed to read anything more... throw new IOException("Reached the end of the stream"); } else { end += bytesRead; } } int originalOffset = offset; for (; !done && offset < end; offset++) { if (buffer[offset] == LF) { int cpLength = offset - originalOffset + 1; if (trim) { int length = 0; if (buffer[offset] == LF) { length ++; if (sawCarriage) { length++; } } cpLength -= length; } if (cpLength > 0) { copyToStrBuffer(buffer, originalOffset, cpLength); } else { // negative length means we need to trim a \r from strBuffer removalBytes = cpLength; } done = true; } else { // did not see newline: sawCarriage = buffer[offset] == CR; } } if (!done) { copyToStrBuffer(buffer, originalOffset, end - originalOffset); offset = end; } } int strLength = strBufferIndex + removalBytes; strBufferIndex = 0; return new String(strBuffer, 0, strLength, charset); }
java
{ "resource": "" }
q5626
DelimitedStreamReader.copyToStrBuffer
train
private void copyToStrBuffer(byte[] buffer, int offset, int length) { Preconditions.checkArgument(length >= 0); if (strBuffer.length - strBufferIndex < length) { // cannot fit, expanding buffer expandStrBuffer(length); } System.arraycopy( buffer, offset, strBuffer, strBufferIndex, Math.min(length, MAX_ALLOWABLE_BUFFER_SIZE - strBufferIndex)); strBufferIndex += length; }
java
{ "resource": "" }
q5627
DelimitedStreamReader.read
train
public String read(int numBytes) throws IOException { Preconditions.checkArgument(numBytes >= 0); Preconditions.checkArgument(numBytes <= MAX_ALLOWABLE_BUFFER_SIZE); int numBytesRemaining = numBytes; // first read whatever we need from our buffer if (!isReadBufferEmpty()) { int length = Math.min(end - offset, numBytesRemaining); copyToStrBuffer(buffer, offset, length); offset += length; numBytesRemaining -= length; } // next read the remaining chars directly into our strBuffer if (numBytesRemaining > 0) { readAmountToStrBuffer(numBytesRemaining); } if (strBufferIndex > 0 && strBuffer[strBufferIndex - 1] != LF) { // the last byte doesn't correspond to lf return readLine(false); } int strBufferLength = strBufferIndex; strBufferIndex = 0; return new String(strBuffer, 0, strBufferLength, charset); }
java
{ "resource": "" }
q5628
DefaultStreamingEndpoint.languages
train
public DefaultStreamingEndpoint languages(List<String> languages) { addPostParameter(Constants.LANGUAGE_PARAM, Joiner.on(',').join(languages)); return this; }
java
{ "resource": "" }
q5629
BaseTwitter4jClient.process
train
@Override public void process() { if (client.isDone() || executorService.isTerminated()) { throw new IllegalStateException("Client is already stopped"); } Runnable runner = new Runnable() { @Override public void run() { try { while (!client.isDone()) { String msg = messageQueue.take(); try { parseMessage(msg); } catch (Exception e) { logger.warn("Exception thrown during parsing msg " + msg, e); onException(e); } } } catch (Exception e) { onException(e); } } }; executorService.execute(runner); }
java
{ "resource": "" }
q5630
ClientBase.stop
train
public void stop(int waitMillis) throws InterruptedException { try { if (!isDone()) { setExitStatus(new Event(EventType.STOPPED_BY_USER, String.format("Stopped by user: waiting for %d ms", waitMillis))); } if (!waitForFinish(waitMillis)) { logger.warn("{} Client thread failed to finish in {} millis", name, waitMillis); } } finally { rateTracker.shutdown(); } }
java
{ "resource": "" }
q5631
WorkerListenerDelegate.fireEvent
train
public void fireEvent(final WorkerEvent event, final Worker worker, final String queue, final Job job, final Object runner, final Object result, final Throwable t) { final ConcurrentSet<WorkerListener> listeners = this.eventListenerMap.get(event); if (listeners != null) { for (final WorkerListener listener : listeners) { if (listener != null) { try { listener.onEvent(event, worker, queue, job, runner, result, t); } catch (Exception e) { log.error("Failure executing listener " + listener + " for event " + event + " from queue " + queue + " on worker " + worker, e); } } } } }
java
{ "resource": "" }
q5632
JesqueUtils.createBacktrace
train
public static List<String> createBacktrace(final Throwable t) { final List<String> bTrace = new LinkedList<String>(); for (final StackTraceElement ste : t.getStackTrace()) { bTrace.add(BT_PREFIX + ste.toString()); } if (t.getCause() != null) { addCauseToBacktrace(t.getCause(), bTrace); } return bTrace; }
java
{ "resource": "" }
q5633
JesqueUtils.addCauseToBacktrace
train
private static void addCauseToBacktrace(final Throwable cause, final List<String> bTrace) { if (cause.getMessage() == null) { bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName()); } else { bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName() + ": " + cause.getMessage()); } for (final StackTraceElement ste : cause.getStackTrace()) { bTrace.add(BT_PREFIX + ste.toString()); } if (cause.getCause() != null) { addCauseToBacktrace(cause.getCause(), bTrace); } }
java
{ "resource": "" }
q5634
JesqueUtils.map
train
@SafeVarargs public static <K, V> Map<K, V> map(final Entry<? extends K, ? extends V>... entries) { final Map<K, V> map = new LinkedHashMap<K, V>(entries.length); for (final Entry<? extends K, ? extends V> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return map; }
java
{ "resource": "" }
q5635
JesqueUtils.set
train
@SafeVarargs public static <K> Set<K> set(final K... keys) { return new LinkedHashSet<K>(Arrays.asList(keys)); }
java
{ "resource": "" }
q5636
JesqueUtils.nullSafeEquals
train
public static boolean nullSafeEquals(final Object obj1, final Object obj2) { return ((obj1 == null && obj2 == null) || (obj1 != null && obj2 != null && obj1.equals(obj2))); }
java
{ "resource": "" }
q5637
QueueInfoDAORedisImpl.size
train
private long size(final Jedis jedis, final String queueName) { final String key = key(QUEUE, queueName); final long size; if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZCARD size = jedis.zcard(key); } else { // Else, use LLEN size = jedis.llen(key); } return size; }
java
{ "resource": "" }
q5638
QueueInfoDAORedisImpl.getJobs
train
private List<Job> getJobs(final Jedis jedis, final String queueName, final long jobOffset, final long jobCount) throws Exception { final String key = key(QUEUE, queueName); final List<Job> jobs = new ArrayList<>(); if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZRANGEWITHSCORES final Set<Tuple> elements = jedis.zrangeWithScores(key, jobOffset, jobOffset + jobCount - 1); for (final Tuple elementWithScore : elements) { final Job job = ObjectMapperFactory.get().readValue(elementWithScore.getElement(), Job.class); job.setRunAt(elementWithScore.getScore()); jobs.add(job); } } else { // Else, use LRANGE final List<String> elements = jedis.lrange(key, jobOffset, jobOffset + jobCount - 1); for (final String element : elements) { jobs.add(ObjectMapperFactory.get().readValue(element, Job.class)); } } return jobs; }
java
{ "resource": "" }
q5639
Job.setVars
train
@SuppressWarnings("unchecked") public void setVars(final Map<String, ? extends Object> vars) { this.vars = (Map<String, Object>)vars; }
java
{ "resource": "" }
q5640
Job.setUnknownField
train
@JsonAnySetter public void setUnknownField(final String name, final Object value) { this.unknownFields.put(name, value); }
java
{ "resource": "" }
q5641
Job.setUnknownFields
train
@JsonIgnore public void setUnknownFields(final Map<String,Object> unknownFields) { this.unknownFields.clear(); this.unknownFields.putAll(unknownFields); }
java
{ "resource": "" }
q5642
MapBasedJobFactory.addJobType
train
public void addJobType(final String jobName, final Class<?> jobType) { checkJobType(jobName, jobType); this.jobTypes.put(jobName, jobType); }
java
{ "resource": "" }
q5643
MapBasedJobFactory.removeJobType
train
public void removeJobType(final Class<?> jobType) { if (jobType == null) { throw new IllegalArgumentException("jobType must not be null"); } this.jobTypes.values().remove(jobType); }
java
{ "resource": "" }
q5644
MapBasedJobFactory.setJobTypes
train
public void setJobTypes(final Map<String, ? extends Class<?>> jobTypes) { checkJobTypes(jobTypes); this.jobTypes.clear(); this.jobTypes.putAll(jobTypes); }
java
{ "resource": "" }
q5645
MapBasedJobFactory.checkJobTypes
train
protected void checkJobTypes(final Map<String, ? extends Class<?>> jobTypes) { if (jobTypes == null) { throw new IllegalArgumentException("jobTypes must not be null"); } for (final Entry<String, ? extends Class<?>> entry : jobTypes.entrySet()) { try { checkJobType(entry.getKey(), entry.getValue()); } catch (IllegalArgumentException iae) { throw new IllegalArgumentException("jobTypes contained invalid value", iae); } } }
java
{ "resource": "" }
q5646
MapBasedJobFactory.checkJobType
train
protected void checkJobType(final String jobName, final Class<?> jobType) { if (jobName == null) { throw new IllegalArgumentException("jobName must not be null"); } if (jobType == null) { throw new IllegalArgumentException("jobType must not be null"); } if (!(Runnable.class.isAssignableFrom(jobType)) && !(Callable.class.isAssignableFrom(jobType))) { throw new IllegalArgumentException( "jobType must implement either Runnable or Callable: " + jobType); } }
java
{ "resource": "" }
q5647
AbstractAdminClient.doPublish
train
public static void doPublish(final Jedis jedis, final String namespace, final String channel, final String jobJson) { jedis.publish(JesqueUtils.createKey(namespace, CHANNEL, channel), jobJson); }
java
{ "resource": "" }
q5648
ReflectionUtils.createObject
train
public static <T> T createObject(final Class<T> clazz, final Object... args) throws NoSuchConstructorException, AmbiguousConstructorException, ReflectiveOperationException { return findConstructor(clazz, args).newInstance(args); }
java
{ "resource": "" }
q5649
ReflectionUtils.createObject
train
public static <T> T createObject(final Class<T> clazz, final Object[] args, final Map<String,Object> vars) throws NoSuchConstructorException, AmbiguousConstructorException, ReflectiveOperationException { return invokeSetters(findConstructor(clazz, args).newInstance(args), vars); }
java
{ "resource": "" }
q5650
ReflectionUtils.findConstructor
train
@SuppressWarnings("rawtypes") private static <T> Constructor<T> findConstructor(final Class<T> clazz, final Object... args) throws NoSuchConstructorException, AmbiguousConstructorException { final Object[] cArgs = (args == null) ? new Object[0] : args; Constructor<T> constructorToUse = null; final Constructor<?>[] candidates = clazz.getConstructors(); Arrays.sort(candidates, ConstructorComparator.INSTANCE); int minTypeDiffWeight = Integer.MAX_VALUE; Set<Constructor<?>> ambiguousConstructors = null; for (final Constructor candidate : candidates) { final Class[] paramTypes = candidate.getParameterTypes(); if (constructorToUse != null && cArgs.length > paramTypes.length) { // Already found greedy constructor that can be satisfied. // Do not look any further, there are only less greedy // constructors left. break; } if (paramTypes.length != cArgs.length) { continue; } final int typeDiffWeight = getTypeDifferenceWeight(paramTypes, cArgs); if (typeDiffWeight < minTypeDiffWeight) { // Choose this constructor if it represents the closest match. constructorToUse = candidate; minTypeDiffWeight = typeDiffWeight; ambiguousConstructors = null; } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) { if (ambiguousConstructors == null) { ambiguousConstructors = new LinkedHashSet<Constructor<?>>(); ambiguousConstructors.add(constructorToUse); } ambiguousConstructors.add(candidate); } } if (ambiguousConstructors != null && !ambiguousConstructors.isEmpty()) { throw new AmbiguousConstructorException(clazz, cArgs, ambiguousConstructors); } if (constructorToUse == null) { throw new NoSuchConstructorException(clazz, cArgs); } return constructorToUse; }
java
{ "resource": "" }
q5651
ReflectionUtils.invokeSetters
train
public static <T> T invokeSetters(final T instance, final Map<String,Object> vars) throws ReflectiveOperationException { if (instance != null && vars != null) { final Class<?> clazz = instance.getClass(); final Method[] methods = clazz.getMethods(); for (final Entry<String,Object> entry : vars.entrySet()) { final String methodName = "set" + entry.getKey().substring(0, 1).toUpperCase(Locale.US) + entry.getKey().substring(1); boolean found = false; for (final Method method : methods) { if (methodName.equals(method.getName()) && method.getParameterTypes().length == 1) { method.invoke(instance, entry.getValue()); found = true; break; } } if (!found) { throw new NoSuchMethodException("Expected setter named '" + methodName + "' for var '" + entry.getKey() + "'"); } } } return instance; }
java
{ "resource": "" }
q5652
WorkerImpl.checkQueues
train
protected static void checkQueues(final Iterable<String> queues) { if (queues == null) { throw new IllegalArgumentException("queues must not be null"); } for (final String queue : queues) { if (queue == null || "".equals(queue)) { throw new IllegalArgumentException("queues' members must not be null: " + queues); } } }
java
{ "resource": "" }
q5653
WorkerImpl.failMsg
train
protected String failMsg(final Throwable thrwbl, final String queue, final Job job) throws IOException { final JobFailure failure = new JobFailure(); failure.setFailedAt(new Date()); failure.setWorker(this.name); failure.setQueue(queue); failure.setPayload(job); failure.setThrowable(thrwbl); return ObjectMapperFactory.get().writeValueAsString(failure); }
java
{ "resource": "" }
q5654
WorkerImpl.statusMsg
train
protected String statusMsg(final String queue, final Job job) throws IOException { final WorkerStatus status = new WorkerStatus(); status.setRunAt(new Date()); status.setQueue(queue); status.setPayload(job); return ObjectMapperFactory.get().writeValueAsString(status); }
java
{ "resource": "" }
q5655
WorkerImpl.pauseMsg
train
protected String pauseMsg() throws IOException { final WorkerStatus status = new WorkerStatus(); status.setRunAt(new Date()); status.setPaused(isPaused()); return ObjectMapperFactory.get().writeValueAsString(status); }
java
{ "resource": "" }
q5656
WorkerImpl.createName
train
protected String createName() { final StringBuilder buf = new StringBuilder(128); try { buf.append(InetAddress.getLocalHost().getHostName()).append(COLON) .append(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]) // PID .append('-').append(this.workerId).append(COLON).append(JAVA_DYNAMIC_QUEUES); for (final String queueName : this.queueNames) { buf.append(',').append(queueName); } } catch (UnknownHostException uhe) { throw new RuntimeException(uhe); } return buf.toString(); }
java
{ "resource": "" }
q5657
WorkerPool.join
train
@Override public void join(final long millis) throws InterruptedException { for (final Thread thread : this.threads) { thread.join(millis); } }
java
{ "resource": "" }
q5658
AdminImpl.checkChannels
train
protected static void checkChannels(final Iterable<String> channels) { if (channels == null) { throw new IllegalArgumentException("channels must not be null"); } for (final String channel : channels) { if (channel == null || "".equals(channel)) { throw new IllegalArgumentException("channels' members must not be null: " + channels); } } }
java
{ "resource": "" }
q5659
PoolUtils.doWorkInPool
train
public static <V> V doWorkInPool(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) throws Exception { if (pool == null) { throw new IllegalArgumentException("pool must not be null"); } if (work == null) { throw new IllegalArgumentException("work must not be null"); } final V result; final Jedis poolResource = pool.getResource(); try { result = work.doWork(poolResource); } finally { poolResource.close(); } return result; }
java
{ "resource": "" }
q5660
PoolUtils.doWorkInPoolNicely
train
public static <V> V doWorkInPoolNicely(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) { final V result; try { result = doWorkInPool(pool, work); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new RuntimeException(e); } return result; }
java
{ "resource": "" }
q5661
PoolUtils.createJedisPool
train
public static Pool<Jedis> createJedisPool(final Config jesqueConfig, final GenericObjectPoolConfig poolConfig) { if (jesqueConfig == null) { throw new IllegalArgumentException("jesqueConfig must not be null"); } if (poolConfig == null) { throw new IllegalArgumentException("poolConfig must not be null"); } if (jesqueConfig.getMasterName() != null && !"".equals(jesqueConfig.getMasterName()) && jesqueConfig.getSentinels() != null && jesqueConfig.getSentinels().size() > 0) { return new JedisSentinelPool(jesqueConfig.getMasterName(), jesqueConfig.getSentinels(), poolConfig, jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase()); } else { return new JedisPool(poolConfig, jesqueConfig.getHost(), jesqueConfig.getPort(), jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase()); } }
java
{ "resource": "" }
q5662
AbstractClient.doEnqueue
train
public static void doEnqueue(final Jedis jedis, final String namespace, final String queue, final String jobJson) { jedis.sadd(JesqueUtils.createKey(namespace, QUEUES), queue); jedis.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson); }
java
{ "resource": "" }
q5663
AbstractClient.doBatchEnqueue
train
public static void doBatchEnqueue(final Jedis jedis, final String namespace, final String queue, final List<String> jobJsons) { Pipeline pipelined = jedis.pipelined(); pipelined.sadd(JesqueUtils.createKey(namespace, QUEUES), queue); for (String jobJson : jobJsons) { pipelined.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson); } pipelined.sync(); }
java
{ "resource": "" }
q5664
AbstractClient.doPriorityEnqueue
train
public static void doPriorityEnqueue(final Jedis jedis, final String namespace, final String queue, final String jobJson) { jedis.sadd(JesqueUtils.createKey(namespace, QUEUES), queue); jedis.lpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson); }
java
{ "resource": "" }
q5665
AbstractClient.doAcquireLock
train
public static boolean doAcquireLock(final Jedis jedis, final String namespace, final String lockName, final String lockHolder, final int timeout) { final String key = JesqueUtils.createKey(namespace, lockName); // If lock already exists, extend it String existingLockHolder = jedis.get(key); if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) { if (jedis.expire(key, timeout) == 1) { existingLockHolder = jedis.get(key); if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) { return true; } } } // Check to see if the key exists and is expired for cleanup purposes if (jedis.exists(key) && (jedis.ttl(key) < 0)) { // It is expired, but it may be in the process of being created, so // sleep and check again try { Thread.sleep(2000); } catch (InterruptedException ie) { } // Ignore interruptions if (jedis.ttl(key) < 0) { existingLockHolder = jedis.get(key); // If it is our lock mark the time to live if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) { if (jedis.expire(key, timeout) == 1) { existingLockHolder = jedis.get(key); if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) { return true; } } } else { // The key is expired, whack it! jedis.del(key); } } else { // Someone else locked it while we were sleeping return false; } } // Ignore the cleanup steps above, start with no assumptions test // creating the key if (jedis.setnx(key, lockHolder) == 1) { // Created the lock, now set the expiration if (jedis.expire(key, timeout) == 1) { // Set the timeout existingLockHolder = jedis.get(key); if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) { return true; } } else { // Don't know why it failed, but for now just report failed // acquisition return false; } } // Failed to create the lock return false; }
java
{ "resource": "" }
q5666
ConfigBuilder.withHost
train
public ConfigBuilder withHost(final String host) { if (host == null || "".equals(host)) { throw new IllegalArgumentException("host must not be null or empty: " + host); } this.host = host; return this; }
java
{ "resource": "" }
q5667
ConfigBuilder.withSentinels
train
public ConfigBuilder withSentinels(final Set<String> sentinels) { if (sentinels == null || sentinels.size() < 1) { throw new IllegalArgumentException("sentinels is null or empty: " + sentinels); } this.sentinels = sentinels; return this; }
java
{ "resource": "" }
q5668
ConfigBuilder.withMasterName
train
public ConfigBuilder withMasterName(final String masterName) { if (masterName == null || "".equals(masterName)) { throw new IllegalArgumentException("masterName is null or empty: " + masterName); } this.masterName = masterName; return this; }
java
{ "resource": "" }
q5669
JedisUtils.ensureJedisConnection
train
public static boolean ensureJedisConnection(final Jedis jedis) { final boolean jedisOK = testJedisConnection(jedis); if (!jedisOK) { try { jedis.quit(); } catch (Exception e) { } // Ignore try { jedis.disconnect(); } catch (Exception e) { } // Ignore jedis.connect(); } return jedisOK; }
java
{ "resource": "" }
q5670
JedisUtils.reconnect
train
public static boolean reconnect(final Jedis jedis, final int reconAttempts, final long reconnectSleepTime) { int i = 1; do { try { jedis.disconnect(); try { Thread.sleep(reconnectSleepTime); } catch (Exception e2) { } jedis.connect(); } catch (JedisConnectionException jce) { } // Ignore bad connection attempts catch (Exception e3) { LOG.error("Unknown Exception while trying to reconnect to Redis", e3); } } while (++i <= reconAttempts && !testJedisConnection(jedis)); return testJedisConnection(jedis); }
java
{ "resource": "" }
q5671
JedisUtils.isRegularQueue
train
public static boolean isRegularQueue(final Jedis jedis, final String key) { return LIST.equalsIgnoreCase(jedis.type(key)); }
java
{ "resource": "" }
q5672
JedisUtils.isDelayedQueue
train
public static boolean isDelayedQueue(final Jedis jedis, final String key) { return ZSET.equalsIgnoreCase(jedis.type(key)); }
java
{ "resource": "" }
q5673
JedisUtils.isKeyUsed
train
public static boolean isKeyUsed(final Jedis jedis, final String key) { return !NONE.equalsIgnoreCase(jedis.type(key)); }
java
{ "resource": "" }
q5674
JedisUtils.canUseAsDelayedQueue
train
public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) { final String type = jedis.type(key); return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type)); }
java
{ "resource": "" }
q5675
SessionManager.createNamespace
train
public void createNamespace() { Map<String, String> namespaceAnnotations = annotationProvider.create(session.getId(), Constants.RUNNING_STATUS); if (namespaceService.exists(session.getNamespace())) { //namespace exists } else if (configuration.isNamespaceLazyCreateEnabled()) { namespaceService.create(session.getNamespace(), namespaceAnnotations); } else { throw new IllegalStateException("Namespace [" + session.getNamespace() + "] doesn't exist and lazily creation of namespaces is disabled. " + "Either use an existing one, or set `namespace.lazy.enabled` to true."); } }
java
{ "resource": "" }
q5676
KuberntesServiceUrlResourceProvider.getPort
train
private static int getPort(Service service, Annotation... qualifiers) { for (Annotation q : qualifiers) { if (q instanceof Port) { Port port = (Port) q; if (port.value() > 0) { return port.value(); } } } ServicePort servicePort = findQualifiedServicePort(service, qualifiers); if (servicePort != null) { return servicePort.getPort(); } return 0; }
java
{ "resource": "" }
q5677
KuberntesServiceUrlResourceProvider.getContainerPort
train
private static int getContainerPort(Service service, Annotation... qualifiers) { for (Annotation q : qualifiers) { if (q instanceof Port) { Port port = (Port) q; if (port.value() > 0) { return port.value(); } } } ServicePort servicePort = findQualifiedServicePort(service, qualifiers); if (servicePort != null) { return servicePort.getTargetPort().getIntVal(); } return 0; }
java
{ "resource": "" }
q5678
KuberntesServiceUrlResourceProvider.getScheme
train
private static String getScheme(Service service, Annotation... qualifiers) { for (Annotation q : qualifiers) { if (q instanceof Scheme) { return ((Scheme) q).value(); } } if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) { String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME); if (s != null && s.isEmpty()) { return s; } } return DEFAULT_SCHEME; }
java
{ "resource": "" }
q5679
KuberntesServiceUrlResourceProvider.getPath
train
private static String getPath(Service service, Annotation... qualifiers) { for (Annotation q : qualifiers) { if (q instanceof Scheme) { return ((Scheme) q).value(); } } if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) { String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME); if (s != null && s.isEmpty()) { return s; } } return DEFAULT_PATH; }
java
{ "resource": "" }
q5680
KuberntesServiceUrlResourceProvider.getRandomPod
train
private static Pod getRandomPod(KubernetesClient client, String name, String namespace) { Endpoints endpoints = client.endpoints().inNamespace(namespace).withName(name).get(); List<String> pods = new ArrayList<>(); if (endpoints != null) { for (EndpointSubset subset : endpoints.getSubsets()) { for (EndpointAddress address : subset.getAddresses()) { if (address.getTargetRef() != null && POD.equals(address.getTargetRef().getKind())) { String pod = address.getTargetRef().getName(); if (pod != null && !pod.isEmpty()) { pods.add(pod); } } } } } if (pods.isEmpty()) { return null; } else { String chosen = pods.get(RANDOM.nextInt(pods.size())); return client.pods().inNamespace(namespace).withName(chosen).get(); } }
java
{ "resource": "" }
q5681
Which.classFileUrl
train
public static URL classFileUrl(Class<?> clazz) throws IOException { ClassLoader cl = clazz.getClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } URL res = cl.getResource(clazz.getName().replace('.', '/') + ".class"); if (res == null) { throw new IllegalArgumentException("Unable to locate class file for " + clazz); } return res; }
java
{ "resource": "" }
q5682
Which.decode
train
private static String decode(String s) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == '%') { baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2))); i += 2; continue; } baos.write(ch); } try { return new String(baos.toByteArray(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new Error(e); // impossible } }
java
{ "resource": "" }
q5683
TemplateProcessor.processTemplateResources
train
public List<? super OpenShiftResource> processTemplateResources() { List<? extends OpenShiftResource> resources; final List<? super OpenShiftResource> processedResources = new ArrayList<>(); templates = OpenShiftResourceFactory.getTemplates(getType()); boolean sync_instantiation = OpenShiftResourceFactory.syncInstantiation(getType()); /* Instantiate templates */ for (Template template : templates) { resources = processTemplate(template); if (resources != null) { if (sync_instantiation) { /* synchronous template instantiation */ processedResources.addAll(resources); } else { /* asynchronous template instantiation */ try { delay(openShiftAdapter, resources); } catch (Throwable t) { throw new IllegalArgumentException(asynchronousDelayErrorMessage(), t); } } } } return processedResources; }
java
{ "resource": "" }
q5684
DockerClientExecutor.execStartVerbose
train
public ExecInspection execStartVerbose(String containerId, String... commands) { this.readWriteLock.readLock().lock(); try { String id = execCreate(containerId, commands); CubeOutput output = execStartOutput(id); return new ExecInspection(output, inspectExec(id)); } finally { this.readWriteLock.readLock().unlock(); } }
java
{ "resource": "" }
q5685
OpenShiftResourceFactory.createImageStreamRequest
train
private static String createImageStreamRequest(String name, String version, String image, boolean insecure) { JSONObject imageStream = new JSONObject(); JSONObject metadata = new JSONObject(); JSONObject annotations = new JSONObject(); metadata.put("name", name); annotations.put("openshift.io/image.insecureRepository", insecure); metadata.put("annotations", annotations); // Definition of the image JSONObject from = new JSONObject(); from.put("kind", "DockerImage"); from.put("name", image); JSONObject importPolicy = new JSONObject(); importPolicy.put("insecure", insecure); JSONObject tag = new JSONObject(); tag.put("name", version); tag.put("from", from); tag.put("importPolicy", importPolicy); JSONObject tagAnnotations = new JSONObject(); tagAnnotations.put("version", version); tag.put("annotations", tagAnnotations); JSONArray tags = new JSONArray(); tags.add(tag); // Add image definition to image stream JSONObject spec = new JSONObject(); spec.put("tags", tags); imageStream.put("kind", "ImageStream"); imageStream.put("apiVersion", "v1"); imageStream.put("metadata", metadata); imageStream.put("spec", spec); return imageStream.toJSONString(); }
java
{ "resource": "" }
q5686
OpenShiftResourceFactory.getTemplates
train
static <T> List<Template> getTemplates(T objectType) { try { List<Template> templates = new ArrayList<>(); TEMP_FINDER.findAnnotations(templates, objectType); return templates; } catch (Exception e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q5687
OpenShiftResourceFactory.syncInstantiation
train
static <T> boolean syncInstantiation(T objectType) { List<Template> templates = new ArrayList<>(); Templates tr = TEMP_FINDER.findAnnotations(templates, objectType); if (tr == null) { /* Default to synchronous instantiation */ return true; } else { return tr.syncInstantiation(); } }
java
{ "resource": "" }
q5688
KubernetesAssistant.deployApplication
train
public void deployApplication(String applicationName, String... classpathLocations) throws IOException { final List<URL> classpathElements = Arrays.stream(classpathLocations) .map(classpath -> Thread.currentThread().getContextClassLoader().getResource(classpath)) .collect(Collectors.toList()); deployApplication(applicationName, classpathElements.toArray(new URL[classpathElements.size()])); }
java
{ "resource": "" }
q5689
KubernetesAssistant.deployApplication
train
public void deployApplication(String applicationName, URL... urls) throws IOException { this.applicationName = applicationName; for (URL url : urls) { try (InputStream inputStream = url.openStream()) { deploy(inputStream); } } }
java
{ "resource": "" }
q5690
KubernetesAssistant.deploy
train
public void deploy(InputStream inputStream) throws IOException { final List<? extends HasMetadata> entities = deploy("application", inputStream); if (this.applicationName == null) { Optional<String> deployment = entities.stream() .filter(hm -> hm instanceof Deployment) .map(hm -> (Deployment) hm) .map(rc -> rc.getMetadata().getName()).findFirst(); deployment.ifPresent(name -> this.applicationName = name); } }
java
{ "resource": "" }
q5691
KubernetesAssistant.getServiceUrl
train
public Optional<URL> getServiceUrl(String name) { Service service = client.services().inNamespace(namespace).withName(name).get(); return service != null ? createUrlForService(service) : Optional.empty(); }
java
{ "resource": "" }
q5692
KubernetesAssistant.getServiceUrl
train
public Optional<URL> getServiceUrl() { Optional<Service> optionalService = client.services().inNamespace(namespace) .list().getItems() .stream() .findFirst(); return optionalService .map(this::createUrlForService) .orElse(Optional.empty()); }
java
{ "resource": "" }
q5693
KubernetesAssistant.cleanup
train
public void cleanup() { List<String> keys = new ArrayList<>(created.keySet()); keys.sort(String::compareTo); for (String key : keys) { created.remove(key) .stream() .sorted(Comparator.comparing(HasMetadata::getKind)) .forEach(metadata -> { log.info(String.format("Deleting %s : %s", key, metadata.getKind())); deleteWithRetries(metadata); }); } }
java
{ "resource": "" }
q5694
KubernetesAssistant.awaitPodReadinessOrFail
train
public void awaitPodReadinessOrFail(Predicate<Pod> filter) { await().atMost(5, TimeUnit.MINUTES).until(() -> { List<Pod> list = client.pods().inNamespace(namespace).list().getItems(); return list.stream() .filter(filter) .filter(Readiness::isPodReady) .collect(Collectors.toList()).size() >= 1; } ); }
java
{ "resource": "" }
q5695
DockerRequirement.getDockerVersion
train
private static Version getDockerVersion(String serverUrl) { try { DockerClient client = DockerClientBuilder.getInstance(serverUrl).build(); return client.versionCmd().exec(); } catch (Exception e) { return null; } }
java
{ "resource": "" }
q5696
CubeConfigurator.configure
train
public void configure(@Observes(precedence = -10) ArquillianDescriptor arquillianDescriptor) { Map<String, String> config = arquillianDescriptor.extension(EXTENSION_NAME).getExtensionProperties(); CubeConfiguration cubeConfiguration = CubeConfiguration.fromMap(config); configurationProducer.set(cubeConfiguration); }
java
{ "resource": "" }
q5697
RestAssuredConfigurator.configure
train
public void configure(@Observes(precedence = -200) ArquillianDescriptor arquillianDescriptor) { restAssuredConfigurationInstanceProducer.set( RestAssuredConfiguration.fromMap(arquillianDescriptor .extension("restassured") .getExtensionProperties())); }
java
{ "resource": "" }
q5698
CubeDockerConfigurationResolver.resolve
train
public Map<String, String> resolve(Map<String, String> config) { config = resolveSystemEnvironmentVariables(config); config = resolveSystemDefaultSetup(config); config = resolveDockerInsideDocker(config); config = resolveDownloadDockerMachine(config); config = resolveAutoStartDockerMachine(config); config = resolveDefaultDockerMachine(config); config = resolveServerUriByOperativeSystem(config); config = resolveServerIp(config); config = resolveTlsVerification(config); return config; }
java
{ "resource": "" }
q5699
SeleniumVersionExtractor.fromClassPath
train
public static String fromClassPath() { Set<String> versions = new HashSet<>(); try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> manifests = classLoader.getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { URL manifestURL = manifests.nextElement(); try (InputStream is = manifestURL.openStream()) { Manifest manifest = new Manifest(); manifest.read(is); Attributes buildInfo = manifest.getAttributes("Build-Info"); if (buildInfo != null) { if (buildInfo.getValue("Selenium-Version") != null) { versions.add(buildInfo.getValue("Selenium-Version")); } else { // might be in build-info part if (manifest.getEntries() != null) { if (manifest.getEntries().containsKey("Build-Info")) { final Attributes attributes = manifest.getEntries().get("Build-Info"); if (attributes.getValue("Selenium-Version") != null) { versions.add(attributes.getValue("Selenium-Version")); } } } } } } } } catch (Exception e) { logger.log(Level.WARNING, "Exception {0} occurred while resolving selenium version and latest image is going to be used.", e.getMessage()); return SELENIUM_VERSION; } if (versions.isEmpty()) { logger.log(Level.INFO, "No version of Selenium found in classpath. Using latest image."); return SELENIUM_VERSION; } String foundVersion = versions.iterator().next(); if (versions.size() > 1) { logger.log(Level.WARNING, "Multiple versions of Selenium found in classpath. Using the first one found {0}.", foundVersion); } return foundVersion; }
java
{ "resource": "" }