_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q179800
Observer.getMeters
test
private static List<InvocationMeter> getMeters() { List<InvocationMeter> invocationMeters = new ArrayList<InvocationMeter>(); ContainerSPI container = (ContainerSPI) Factory.getAppFactory(); for (ManagedMethodSPI managedMethod : container.getManagedMethods()) { invocationMeters.add(((ManagedMethod) managedMethod).getMeter()); } return invocationMeters; }
java
{ "resource": "" }
q179801
EventStream.config
test
protected void config(EventStreamConfig config) { if (config.hasSecretKey()) { secretKey = config.getSecretKey(); } if (config.hasKeepAlivePeriod()) { keepAlivePeriod = config.getKeepAlivePeriod(); } parameters = config.getParameters(); }
java
{ "resource": "" }
q179802
EventStream.setRemoteHost
test
protected void setRemoteHost(String remoteHost) { if (string == null) { string = Strings.concat('#', STREAM_ID++, ':', remoteHost); } }
java
{ "resource": "" }
q179803
EventStream.getParameter
test
protected <T> T getParameter(String name, Class<T> type) { if (parameters == null) { throw new BugError("Event stream |%s| parameters not configured.", this); } String value = parameters.get(name); if (value == null) { throw new BugError("Missing event stream parameter |%s| of expected type |%s|.", name, type); } return ConverterRegistry.getConverter().asObject(value, type); }
java
{ "resource": "" }
q179804
FileSystemDirectoryHelper.removePrefix
test
public String removePrefix(final String path, final String prefix) { String pathWithoutPrefix = path; if (pathWithoutPrefix.startsWith(prefix)) { pathWithoutPrefix = pathWithoutPrefix.substring(prefix.length()); while (pathWithoutPrefix.startsWith("/") || pathWithoutPrefix.startsWith("\\")) { pathWithoutPrefix = pathWithoutPrefix.substring(1); } } return pathWithoutPrefix; }
java
{ "resource": "" }
q179805
FileSystemDirectoryHelper.getCommonDir
test
public File getCommonDir(final File dir1, final File dir2) throws IOException { List<File> parts1 = getParentDirs(dir1); List<File> parts2 = getParentDirs(dir2); File matched = null; final int maxCommonSize = Math.min(parts1.size(), parts2.size()); for (int i = 0; i < maxCommonSize; ++i) { if (parts1.get(i).equals(parts2.get(i))) { matched = parts1.get(i); } else { break; } } return matched; }
java
{ "resource": "" }
q179806
FileSystemDirectoryHelper.abs2rel
test
public String abs2rel(final String basePath, final String absPath) { if (!isAbsolutePath(absPath)) { return absPath; } if (isWindowsDrive(absPath) && isWindowsDrive(basePath) && absPath.charAt(0) != basePath.charAt(0)) { return absPath; } StringBuilder result = new StringBuilder(); String[] baseParts = getParts(basePath); String[] absParts = getParts(absPath); // extract common prefix int start = 0; for (int i = 0; i < Math.min(baseParts.length, absParts.length); ++i) { if (baseParts[i].equals(absParts[i])) { start = i + 1; } } for (int i = start; i < baseParts.length; ++i) { if (result.length() > 0) { result.append(File.separator); } result.append(".."); } for (int i = start; i < absParts.length; ++i) { if (result.length() > 0) { result.append(File.separator); } result.append(absParts[i]); } return result.toString(); }
java
{ "resource": "" }
q179807
FileSystemDirectoryHelper.rel2abs
test
public File rel2abs(final String basePath, final String relPath) { String[] baseParts = getParts(basePath); String[] relParts = getParts(relPath); if (isAbsolutePath(relPath)) { return new File(relPath); } List<String> parts = new ArrayList<>(); for (int i = 0; i < baseParts.length; ++i) { if (i > 0 || !isWindowsDrive(basePath)) { parts.add(baseParts[i]); } } for (String part : relParts) { if (part.equals("..") && parts.size() > 0) { parts.remove(parts.size() - 1); } else if (!part.equals(".") && !part.equals("..")) { parts.add(part); } } StringBuilder result = new StringBuilder(); if (isWindowsDrive(basePath)) { result.append(baseParts[0]); } for (String part : parts) { result.append(File.separator); result.append(part); } return new File(result.toString()); }
java
{ "resource": "" }
q179808
FileSystemDirectoryHelper.dirDepth
test
public int dirDepth(final File path) { final String stringPath = path.getPath(); return stringPath.length() - stringPath.replaceAll("[/\\\\]", "").length(); }
java
{ "resource": "" }
q179809
AppServlet.dumpError
test
protected static void dumpError(RequestContext context, Throwable throwable) { log.dump("Error on HTTP request:", throwable); context.dump(); }
java
{ "resource": "" }
q179810
AppServlet.sendJsonObject
test
protected static void sendJsonObject(RequestContext context, Object object, int statusCode) throws IOException { final HttpServletResponse httpResponse = context.getResponse(); if (httpResponse.isCommitted()) { log.fatal("Abort HTTP transaction. Attempt to send JSON object after reponse commited."); return; } log.trace("Send response object |%s|.", object.toString()); Json json = Classes.loadService(Json.class); String buffer = json.stringify(object); byte[] bytes = buffer.getBytes("UTF-8"); httpResponse.setStatus(statusCode); httpResponse.setContentType(ContentType.APPLICATION_JSON.getValue()); httpResponse.setContentLength(bytes.length); httpResponse.setHeader("Content-Language", context.getLocale().toLanguageTag()); httpResponse.getOutputStream().write(bytes); httpResponse.getOutputStream().flush(); }
java
{ "resource": "" }
q179811
ParameterizedTemplateModels.addParamTemplate
test
public final void addParamTemplate(final ParameterizedTemplateModel paramTemplate) { if (paramTemplates == null) { paramTemplates = new ArrayList<ParameterizedTemplateModel>(); } paramTemplates.add(paramTemplate); }
java
{ "resource": "" }
q179812
ParameterizedTemplateModels.addParamTemplates
test
public final void addParamTemplates(final List<ParameterizedTemplateModel> list) { if (list != null) { for (final ParameterizedTemplateModel template : list) { addParamTemplate(template); } } }
java
{ "resource": "" }
q179813
ParameterizedTemplateModels.init
test
public final void init(final SrcGen4JContext context, final Map<String, String> vars) { if (paramTemplates != null) { for (final ParameterizedTemplateModel paramTemplate : paramTemplates) { paramTemplate.init(context, vars); } } }
java
{ "resource": "" }
q179814
ParameterizedTemplateModels.findReferencesTo
test
public final List<ParameterizedTemplateModel> findReferencesTo(final File templateDir, final File templateFile) { final List<ParameterizedTemplateModel> result = new ArrayList<ParameterizedTemplateModel>(); if ((paramTemplates != null) && Utils4J.fileInsideDirectory(templateDir, templateFile)) { for (final ParameterizedTemplateModel paramTemplate : paramTemplates) { if (paramTemplate.hasReferenceTo(templateDir, templateFile)) { result.add(paramTemplate); } } } return result; }
java
{ "resource": "" }
q179815
ElementView.setSaveEnabled
test
public void setSaveEnabled(boolean val) { saveButton.setVisible(val); setReadOnly(!val); entityForm.setReadOnly(!val); }
java
{ "resource": "" }
q179816
ElementView.delete
test
protected void delete() { String question = "Are you sure you want to delete " + getCaption() + "?"; ConfirmDialog.show(getUI(), question, (ConfirmDialog cd) -> { if (cd.isConfirmed()) { try { onDelete(); close(); } catch (IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex) { onError(ex); } catch (RuntimeException ex) { // Must explicitly send unhandled exceptions to error handler. // Would otherwise get swallowed silently within callback handler. getUI().getErrorHandler().error(new com.vaadin.server.ErrorEvent(ex)); } } }); }
java
{ "resource": "" }
q179817
ElementView.onDelete
test
protected void onDelete() throws IOException, IllegalArgumentException, IllegalAccessException, FileNotFoundException, IllegalStateException { endpoint.delete(); eventBus.post(new ElementDeletedEvent<>(endpoint)); }
java
{ "resource": "" }
q179818
LocalInstanceFactory.newInstance
test
@SuppressWarnings("unchecked") @Override public <T> T newInstance(ManagedClassSPI managedClass, Object... args) { Constructor<?> constructor = managedClass.getConstructor(); if (constructor == null) { throw new BugError("Local instance factory cannot instantiate |%s|. Missing constructor.", managedClass); } Object instance = null; try { instance = constructor.newInstance(args); } catch (IllegalArgumentException e) { log.error("Wrong number of arguments or bad types for |%s|: [%s].", constructor, Strings.join(Classes.getParameterTypes(args))); throw e; } catch (InstantiationException e) { // managed class implementation is already validated, i.e. is not abstract and // test for existing constructor is performed... so no obvious reasons for instantiation exception throw new BugError(e); } catch (IllegalAccessException e) { // constructor has accessibility true and class is tested for public access modifier // so there is no reason for illegal access exception throw new BugError(e); } catch (InvocationTargetException e) { log.error("Managed instance constructor |%s| fail due to: %s.", constructor, e.getCause()); throw new InvocationException(e); } if (managedClass.getInstanceType().equals(InstanceType.PROXY)) { // there are two proxy handlers: one transactional and one not // the difference is that transactional proxy handler gets a reference to an external transactional resource ManagedProxyHandler handler = null; if (managedClass.isTransactional()) { TransactionalResource transactionalResource = managedClass.getContainer().getInstance(TransactionalResource.class); handler = new ManagedProxyHandler(transactionalResource, managedClass, instance); } else { handler = new ManagedProxyHandler(managedClass, instance); } final ClassLoader classLoader = managedClass.getImplementationClass().getClassLoader(); final Class<?>[] interfaceClasses = managedClass.getInterfaceClasses(); return (T) Proxy.newProxyInstance(classLoader, interfaceClasses, handler); } return (T) instance; }
java
{ "resource": "" }
q179819
FitResultTable.getFiles
test
public File[] getFiles() { List<File> result = new ArrayList<>(); for (FileCount fileCount : results) { result.add(fileCount.getFile()); } Collections.sort(result, new FitFileComparator()); return result.toArray(new File[result.size()]); }
java
{ "resource": "" }
q179820
FitResultTable.getSummary
test
public Counts getSummary() { Counts result = new Counts(); for (FileCount fileCount : results) { if (fileCount.getCounts() != null) { result.tally(fileCount.getCounts()); } } return result; }
java
{ "resource": "" }
q179821
FitResultTable.getSummaryRow
test
public String getSummaryRow(final File directory) { StringBuilder builder = new StringBuilder(); Counts counts = getSummary(); builder.append("<tr bgcolor=\""); builder.append(color(counts)); builder.append("\"><th style=\"text-align: left\">"); builder.append(directory.getName()); builder.append("</th><th style=\"text-align: left\">"); builder.append(counts.toString()); builder.append("</th></tr>"); return builder.toString(); }
java
{ "resource": "" }
q179822
FitResultTable.getSubSummaryRow
test
public String getSubSummaryRow(final File path) throws IOException { Counts sum = subDirSum(path); return String.format("<tr bgcolor=\"%s\"><th style=\"text-align: left\">%s</th><td>%s</td></tr>", color(sum), FitUtils.htmlSafeFile(dirHelper.abs2rel(new File("").getAbsolutePath(), path.getAbsolutePath())), sum.toString()); }
java
{ "resource": "" }
q179823
ServiceInstanceFactory.newInstance
test
@SuppressWarnings("unchecked") @Override public <I> I newInstance(ManagedClassSPI managedClass, Object... args) { if (args.length > 0) { throw new IllegalArgumentException("Service instances factory does not support arguments."); } Class<?>[] interfaceClasses = managedClass.getInterfaceClasses(); if (interfaceClasses == null) { throw new BugError("Invalid managed class. Null interface classes."); } if (interfaceClasses.length != 1) { throw new BugError("Invalid managed class. It should have exactly one interface class."); } return (I) Classes.loadService(interfaceClasses[0]); }
java
{ "resource": "" }
q179824
XtextParserConfig.getSetupClass
test
public final Class<?> getSetupClass() { if (setupClass != null) { return setupClass; } LOG.info("Creating setup class: {}", setupClassName); try { setupClass = Class.forName(setupClassName, true, context.getClassLoader()); } catch (final ClassNotFoundException ex) { throw new RuntimeException("Couldn't load setup class: " + setupClassName, ex); } return setupClass; }
java
{ "resource": "" }
q179825
XtextParserConfig.getModelDirs
test
public final List<File> getModelDirs() { if ((modelDirs == null) && (modelPath != null)) { modelDirs = paths().stream().filter(XtextParserConfig::isFile).map(XtextParserConfig::asFile).collect(Collectors.toList()); } return modelDirs; }
java
{ "resource": "" }
q179826
XtextParserConfig.getModelResources
test
public final List<URI> getModelResources() { if ((modelResources == null) && (modelPath != null)) { modelResources = new ArrayList<>(); modelResources = paths().stream().filter(XtextParserConfig::isResource).map(XtextParserConfig::asResource) .collect(Collectors.toList()); } return modelResources; }
java
{ "resource": "" }
q179827
EntityPicker.setCandidates
test
public void setCandidates(Collection<T> candidates) { twinColSelect.setContainerDataSource( container = new BeanItemContainer<>(entityType, candidates)); }
java
{ "resource": "" }
q179828
TinyConfigBuilder.loadXML
test
protected static void loadXML(InputStream inputStream, Loader loader) throws ConfigException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(loader); reader.parse(new InputSource(inputStream)); } catch (Exception e) { throw new ConfigException("Fail to load configuration document from file |%s|: %s", inputStream, e); } }
java
{ "resource": "" }
q179829
AbstractEndpointView.onError
test
protected void onError(Exception ex) { Notification.show("Error", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE); }
java
{ "resource": "" }
q179830
QueryParametersParser.isObject
test
private static boolean isObject(Type[] formalParameters) { if (formalParameters.length != 1) { return false; } final Type type = formalParameters[0]; if (!(type instanceof Class)) { return false; } if (Types.isPrimitive(type)) { return false; } if (Types.isArrayLike(type)) { return false; } if (Types.isMap(type)) { return false; } if (ConverterRegistry.hasType(type)) { return false; } return true; }
java
{ "resource": "" }
q179831
JsonArgumentsReader.read
test
@Override public Object[] read(HttpServletRequest httpRequest, Type[] formalParameters) throws IOException, IllegalArgumentException { JsonReader reader = new JsonReader(httpRequest.getInputStream(), expectedStartSequence(formalParameters)); try { return json.parse(reader, formalParameters); } catch (JsonException e) { throw new IllegalArgumentException(e.getMessage()); } finally { reader.close(); } }
java
{ "resource": "" }
q179832
JsonArgumentsReader.read
test
@Override public Object read(InputStream inputStream, Type type) throws IOException { try { return json.parse(new InputStreamReader(inputStream, "UTF-8"), type); } catch (JsonException | ClassCastException | UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage()); } }
java
{ "resource": "" }
q179833
FitUtils.extractCellParameter
test
public static String extractCellParameter(FitCell cell) { final Matcher matcher = PARAMETER_PATTERN.matcher(cell.getFitValue()); if (matcher.matches()) { cell.setFitValue(matcher.group(1)); return matcher.group(2); } else { return null; } }
java
{ "resource": "" }
q179834
TypedQueryAccessor.getHints
test
@Override public java.util.Map<java.lang.String, java.lang.Object> getHints() { return this.q.getHints(); }
java
{ "resource": "" }
q179835
HttpHeader.isXHR
test
public static boolean isXHR(HttpServletRequest httpRequest) { String requestedWith = httpRequest.getHeader(X_REQUESTED_WITH); return requestedWith != null ? requestedWith.equalsIgnoreCase(XML_HTTP_REQUEST) : false; }
java
{ "resource": "" }
q179836
HttpHeader.isAndroid
test
public static boolean isAndroid(HttpServletRequest httpRequest) { String requestedWith = httpRequest.getHeader(X_REQUESTED_WITH); return requestedWith != null ? requestedWith.equalsIgnoreCase(ANDROID_USER_AGENT) : false; }
java
{ "resource": "" }
q179837
AbstractCollectionView.handle
test
@Subscribe public void handle(ElementEvent<TEntity> message) { if (message.getEndpoint().getEntityType() == this.endpoint.getEntityType()) { refresh(); } }
java
{ "resource": "" }
q179838
BeanUtils.getPropertiesWithAnnotation
test
public static <TAnnotation extends Annotation> List<PropertyDescriptor> getPropertiesWithAnnotation(Class<?> beanType, Class<TAnnotation> annotationType) { LinkedList<PropertyDescriptor> result = new LinkedList<>(); getProperties(beanType).forEach(property -> { if (property.getReadMethod() != null && property.getReadMethod().getAnnotation(annotationType) != null || isFieldAnnotated(beanType, property.getName(), annotationType)) { result.add(property); } }); return result; }
java
{ "resource": "" }
q179839
BeanUtils.getAnnotation
test
public static <TAnnotation extends Annotation> Optional<TAnnotation> getAnnotation(Class<?> beanType, PropertyDescriptor property, Class<TAnnotation> annotationType) { Optional<TAnnotation> annotation = stream(property.getReadMethod().getAnnotationsByType(annotationType)).findAny(); return annotation.isPresent() ? annotation : getAnnotationOnField(beanType, property.getName(), annotationType); }
java
{ "resource": "" }
q179840
Server.log
test
private static String log(String message, Object... args) { message = String.format(message, args); java.util.logging.Logger.getLogger(Server.class.getCanonicalName()).log(java.util.logging.Level.SEVERE, message); return message; }
java
{ "resource": "" }
q179841
JRubyWhois.lookup
test
public WhoisResult lookup(String domain, int timeout) { container.put("domain", domain); container.put("timeout_param", timeout); try { return (WhoisResult) container.runScriptlet( JRubyWhois.class.getResourceAsStream("jruby-whois.rb"), "jruby-whois.rb"); } catch (EvalFailedException e) { if (e.getMessage().startsWith("(ServerNotFound)")) { throw new ServerNotFoundException(e); } if (e.getMessage().startsWith("(WebInterfaceError")) { throw new WebInterfaceErrorException(e); } throw e; } }
java
{ "resource": "" }
q179842
JRubyWhois.hasParserForWhoisHost
test
public boolean hasParserForWhoisHost(String whoisHost) { container.put("host", whoisHost); return (Boolean) container.runScriptlet( JRubyWhois.class.getResourceAsStream("jruby-has-parser.rb"), "jruby-has-parser.rb"); }
java
{ "resource": "" }
q179843
HttpRmiServlet.getManagedClass
test
private static ManagedClassSPI getManagedClass(ContainerSPI container, String interfaceName, String requestURI) throws ClassNotFoundException { Class<?> interfaceClass = Classes.forOptionalName(interfaceName); if (interfaceClass == null) { log.error("HTTP-RMI request for not existing class |%s|.", interfaceName); throw new ClassNotFoundException(requestURI); } ManagedClassSPI managedClass = container.getManagedClass(interfaceClass); if (managedClass == null) { log.error("HTTP-RMI request for not existing managed class |%s|.", interfaceName); throw new ClassNotFoundException(requestURI); } if (!managedClass.isRemotelyAccessible()) { log.error("HTTP-RMI request for local managed class |%s|. See @Remote annotation.", interfaceName); throw new ClassNotFoundException(requestURI); } return managedClass; }
java
{ "resource": "" }
q179844
HttpRmiServlet.getManagedMethod
test
private static ManagedMethodSPI getManagedMethod(ManagedClassSPI managedClass, String methodName, String requestURI) throws NoSuchMethodException { ManagedMethodSPI managedMethod = managedClass.getNetMethod(methodName); if (managedMethod == null) { log.error("HTTP-RMI request for not existing managed method |%s#%s|.", managedClass.getInterfaceClass().getName(), methodName); throw new NoSuchMethodException(requestURI); } if (!managedMethod.isRemotelyAccessible()) { log.error("HTTP-RMI request for local managed method |%s#%s|. See @Remote annotation.", managedClass.getInterfaceClass().getName(), methodName); throw new NoSuchMethodException(requestURI); } if (Types.isKindOf(managedMethod.getReturnType(), Resource.class)) { log.error("HTTP-RMI request for managed method |%s#%s| returning a resource.", managedClass.getInterfaceClass().getName(), methodName); throw new NoSuchMethodException(requestURI); } return managedMethod; }
java
{ "resource": "" }
q179845
LogEventAnalyzer.processNotContainsException
test
public void processNotContainsException(Map<String, String> parameters) { LoggingEvent match = getMessageWithException(parameters); if (match == null) { cell.right(); } else { cell.wrong(match.getThrowableInformation().getThrowableStrRep()[0]); } }
java
{ "resource": "" }
q179846
LogEventAnalyzer.processNotContains
test
public void processNotContains(Map<String, String> parameters) { LoggingEvent match = getMessageWithString(parameters); if (match == null) { cell.right(); } else { cell.wrong(match.getMessage().toString()); } }
java
{ "resource": "" }
q179847
ResultSetImpl.getBoolean2
test
public Boolean getBoolean2(String columnLabel) throws java.sql.SQLException { boolean value = this.rs.getBoolean(columnLabel); return !this.rs.wasNull() ? value : null; }
java
{ "resource": "" }
q179848
ResultSetImpl.isWrapperFor
test
@Override public boolean isWrapperFor(java.lang.Class<?> arg0) throws java.sql.SQLException { return this.rs.isWrapperFor(arg0); }
java
{ "resource": "" }
q179849
AbstractView.serialize
test
@Override public void serialize(HttpServletResponse httpResponse) throws IOException { httpResponse.setHeader(HttpHeader.CACHE_CONTROL, HttpHeader.NO_CACHE); httpResponse.addHeader(HttpHeader.CACHE_CONTROL, HttpHeader.NO_STORE); httpResponse.setHeader(HttpHeader.PRAGMA, HttpHeader.NO_CACHE); httpResponse.setDateHeader(HttpHeader.EXPIRES, 0); httpResponse.setContentType(getContentType().getValue()); serialize(httpResponse.getOutputStream()); }
java
{ "resource": "" }
q179850
Cookies.get
test
public String get(String name) { Params.notNullOrEmpty(name, "Cookie name"); if (cookies == null) { return null; } for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } return null; }
java
{ "resource": "" }
q179851
Cookies.add
test
public void add(String name, String value) { Params.notNullOrEmpty(name, "Cookie name"); Params.notNull(value, "Cookie value"); Cookie cookie = new Cookie(name, value); cookie.setPath("/"); httpResponse.addCookie(cookie); }
java
{ "resource": "" }
q179852
Cookies.remove
test
public void remove(String name) { Params.notNullOrEmpty(name, "Cookie name"); if (cookies == null) { return; } for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { cookie.setMaxAge(0); cookie.setValue(""); cookie.setPath("/"); httpResponse.addCookie(cookie); break; } } }
java
{ "resource": "" }
q179853
Cookies.iterator
test
public Iterator<Cookie> iterator() { if (cookies == null) { return Collections.emptyIterator(); } return Arrays.asList(cookies).iterator(); }
java
{ "resource": "" }
q179854
TargetFileListProducerConfig.getTargetFileListProducer
test
public final TargetFileListProducer getTargetFileListProducer() { if (tflProducer != null) { return tflProducer; } final Object obj = Utils4J.createInstance(className); if (!(obj instanceof TargetFileListProducer)) { throw new IllegalStateException( "Expected class to be of type '" + TargetFileListProducer.class.getName() + "', but was: " + className); } tflProducer = (TargetFileListProducer) obj; return tflProducer; }
java
{ "resource": "" }
q179855
DynamicObjectFactory.add
test
public void add(final Class<?> type, final String name) throws ClassNotFoundException { FieldGen fg; if (result != null) { throw new IllegalStateException("Class already generated"); } fg = new FieldGen(Constants.ACC_PUBLIC | Constants.ACC_SUPER, Type.getType(type), name, cg.getConstantPool()); cg.addField(fg.getField()); }
java
{ "resource": "" }
q179856
DynamicObjectFactory.compile
test
public final Class<?> compile() { if (result == null) { loader.loadJavaClass(cg.getClassName(), cg.getJavaClass()); try { result = loader.loadClass(cg.getClassName()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } return result; }
java
{ "resource": "" }
q179857
Challenge.verifyResponse
test
public boolean verifyResponse(String token) throws NullPointerException { return value.equals(getValue(tokenedImageFiles.get(token))); }
java
{ "resource": "" }
q179858
Challenge.getValue
test
private static String getValue(File file) throws NullPointerException { if (file == null) { return null; } return file.getName().toLowerCase().replaceAll(EXTENSION_REX, "").replaceAll(NOT_LETTERS_REX, " "); }
java
{ "resource": "" }
q179859
URIUtils.ensureTrailingSlash
test
@SneakyThrows public static URI ensureTrailingSlash(URI uri) { URIBuilder builder = new URIBuilder(uri); if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } return builder.build(); }
java
{ "resource": "" }
q179860
TinyContainer.login
test
@Override public boolean login(String username, String password) { try { getHttpServletRequest().login(username, password); } catch (ServletException e) { // exception is thrown if request is already authenticated, servlet container authentication is not enabled or // credentials are not accepted // consider all these conditions as login fail but record the event to application logger log.debug(e); return false; } return true; }
java
{ "resource": "" }
q179861
TinyContainer.getHttpServletRequest
test
private HttpServletRequest getHttpServletRequest() { RequestContext context = getInstance(RequestContext.class); HttpServletRequest request = context.getRequest(); if (request == null) { throw new BugError("Attempt to use not initialized HTTP request."); } return request; }
java
{ "resource": "" }
q179862
ManagedProxyHandler.invoke
test
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final ManagedMethodSPI managedMethod = managedClass.getManagedMethod(method); log.trace("Invoke |%s|.", managedMethod); if (!managedMethod.isTransactional()) { // execute managed method that is not included within transactional boundaries try { return managedMethod.invoke(managedInstance, args); } catch (Throwable t) { throw throwable(t, "Non transactional method |%s| invocation fails.", managedMethod); } } if (managedMethod.isImmutable()) { return executeImmutableTransaction(managedMethod, args); } return executeMutableTransaction(managedMethod, args); }
java
{ "resource": "" }
q179863
ManagedProxyHandler.executeMutableTransaction
test
private Object executeMutableTransaction(ManagedMethodSPI managedMethod, Object[] args) throws Throwable { // store transaction session on current thread via transactional resource utility // it may happen to have multiple nested transaction on current thread // since all are created by the same transactional resource, all are part of the same session // and there is no harm if storeSession is invoked multiple times // also performance penalty is comparable with the effort to prevent this multiple write Transaction transaction = transactionalResource.createTransaction(); transactionalResource.storeSession(transaction.getSession()); try { Object result = managedMethod.invoke(managedInstance, args); transaction.commit(); if (transaction.unused()) { log.debug("Method |%s| superfluously declared transactional.", managedMethod); } return result; } catch (Throwable throwable) { transaction.rollback(); throw throwable(throwable, "Mutable transactional method |%s| invocation fail.", managedMethod); } finally { if (transaction.close()) { // it may happen to have multiple nested transaction on this thread // if this is the case, remove session from current thread only if outermost transaction is closed // of course if not nested transactions, remove at once transactionalResource.releaseSession(); } } }
java
{ "resource": "" }
q179864
ManagedProxyHandler.executeImmutableTransaction
test
private Object executeImmutableTransaction(ManagedMethodSPI managedMethod, Object[] args) throws Throwable { Transaction transaction = transactionalResource.createReadOnlyTransaction(); // see mutable transaction comment transactionalResource.storeSession(transaction.getSession()); try { Object result = managedMethod.invoke(managedInstance, args); if (transaction.unused()) { log.debug("Method |%s| superfluously declared transactional.", managedMethod); } return result; } catch (Throwable throwable) { throw throwable(throwable, "Immutable transactional method |%s| invocation fail.", managedMethod); } finally { if (transaction.close()) { // see mutable transaction comment transactionalResource.releaseSession(); } } }
java
{ "resource": "" }
q179865
FileSelector.getFiles
test
public File[] getFiles() { final File[] files = directory.listFiles(filter); if (files == null) { return new File[0]; } else { return files; } }
java
{ "resource": "" }
q179866
FileSelector.getLastFile
test
public File getLastFile() throws FileNotFoundException { File[] files = directory.listFiles(filter); if (files == null || files.length == 0) { throw new FileNotFoundException(); } return files[files.length - 1]; }
java
{ "resource": "" }
q179867
AbstractParser.getConcreteConfig
test
@SuppressWarnings("unchecked") protected final CONFIG_TYPE getConcreteConfig(final ParserConfig config) { final Config<ParserConfig> cfg = config.getConfig(); if (cfg == null) { throw new IllegalStateException( "The configuration is expected to be of type '" + concreteConfigClass.getName() + "', but was: null"); } else { if (!(concreteConfigClass.isAssignableFrom(cfg.getConfig().getClass()))) { throw new IllegalStateException( "The configuration is expected to be of type '" + concreteConfigClass.getName() + "', but was: " + cfg.getConfig().getClass().getName() + " - Did you add the configuration class to the JXB context?"); } } return (CONFIG_TYPE) cfg.getConfig(); }
java
{ "resource": "" }
q179868
RequestPreprocessor.startsWith
test
private static boolean startsWith(String requestPath, String pathComponent) { if (requestPath.charAt(0) != '/') { return false; } int i = 1; for (int j = 0; i < requestPath.length(); ++i, ++j) { if (requestPath.charAt(i) == '/') { return j == pathComponent.length(); } if (j == pathComponent.length()) { return false; } if (Character.toLowerCase(requestPath.charAt(i)) != Character.toLowerCase(pathComponent.charAt(j))) { return false; } } return false; }
java
{ "resource": "" }
q179869
EMFGeneratorConfig.getFactories
test
@SuppressWarnings("unchecked") @NotNull public final <MODEL> List<ArtifactFactory<MODEL>> getFactories(final Class<MODEL> modelType) { final List<ArtifactFactory<MODEL>> list = new ArrayList<ArtifactFactory<MODEL>>(); if (factories == null) { factories = new ArrayList<ArtifactFactory<?>>(); if (factoryConfigs != null) { for (final ArtifactFactoryConfig factoryConfig : factoryConfigs) { factories.add(factoryConfig.getFactory()); } } } for (final ArtifactFactory<?> factory : factories) { if (modelType.isAssignableFrom(factory.getModelType())) { list.add((ArtifactFactory<MODEL>) factory); } } return list; }
java
{ "resource": "" }
q179870
SessionScopeFactory.getSession
test
private HttpSession getSession(InstanceKey instanceKey) { RequestContext requestContext = appFactory.getInstance(RequestContext.class); HttpServletRequest httpRequest = requestContext.getRequest(); if (httpRequest == null) { throw new BugError("Invalid web context due to null HTTP request. Cannot create managed instance for |%s| with scope SESSION.", instanceKey); } // create HTTP session if missing; accordingly API httpSession is never null if 'create' flag is true return httpRequest.getSession(true); }
java
{ "resource": "" }
q179871
FileResource.serialize
test
@Override public void serialize(HttpServletResponse httpResponse) throws IOException { httpResponse.setHeader(HttpHeader.CACHE_CONTROL, HttpHeader.NO_CACHE); httpResponse.addHeader(HttpHeader.CACHE_CONTROL, HttpHeader.NO_STORE); httpResponse.setHeader(HttpHeader.PRAGMA, HttpHeader.NO_CACHE); httpResponse.setDateHeader(HttpHeader.EXPIRES, 0); httpResponse.setContentType(contentType); httpResponse.setHeader(HttpHeader.CONTENT_LENGTH, Long.toString(file.length())); Files.copy(file, httpResponse.getOutputStream()); }
java
{ "resource": "" }
q179872
EntryEndpoint.readMeta
test
public void readMeta() throws IOException, IllegalArgumentException, IllegalAccessException, FileNotFoundException, IllegalStateException { executeAndHandle(Request.Get(uri)); }
java
{ "resource": "" }
q179873
ResourceServlet.handleRequest
test
@Override protected void handleRequest(RequestContext context) throws ServletException, IOException { // for exceptions generated before response commit uses HttpServletResponse.sendError // on send error, servlet container prepares error response using container internal HTML for response body // if <error-page> is configured into deployment descriptor servlet container uses that HTML for response body final HttpServletRequest httpRequest = context.getRequest(); final HttpServletResponse httpResponse = context.getResponse(); ArgumentsReader argumentsReader = null; Resource resource = null; try { ManagedMethodSPI method = resourceMethods.get(key(context.getRequestPath())); if (method == null) { throw new NoSuchMethodException(httpRequest.getRequestURI()); } final Type[] formalParameters = method.getParameterTypes(); argumentsReader = argumentsReaderFactory.getArgumentsReader(httpRequest, formalParameters); Object[] arguments = argumentsReader.read(httpRequest, formalParameters); Object controller = container.getInstance(method.getDeclaringClass()); resource = method.invoke(controller, arguments); if (resource == null) { throw new BugError("Null resource |%s|.", httpRequest.getRequestURI()); } } catch (AuthorizationException e) { // at this point, resource is private and need to redirect to a login page // if application provides one, tiny container is configured with, and use it // otherwise servlet container should have one // if no login page found send back servlet container error - that could be custom error page, if declared String loginPage = container.getLoginPage(); if (loginPage != null) { httpResponse.sendRedirect(loginPage); } else { // expected servlet container behavior: // if <login-config> section exist into web.xml do what is configured there // else send back internal page with message about SC_UNAUTHORIZED // authenticate can throw ServletException if fails, perhaps because is not configured // let servlet container handle this error, that could be custom error page is configured httpRequest.authenticate(httpResponse); } return; } catch (NoSuchMethodException | IllegalArgumentException e) { // do not use AppServlet#sendError since it is encoded JSON and for resources need HTML dumpError(context, e); httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, httpRequest.getRequestURI()); return; } catch (InvocationException e) { // do not use AppServlet#sendError since it is encoded JSON and for resources need HTML dumpError(context, e); if (e.getCause() instanceof NoSuchResourceException) { httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, httpRequest.getRequestURI()); } else { httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getCause().getMessage()); } return; } finally { if (argumentsReader != null) { argumentsReader.clean(); } } // once serialization process started response becomes committed // and is not longer possible to use HttpServletResponse#sendError // let servlet container handle IO exceptions but since client already start rendering // there is no so much to do beside closing or reseting connection httpResponse.setStatus(HttpServletResponse.SC_OK); resource.serialize(httpResponse); }
java
{ "resource": "" }
q179874
TableFixture.tearDown
test
@Override public void tearDown() throws Exception { if (statement != null) { statement.close(); statement = null; } super.tearDown(); }
java
{ "resource": "" }
q179875
EventStreamManagerImpl.preDestroy
test
@Override public void preDestroy() { if (eventStreams.isEmpty()) { return; } // EventStream#close signals stream loop that breaks // as a consequence, EventStreamServlet ends current request processing and call this#closeEventStream // this#closeEventStream removes event stream from this#eventStreams list resulting in concurrent change // to cope with this concurrent change uses a temporary array // toArray API is a little confusing for me regarding returned array // to be on safe side let toArray to determine array size // also I presume returned array is not altered by list updates for (EventStream eventStream : eventStreams.toArray(new EventStream[0])) { log.debug("Force close stale event stream |%s|.", eventStream); eventStream.close(); } }
java
{ "resource": "" }
q179876
AbstractBlobView.handleAllowedMethods
test
protected void handleAllowedMethods() { endpoint.isDownloadAllowed().ifPresent(this::setDownloadEnabled); endpoint.isUploadAllowed().ifPresent(this::setUploadEnabled); endpoint.isDeleteAllowed().ifPresent(this::setDeleteEnabled); }
java
{ "resource": "" }
q179877
AbstractBlobView.upload
test
protected void upload() { try { onUpload(); eventBus.post(new BlobUploadEvent(endpoint)); Notification.show("Success", "Upload complete", Notification.Type.TRAY_NOTIFICATION); } catch (IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex) { onError(ex); } }
java
{ "resource": "" }
q179878
AbstractBlobView.delete
test
protected void delete() { String question = "Are you sure you want to delete the data from the server?"; ConfirmDialog.show(getUI(), question, new ConfirmDialog.Listener() { @Override public void onClose(ConfirmDialog cd) { if (cd.isConfirmed()) { try { endpoint.delete(); close(); } catch (IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex) { onError(ex); } catch (RuntimeException ex) { // Must explicitly send unhandled exceptions to error handler. // Would otherwise get swallowed silently within callback handler. getUI().getErrorHandler().error(new com.vaadin.server.ErrorEvent(ex)); } } } }); }
java
{ "resource": "" }
q179879
Fixture.extractColumnParameters
test
protected String[] extractColumnParameters(FitRow row) { final List<String> result = new ArrayList<>(); for (FitCell cell : row.cells()) { result.add(FitUtils.extractCellParameter(cell)); } return result.toArray(new String[result.size()]); }
java
{ "resource": "" }
q179880
Fixture.getArgNames
test
protected String[] getArgNames() { if (args == null) { return new String[]{}; } return args.keySet().toArray(new String[args.keySet().size()]); }
java
{ "resource": "" }
q179881
Timer.period
test
public synchronized void period(final PeriodicTask periodicTask, long period) { TimerTask task = new PeriodicTaskImpl(periodicTask); this.tasks.put(periodicTask, task); this.timer.schedule(task, 0L, period); }
java
{ "resource": "" }
q179882
Timer.timeout
test
public synchronized void timeout(final TimeoutTask timeoutTask, long timeout) { TimerTask task = this.tasks.get(timeoutTask); if (task != null) { task.cancel(); this.tasks.values().remove(task); } task = new TimeoutTaskImpl(timeoutTask); this.tasks.put(timeoutTask, task); this.timer.schedule(task, timeout); }
java
{ "resource": "" }
q179883
ViewManagerImpl.config
test
@Override public void config(Config config) throws ConfigException, IOException { for (Config repositorySection : config.findChildren("repository")) { // view manager configuration section is named <views> // a <views> configuration section has one or many <repository> child sections // scan every repository files accordingly files pattern and add meta views to views meta pool // load repository view implementation class and perform insanity checks String className = repositorySection.getAttribute("class", DEF_IMPLEMENTATION); Class<?> implementation = Classes.forOptionalName(className); if (implementation == null) { throw new ConfigException("Unable to load view implementation |%s|.", className); } if (!Types.isKindOf(implementation, View.class)) { throw new ConfigException("View implementation |%s| is not of proper type.", className); } if (!Classes.isInstantiable(implementation)) { throw new ConfigException("View implementation |%s| is not instantiable. Ensure is not abstract or interface and have default constructor.", implementation); } @SuppressWarnings("unchecked") Class<? extends View> viewImplementation = (Class<? extends View>) implementation; // load repository path and files pattern and create I18N repository instance String repositoryPath = repositorySection.getAttribute("path"); if (repositoryPath == null) { throw new ConfigException("Invalid views repository configuration. Missing <path> attribute."); } String filesPattern = repositorySection.getAttribute("files-pattern"); if (filesPattern == null) { throw new ConfigException("Invalid views repository configuration. Missing <files-pattern> attribute."); } ConfigBuilder builder = new I18nRepository.ConfigBuilder(repositoryPath, filesPattern); I18nRepository repository = new I18nRepository(builder.build()); if (viewsMetaPool == null) { // uses first repository to initialize i18n pool // limitation for this solution is that all repositories should be the kind: locale sensitive or not viewsMetaPool = repository.getPoolInstance(); } Properties properties = repositorySection.getProperties(); // traverses all files from I18N repository instance and register view meta instance // builder is used by view meta to load the document template for (I18nFile template : repository) { ViewMeta meta = new ViewMeta(template.getFile(), viewImplementation, properties); if (viewsMetaPool.put(meta.getName(), meta, template.getLocale())) { log.warn("Override view |%s|", meta); } else { log.debug("Register view |%s|", meta); } } } }
java
{ "resource": "" }
q179884
RecursiveFileSelector.next
test
@Override public final File next() { if (files == null || fileIndex >= files.length) { if (!cacheNext()) { throw new NoSuchElementException(); } } return files[fileIndex++]; }
java
{ "resource": "" }
q179885
Launcher.configureApplication
test
private static void configureApplication() { // Try to load the file. File file = new File("chameria.props"); if (file.exists()) { Properties props = new Properties(); InputStream is = null; try { is = new FileInputStream(file); props.load(is); String n = props.getProperty("application.name"); if (n != null) { QApplication.setApplicationName(n); } else { QApplication.setApplicationName("akquinet ChameRIA"); } n = props.getProperty("application.version"); if (n != null) { QApplication.setApplicationVersion(n); } n = props.getProperty("application.icon"); if (n != null) { QIcon icon = new QIcon(n); QApplication.setWindowIcon(icon); } } catch (Exception e) { System.err.println("Cannot read the application configuration " + e.getMessage()); e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignored } } } } QApplication.setOrganizationName("akquinet A.G."); }
java
{ "resource": "" }
q179886
Launcher.printWelcomeBanner
test
private static void printWelcomeBanner() { StringBuffer banner = new StringBuffer(); banner.append("\n"); banner.append("\t============================\n"); banner.append("\t| |\n"); banner.append("\t| Welcome to ChameRIA |\n"); banner.append("\t| |\n"); banner.append("\t============================\n"); banner.append("\n"); System.out.println(banner); }
java
{ "resource": "" }
q179887
Launcher.printStoppedBanner
test
private static void printStoppedBanner() { System.out.println("\n"); System.out.println("\t========================="); System.out.println("\t| ChameRIA stopped |"); System.out.println("\t========================="); System.out.println("\n"); }
java
{ "resource": "" }
q179888
Launcher.createChameleon
test
public static ChameRIA createChameleon(String[] args) throws Exception { boolean debug = isDebugModeEnabled(args); String core = getCore(args); String app = getApp(args); String runtime = getRuntime(args); String fileinstall = getDeployDirectory(args); String config = getProps(args); if (config == null || ! new File(config).exists()) { return new ChameRIA(core, debug, app, runtime, fileinstall, null); } else { return new ChameRIA(core, debug, app, runtime, fileinstall, config); } }
java
{ "resource": "" }
q179889
Launcher.registerShutdownHook
test
private static void registerShutdownHook(final ChameRIA chameleon) { Runtime runtime = Runtime.getRuntime(); Runnable hook = new Runnable() { public void run() { try { if (chameleon != null) { chameleon.stop(); printStoppedBanner(); } } catch (BundleException e) { System.err.println("Cannot stop Chameleon correctly : " + e.getMessage()); } catch (InterruptedException e) { System.err.println("Unexpected Exception : " + e.getMessage()); // nothing to do } } }; runtime.addShutdownHook(new Thread(hook)); }
java
{ "resource": "" }
q179890
ActionView.trigger
test
public void trigger() { try { onTrigger(); Notification.show(getCaption(), "Successful.", Notification.Type.TRAY_NOTIFICATION); } catch (IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex) { onError(ex); } }
java
{ "resource": "" }
q179891
ActionView.onTrigger
test
protected void onTrigger() throws IOException, IllegalArgumentException, IllegalAccessException, FileNotFoundException, IllegalStateException { endpoint.trigger(); eventBus.post(new TriggerEvent(endpoint)); }
java
{ "resource": "" }
q179892
FitParseResult.insertAndReplace
test
public void insertAndReplace(final FitRow row) { if (results.isEmpty()) { return; } int index = row.getIndex(); FitTable table = row.getTable(); table.remove(index); addRows(table, index); }
java
{ "resource": "" }
q179893
FitParseResult.getCounts
test
public Counts getCounts() { Counts counts = new Counts(); for (FileCount fileCount : results) { counts.tally(fileCount.getCounts()); } return counts; }
java
{ "resource": "" }
q179894
Summary.setScore
test
public void setScore(double v) { if (Summary_Type.featOkTst && ((Summary_Type)jcasType).casFeat_score == null) jcasType.jcas.throwFeatMissing("score", "edu.cmu.lti.oaqa.type.answer.Summary"); jcasType.ll_cas.ll_setDoubleValue(addr, ((Summary_Type)jcasType).casFeatCode_score, v);}
java
{ "resource": "" }
q179895
Summary.getVariants
test
public StringList getVariants() { if (Summary_Type.featOkTst && ((Summary_Type)jcasType).casFeat_variants == null) jcasType.jcas.throwFeatMissing("variants", "edu.cmu.lti.oaqa.type.answer.Summary"); return (StringList)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((Summary_Type)jcasType).casFeatCode_variants)));}
java
{ "resource": "" }
q179896
Summary.setVariants
test
public void setVariants(StringList v) { if (Summary_Type.featOkTst && ((Summary_Type)jcasType).casFeat_variants == null) jcasType.jcas.throwFeatMissing("variants", "edu.cmu.lti.oaqa.type.answer.Summary"); jcasType.ll_cas.ll_setRefValue(addr, ((Summary_Type)jcasType).casFeatCode_variants, jcasType.ll_cas.ll_getFSRef(v));}
java
{ "resource": "" }
q179897
Question.getQuestionType
test
public String getQuestionType() { if (Question_Type.featOkTst && ((Question_Type)jcasType).casFeat_questionType == null) jcasType.jcas.throwFeatMissing("questionType", "edu.cmu.lti.oaqa.type.input.Question"); return jcasType.ll_cas.ll_getStringValue(addr, ((Question_Type)jcasType).casFeatCode_questionType);}
java
{ "resource": "" }
q179898
Question.setQuestionType
test
public void setQuestionType(String v) { if (Question_Type.featOkTst && ((Question_Type)jcasType).casFeat_questionType == null) jcasType.jcas.throwFeatMissing("questionType", "edu.cmu.lti.oaqa.type.input.Question"); jcasType.ll_cas.ll_setStringValue(addr, ((Question_Type)jcasType).casFeatCode_questionType, v);}
java
{ "resource": "" }
q179899
Focus.getToken
test
public Token getToken() { if (Focus_Type.featOkTst && ((Focus_Type)jcasType).casFeat_token == null) jcasType.jcas.throwFeatMissing("token", "edu.cmu.lti.oaqa.type.nlp.Focus"); return (Token)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((Focus_Type)jcasType).casFeatCode_token)));}
java
{ "resource": "" }