_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q171500
FileUtil.cleanDir
test
public static void cleanDir(final File destDir) throws IOException { checkExists(destDir); checkIsDirectory(destDir); File[] files = destDir.listFiles(); if (files == null) { throw new IOException("Failed to list contents of: " + destDir); } IOException exception = null; for (File file : files) { try { if (file.isDirectory()) { deleteDir(file); } else { file.delete(); } } catch (IOException ioex) { exception = ioex; continue; } } if (exception != null) { throw exception; } }
java
{ "resource": "" }
q171501
FileUtil.readUTFChars
test
public static char[] readUTFChars(final File file) throws IOException { checkExists(file); checkIsFile(file); UnicodeInputStream in = unicodeInputStreamOf(file); try { return StreamUtil.readChars(in, detectEncoding(in)); } finally { StreamUtil.close(in); } }
java
{ "resource": "" }
q171502
FileUtil.readChars
test
public static char[] readChars(final File file, final String encoding) throws IOException { checkExists(file); checkIsFile(file); InputStream in = streamOf(file, encoding); try { return StreamUtil.readChars(in, encoding); } finally { StreamUtil.close(in); } }
java
{ "resource": "" }
q171503
FileUtil.writeChars
test
public static void writeChars(final File dest, final char[] data, final String encoding) throws IOException { outChars(dest, data, encoding, false); }
java
{ "resource": "" }
q171504
FileUtil.writeString
test
public static void writeString(final File dest, final String data, final String encoding) throws IOException { outString(dest, data, encoding, false); }
java
{ "resource": "" }
q171505
FileUtil.appendString
test
public static void appendString(final File dest, final String data, final String encoding) throws IOException { outString(dest, data, encoding, true); }
java
{ "resource": "" }
q171506
FileUtil.readBytes
test
public static byte[] readBytes(final File file, final int count) throws IOException { checkExists(file); checkIsFile(file); long numToRead = file.length(); if (numToRead >= Integer.MAX_VALUE) { throw new IOException("File is larger then max array size"); } if (count > NEGATIVE_ONE && count < numToRead) { numToRead = count; } byte[] bytes = new byte[(int) numToRead]; RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); randomAccessFile.readFully(bytes); randomAccessFile.close(); return bytes; }
java
{ "resource": "" }
q171507
FileUtil.writeBytes
test
public static void writeBytes(final File dest, final byte[] data, final int off, final int len) throws IOException { outBytes(dest, data, off, len, false); }
java
{ "resource": "" }
q171508
FileUtil.appendBytes
test
public static void appendBytes(final File dest, final byte[] data, final int off, final int len) throws IOException { outBytes(dest, data, off, len, true); }
java
{ "resource": "" }
q171509
FileUtil.copy
test
public static void copy(final File src, final File dest) throws IOException { if (src.isDirectory()) { copyDir(src, dest); return; } if (dest.isDirectory()) { copyFileToDir(src, dest); return; } copyFile(src, dest); }
java
{ "resource": "" }
q171510
FileUtil.delete
test
public static void delete(final File dest) throws IOException { if (dest.isDirectory()) { deleteDir(dest); return; } deleteFile(dest); }
java
{ "resource": "" }
q171511
FileUtil.createTempDirectory
test
public static File createTempDirectory(final String prefix, final String suffix, final File tempDir) throws IOException { File file = createTempFile(prefix, suffix, tempDir); file.delete(); file.mkdir(); return file; }
java
{ "resource": "" }
q171512
FileUtil.isBinary
test
public static boolean isBinary(final File file) throws IOException { byte[] bytes = readBytes(file, 128); for (byte b : bytes) { if (b < 32 && b != 9 && b != 10 && b != 13) { return true; } } return false; }
java
{ "resource": "" }
q171513
FileUtil.checkDirCopy
test
private static void checkDirCopy(final File srcDir, final File destDir) throws IOException { checkExists(srcDir); checkIsDirectory(srcDir); if (equals(srcDir, destDir)) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are equal"); } }
java
{ "resource": "" }
q171514
FileUtil.checkFileCopy
test
private static void checkFileCopy(final File srcFile, final File destFile) throws IOException { checkExists(srcFile); checkIsFile(srcFile); if (equals(srcFile, destFile)) { throw new IOException("Files '" + srcFile + "' and '" + destFile + "' are equal"); } File destParent = destFile.getParentFile(); if (destParent != null && !destParent.exists()) { checkCreateDirectory(destParent); } }
java
{ "resource": "" }
q171515
Cli.printUsage
test
public void printUsage(final String commandName) { final StringBuilder usage = new StringBuilder(commandName); for (final Option option : options) { if (option.shortName != null) { usage.append(" [-").append(option.shortName).append("]"); } else if (option.longName != null) { usage.append(" [--").append(option.longName).append("]"); } } for (final Param param : params) { usage.append(" ").append(param.label); } System.out.println(usage); }
java
{ "resource": "" }
q171516
ActionsManager.resolveActionMethod
test
public Method resolveActionMethod(final Class<?> actionClass, final String methodName) { MethodDescriptor methodDescriptor = ClassIntrospector.get().lookup(actionClass).getMethodDescriptor(methodName, false); if (methodDescriptor == null) { throw new MadvocException("Public method not found: " + actionClass.getSimpleName() + "#" + methodName); } return methodDescriptor.getMethod(); }
java
{ "resource": "" }
q171517
ActionsManager.registerAction
test
public ActionRuntime registerAction(final Class actionClass, final String actionMethodName, final ActionDefinition actionDefinition) { Method actionMethod = resolveActionMethod(actionClass, actionMethodName); return registerAction(actionClass, actionMethod, actionDefinition); }
java
{ "resource": "" }
q171518
ActionsManager.registerPathAlias
test
public void registerPathAlias(final String alias, final String path) { final String existing = pathAliases.put(alias, path); if (existing != null) { throw new MadvocException("Duplicated alias detected: [" + alias + "] for paths: " + path + ", " + existing); } }
java
{ "resource": "" }
q171519
LoopIterator.next
test
public boolean next() { if (!looping) { return false; } if (last) { return false; } if (count == 0) { value = start; first = true; } else { value += step; first = false; } count++; last = isLastIteration(value + step); return true; }
java
{ "resource": "" }
q171520
CharArraySequence.from
test
public static CharArraySequence from(final char[] value, final int offset, final int len) { final char[] buffer = new char[value.length]; System.arraycopy(value, offset, buffer, 0, len); return new CharArraySequence(buffer); }
java
{ "resource": "" }
q171521
DelegateAdvice.execute
test
public Object execute() throws Exception { String methodName = ProxyTarget.targetMethodName(); Class[] argTypes = ProxyTarget.createArgumentsClassArray(); Object[] args = ProxyTarget.createArgumentsArray(); // lookup method on target object class (and not #targetClass!() Class type = _target.getClass(); Method method = type.getMethod(methodName, argTypes); // remember context classloader ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Object result; try { // change class loader Thread.currentThread().setContextClassLoader(type.getClassLoader()); // invoke result = method.invoke(_target, args); } finally { // return context classloader Thread.currentThread().setContextClassLoader(contextClassLoader); } return ProxyTarget.returnValue(result); }
java
{ "resource": "" }
q171522
Scanner.matchUpperCase
test
public final boolean matchUpperCase(final char[] uppercaseTarget) { if (ndx + uppercaseTarget.length > total) { return false; } int j = ndx; for (int i = 0; i < uppercaseTarget.length; i++, j++) { final char c = CharUtil.toUpperAscii(input[j]); if (c != uppercaseTarget[i]) { return false; } } return true; }
java
{ "resource": "" }
q171523
Scanner.charSequence
test
protected final CharSequence charSequence(final int from, final int to) { if (from == to) { return CharArraySequence.EMPTY; } return CharArraySequence.of(input, from, to - from); }
java
{ "resource": "" }
q171524
ClassPathURLs.of
test
public static URL[] of(ClassLoader classLoader, Class clazz) { if (clazz == null) { clazz = ClassPathURLs.class; } if (classLoader == null) { classLoader = clazz.getClassLoader(); } final Set<URL> urls = new LinkedHashSet<>(); while (classLoader != null) { if (classLoader instanceof URLClassLoader) { URLClassLoader urlClassLoader = (URLClassLoader) classLoader; URL[] allURLS = urlClassLoader.getURLs(); Collections.addAll(urls, allURLS); break; } URL classUrl = classModuleUrl(classLoader, clazz); if (classUrl != null) { urls.add(classUrl); } classUrl = classModuleUrl(classLoader, ClassPathURLs.class); if (classUrl != null) { urls.add(classUrl); } ModuleDescriptor moduleDescriptor = clazz.getModule().getDescriptor(); if (moduleDescriptor != null) { moduleDescriptor.requires().forEach(req -> { ModuleLayer.boot() .findModule(req.name()) .ifPresent(mod -> { ClassLoader moduleClassLoader = mod.getClassLoader(); if (moduleClassLoader != null) { URL url = moduleClassLoader.getResource(MANIFEST); if (url != null) { url = fixManifestUrl(url); urls.add(url); } } }); }); } classLoader = classLoader.getParent(); } return urls.toArray(new URL[0]); }
java
{ "resource": "" }
q171525
Email.bcc
test
public Email bcc(final EmailAddress... bccs) { this.bcc = ArraysUtil.join(this.bcc, valueOrEmptyArray(bccs)); return _this(); }
java
{ "resource": "" }
q171526
TypeJsonSerializerMap.register
test
public void register(final Class type, final TypeJsonSerializer typeJsonSerializer) { map.put(type, typeJsonSerializer); cache.clear(); }
java
{ "resource": "" }
q171527
TypeJsonSerializerMap.lookupSerializer
test
protected TypeJsonSerializer lookupSerializer(final Class type) { TypeJsonSerializer tjs = map.get(type); if (tjs == null) { if (defaultSerializerMap != null) { tjs = defaultSerializerMap.map.get(type); } } return tjs; }
java
{ "resource": "" }
q171528
MultipartStreamParser.parseRequestStream
test
public void parseRequestStream(final InputStream inputStream, final String encoding) throws IOException { setParsed(); MultipartRequestInputStream input = new MultipartRequestInputStream(inputStream); input.readBoundary(); while (true) { FileUploadHeader header = input.readDataHeader(encoding); if (header == null) { break; } if (header.isFile) { String fileName = header.fileName; if (fileName.length() > 0) { if (header.contentType.indexOf("application/x-macbinary") > 0) { input.skipBytes(128); } } FileUpload newFile = fileUploadFactory.create(input); newFile.processStream(); if (fileName.length() == 0) { // file was specified, but no name was provided, therefore it was not uploaded if (newFile.getSize() == 0) { newFile.size = -1; } } putFile(header.formFieldName, newFile); } else { // no file, therefore it is regular form parameter. FastByteArrayOutputStream fbos = new FastByteArrayOutputStream(); input.copyAll(fbos); String value = encoding != null ? new String(fbos.toByteArray(), encoding) : new String(fbos.toByteArray()); putParameter(header.formFieldName, value); } input.skipBytes(1); input.mark(1); // read byte, but may be end of stream int nextByte = input.read(); if (nextByte == -1 || nextByte == '-') { input.reset(); break; } input.reset(); } }
java
{ "resource": "" }
q171529
MultipartStreamParser.getParameter
test
public String getParameter(final String paramName) { if (requestParameters == null) { return null; } String[] values = requestParameters.get(paramName); if ((values != null) && (values.length > 0)) { return values[0]; } return null; }
java
{ "resource": "" }
q171530
MultipartStreamParser.getParameterValues
test
public String[] getParameterValues(final String paramName) { if (requestParameters == null) { return null; } return requestParameters.get(paramName); }
java
{ "resource": "" }
q171531
MultipartStreamParser.getFile
test
public FileUpload getFile(final String paramName) { if (requestFiles == null) { return null; } FileUpload[] values = requestFiles.get(paramName); if ((values != null) && (values.length > 0)) { return values[0]; } return null; }
java
{ "resource": "" }
q171532
MultipartStreamParser.getFiles
test
public FileUpload[] getFiles(final String paramName) { if (requestFiles == null) { return null; } return requestFiles.get(paramName); }
java
{ "resource": "" }
q171533
CharacterEncodingFilter.init
test
@Override public void init(final FilterConfig filterConfig) { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); if (this.encoding == null) { this.encoding = JoddCore.encoding; } this.ignore = Converter.get().toBooleanValue(filterConfig.getInitParameter("ignore"), true); }
java
{ "resource": "" }
q171534
TemplateParser.parse
test
public void parse(final DbSqlBuilder sqlBuilder, final String template) { int length = template.length(); int last = 0; while (true) { int mark = template.indexOf('$', last); if (mark == -1) { if (last < length) { sqlBuilder.appendRaw(template.substring(last)); } break; } int escapesCount = countEscapes(template, mark); // check if escaped if (escapesCount > 0) { boolean isEscaped = escapesCount % 2 != 0; int escapesToAdd = escapesCount >> 1; sqlBuilder.appendRaw(template.substring(last, mark - escapesCount + escapesToAdd) + '$'); if (isEscaped) { last = mark + 1; continue; } } else { sqlBuilder.appendRaw(template.substring(last, mark)); } int end; if (template.startsWith(MACRO_TABLE, mark)) { mark += MACRO_TABLE.length(); end = findMacroEnd(template, mark); onTable(sqlBuilder, template.substring(mark, end)); } else if (template.startsWith(MACRO_COLUMN, mark)) { mark += MACRO_COLUMN.length(); end = findMacroEnd(template, mark); onColumn(sqlBuilder, template.substring(mark, end)); } else if (template.startsWith(MACRO_MATCH, mark)) { mark += MACRO_MATCH.length(); end = findMacroEnd(template, mark); onMatch(sqlBuilder, template.substring(mark, end)); } else if (template.startsWith(MACRO_VALUE, mark)) { mark += MACRO_VALUE.length(); end = findMacroEnd(template, mark); onValue(sqlBuilder, template.substring(mark, end)); } else { mark++; // reference found end = mark; // find macro end while (end < length) { if (!isReferenceChar(template, end)) { break; } end++; } onReference(sqlBuilder, template.substring(mark, end)); end--; } end++; last = end; } }
java
{ "resource": "" }
q171535
TemplateParser.findMacroEnd
test
protected int findMacroEnd(final String template, final int fromIndex) { int endIndex = template.indexOf('}', fromIndex); if (endIndex == -1) { throw new DbSqlBuilderException("Template syntax error, some macros are not closed. Error at: '..." + template.substring(fromIndex)); } return endIndex; }
java
{ "resource": "" }
q171536
TemplateParser.countEscapes
test
protected int countEscapes(final String template, int macroIndex) { macroIndex--; int escapeCount = 0; while (macroIndex >= 0) { if (template.charAt(macroIndex) != ESCAPE_CHARACTER) { break; } escapeCount++; macroIndex--; } return escapeCount; }
java
{ "resource": "" }
q171537
HttpUtil.buildQuery
test
public static String buildQuery(final HttpMultiMap<?> queryMap, final String encoding) { if (queryMap.isEmpty()) { return StringPool.EMPTY; } int queryMapSize = queryMap.size(); StringBand query = new StringBand(queryMapSize * 4); int count = 0; for (Map.Entry<String, ?> entry : queryMap) { String key = entry.getKey(); key = URLCoder.encodeQueryParam(key, encoding); Object value = entry.getValue(); if (value == null) { if (count != 0) { query.append('&'); } query.append(key); count++; } else { if (count != 0) { query.append('&'); } query.append(key); count++; query.append('='); String valueString = URLCoder.encodeQueryParam(value.toString(), encoding); query.append(valueString); } } return query.toString(); }
java
{ "resource": "" }
q171538
HttpUtil.parseQuery
test
public static HttpMultiMap<String> parseQuery(final String query, final boolean decode) { final HttpMultiMap<String> queryMap = HttpMultiMap.newCaseInsensitiveMap(); if (StringUtil.isBlank(query)) { return queryMap; } int lastNdx = 0; while (lastNdx < query.length()) { int ndx = query.indexOf('&', lastNdx); if (ndx == -1) { ndx = query.length(); } final String paramAndValue = query.substring(lastNdx, ndx); ndx = paramAndValue.indexOf('='); if (ndx == -1) { queryMap.add(paramAndValue, null); } else { String name = paramAndValue.substring(0, ndx); if (decode) { name = URLDecoder.decodeQuery(name); } String value = paramAndValue.substring(ndx + 1); if (decode) { value = URLDecoder.decodeQuery(value); } queryMap.add(name, value); } lastNdx += paramAndValue.length() + 1; } return queryMap; }
java
{ "resource": "" }
q171539
HttpUtil.prepareHeaderParameterName
test
public static String prepareHeaderParameterName(final String headerName) { // special cases if (headerName.equals("etag")) { return HttpBase.HEADER_ETAG; } if (headerName.equals("www-authenticate")) { return "WWW-Authenticate"; } char[] name = headerName.toCharArray(); boolean capitalize = true; for (int i = 0; i < name.length; i++) { char c = name[i]; if (c == '-') { capitalize = true; continue; } if (capitalize) { name[i] = Character.toUpperCase(c); capitalize = false; } else { name[i] = Character.toLowerCase(c); } } return new String(name); }
java
{ "resource": "" }
q171540
HttpUtil.extractMediaType
test
public static String extractMediaType(final String contentType) { int index = contentType.indexOf(';'); if (index == -1) { return contentType; } return contentType.substring(0, index); }
java
{ "resource": "" }
q171541
LagartoHtmlRenderer.toHtml
test
public String toHtml(final Node node, final Appendable appendable) { NodeVisitor renderer = createRenderer(appendable); node.visit(renderer); return appendable.toString(); }
java
{ "resource": "" }
q171542
LagartoHtmlRenderer.toInnerHtml
test
public String toInnerHtml(final Node node, final Appendable appendable) { NodeVisitor renderer = createRenderer(appendable); node.visitChildren(renderer); return appendable.toString(); }
java
{ "resource": "" }
q171543
Madvoc.configureWith
test
public void configureWith(final ServletContext servletContext) { webAppClassName = servletContext.getInitParameter(PARAM_MADVOC_WEBAPP); paramsFiles = Converter.get().toStringArray(servletContext.getInitParameter(PARAM_MADVOC_PARAMS)); madvocConfiguratorClassName = servletContext.getInitParameter(PARAM_MADVOC_CONFIGURATOR); }
java
{ "resource": "" }
q171544
JsonParser.reset
test
protected void reset() { this.ndx = 0; this.textLen = 0; this.path = new Path(); this.notFirstObject = false; if (useAltPaths) { path.altPath = new Path(); } if (classMetadataName != null) { mapToBean = createMapToBean(classMetadataName); } }
java
{ "resource": "" }
q171545
JsonParser.lazy
test
public JsonParser lazy(final boolean lazy) { this.lazy = lazy; this.mapSupplier = lazy ? LAZYMAP_SUPPLIER : HASHMAP_SUPPLIER; this.listSupplier = lazy ? LAZYLIST_SUPPLIER : ARRAYLIST_SUPPLIER; return this; }
java
{ "resource": "" }
q171546
JsonParser.replaceWithMappedTypeForPath
test
protected Class replaceWithMappedTypeForPath(final Class target) { if (mappings == null) { return target; } Class newType; // first try alt paths Path altPath = path.getAltPath(); if (altPath != null) { if (!altPath.equals(path)) { newType = mappings.get(altPath); if (newType != null) { return newType; } } } // now check regular paths newType = mappings.get(path); if (newType != null) { return newType; } return target; }
java
{ "resource": "" }
q171547
JsonParser.parseAsList
test
public <T> List<T> parseAsList(final String string, final Class<T> componentType) { return new JsonParser() .map(JsonParser.VALUES, componentType) .parse(string); }
java
{ "resource": "" }
q171548
JsonParser.parseAsMap
test
public <K, V> Map<K, V> parseAsMap( final String string, final Class<K> keyType, final Class<V> valueType) { return new JsonParser() .map(JsonParser.KEYS, keyType) .map(JsonParser.VALUES, valueType) .parse(string); }
java
{ "resource": "" }
q171549
JsonParser.resolveLazyValue
test
private Object resolveLazyValue(Object value) { if (value instanceof Supplier) { value = ((Supplier)value).get(); } return value; }
java
{ "resource": "" }
q171550
JsonParser.skipObject
test
private void skipObject() { int bracketCount = 1; boolean insideString = false; while (ndx < total) { final char c = input[ndx]; if (insideString) { if (c == '\"' && notPrecededByEvenNumberOfBackslashes()) { insideString = false; } } else if (c == '\"') { insideString = true; } else if (c == '{') { bracketCount++; } else if (c == '}') { bracketCount--; if (bracketCount == 0) { ndx++; return; } } ndx++; } }
java
{ "resource": "" }
q171551
JsonParser.parseString
test
protected String parseString() { char quote = '\"'; if (looseMode) { quote = consumeOneOf('\"', '\''); if (quote == 0) { return parseUnquotedStringContent(); } } else { consume(quote); } return parseStringContent(quote); }
java
{ "resource": "" }
q171552
JsonParser.parseStringContent
test
protected String parseStringContent(final char quote) { final int startNdx = ndx; // roll-out until the end of the string or the escape char while (true) { final char c = input[ndx]; if (c == quote) { // no escapes found, just use existing string ndx++; return new String(input, startNdx, ndx - 1 - startNdx); } if (c == '\\') { break; } ndx++; } // escapes found, proceed differently textLen = ndx - startNdx; growEmpty(); // for (int i = startNdx, j = 0; j < textLen; i++, j++) { // text[j] = input[i]; // } System.arraycopy(input, startNdx, text, 0, textLen); // escape char, process everything until the end while (true) { char c = input[ndx]; if (c == quote) { // done ndx++; final String str = new String(text, 0, textLen); textLen = 0; return str; } if (c == '\\') { // escape char found ndx++; c = input[ndx]; switch (c) { case '\"' : c = '\"'; break; case '\\' : c = '\\'; break; case '/' : c = '/'; break; case 'b' : c = '\b'; break; case 'f' : c = '\f'; break; case 'n' : c = '\n'; break; case 'r' : c = '\r'; break; case 't' : c = '\t'; break; case 'u' : ndx++; c = parseUnicode(); break; default: if (looseMode) { if (c != '\'') { c = '\\'; ndx--; } } else { syntaxError("Invalid escape char: " + c); } } } text[textLen] = c; textLen++; growAndCopy(); ndx++; } }
java
{ "resource": "" }
q171553
JsonParser.parseUnicode
test
protected char parseUnicode() { int i0 = CharUtil.hex2int(input[ndx++]); int i1 = CharUtil.hex2int(input[ndx++]); int i2 = CharUtil.hex2int(input[ndx++]); int i3 = CharUtil.hex2int(input[ndx]); return (char) ((i0 << 12) + (i1 << 8) + (i2 << 4) + i3); }
java
{ "resource": "" }
q171554
JsonParser.parseUnquotedStringContent
test
protected String parseUnquotedStringContent() { final int startNdx = ndx; while (true) { final char c = input[ndx]; if (c <= ' ' || CharUtil.equalsOne(c, UNQUOTED_DELIMETERS)) { final int currentNdx = ndx; // done skipWhiteSpaces(); return new String(input, startNdx, currentNdx - startNdx); } ndx++; } }
java
{ "resource": "" }
q171555
JsonParser.parseNumber
test
protected Number parseNumber() { final int startIndex = ndx; char c = input[ndx]; boolean isDouble = false; boolean isExp = false; if (c == '-') { ndx++; } while (true) { if (isEOF()) { break; } c = input[ndx]; if (c >= '0' && c <= '9') { ndx++; continue; } if (c <= 32) { // white space break; } if (c == ',' || c == '}' || c == ']') { // delimiter break; } if (c == '.') { isDouble = true; } else if (c == 'e' || c == 'E') { isExp = true; } ndx++; } final String value = new String(input, startIndex, ndx - startIndex); if (isDouble) { return Double.valueOf(value); } long longNumber; if (isExp) { longNumber = Double.valueOf(value).longValue(); } else { if (value.length() >= 19) { // if string is 19 chars and longer, it can be over the limit BigInteger bigInteger = new BigInteger(value); if (isGreaterThanLong(bigInteger)) { return bigInteger; } longNumber = bigInteger.longValue(); } else { longNumber = Long.parseLong(value); } } if ((longNumber >= Integer.MIN_VALUE) && (longNumber <= Integer.MAX_VALUE)) { return (int) longNumber; } return longNumber; }
java
{ "resource": "" }
q171556
JsonParser.parseArrayContent
test
protected Object parseArrayContent(Class targetType, Class componentType) { // detect special case if (targetType == Object.class) { targetType = List.class; } // continue targetType = replaceWithMappedTypeForPath(targetType); if (componentType == null && targetType != null && targetType.isArray()) { componentType = targetType.getComponentType(); } path.push(VALUES); componentType = replaceWithMappedTypeForPath(componentType); Collection<Object> target = newArrayInstance(targetType); boolean koma = false; mainloop: while (true) { skipWhiteSpaces(); char c = input[ndx]; if (c == ']') { if (koma) { syntaxError("Trailing comma"); } ndx++; path.pop(); return target; } Object value = parseValue(componentType, null, null); target.add(value); skipWhiteSpaces(); c = input[ndx]; switch (c) { case ']': ndx++; break mainloop; case ',': ndx++; koma = true; break; default: syntaxError("Invalid char: expected ] or ,"); } } path.pop(); if (targetType != null) { return convertType(target, targetType); } return target; }
java
{ "resource": "" }
q171557
ProxettaWrapperClassBuilder.createEmptyCtor
test
protected void createEmptyCtor() { final MethodVisitor mv = wd.dest.visitMethod(AsmUtil.ACC_PUBLIC, INIT, "()V", null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn( Opcodes.INVOKESPECIAL, AsmUtil.SIGNATURE_JAVA_LANG_OBJECT, INIT, "()V", false); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); }
java
{ "resource": "" }
q171558
ProxettaWrapperClassBuilder.createSimpleMethodWrapper
test
protected void createSimpleMethodWrapper(final MethodSignatureVisitor msign) { int access = msign.getAccessFlags(); access &= ~ACC_ABSTRACT; access &= ~ACC_NATIVE; MethodVisitor mv = wd.dest.visitMethod( access, msign.getMethodName(), msign.getDescription(), msign.getAsmMethodSignature(), msign.getExceptions()); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, wd.thisReference, wd.wrapperRef, wd.wrapperType); loadVirtualMethodArguments(mv, msign); if (wd.wrapInterface) { mv.visitMethodInsn( INVOKEINTERFACE, wd.wrapperType.substring(1, wd.wrapperType.length() - 1), msign.getMethodName(), msign.getDescription(), true); } else { mv.visitMethodInsn( INVOKEVIRTUAL, wd.wrapperType.substring(1, wd.wrapperType.length() - 1), msign.getMethodName(), msign.getDescription(), false); } ProxettaAsmUtil.prepareReturnValue(mv, msign, 0); visitReturn(mv, msign, true); mv.visitMaxs(0, 0); mv.visitEnd(); }
java
{ "resource": "" }
q171559
MethodSignatureVisitor.resolveRawTypeName
test
private String resolveRawTypeName(String typeName) { if (typeName == null) { return null; } boolean isArray = typeName.startsWith(StringPool.LEFT_SQ_BRACKET); if (isArray) { typeName = typeName.substring(1); } String rawTypeName; if (generics.containsKey(typeName)) { rawTypeName = generics.get(typeName); } else { rawTypeName = declaredTypeGeneric.getOrDefault(typeName, typeName); } if (isArray) { rawTypeName = '[' + rawTypeName; } return rawTypeName; }
java
{ "resource": "" }
q171560
ReferencesResolver.resolveReferenceFromValue
test
public BeanReferences resolveReferenceFromValue(final PropertyDescriptor propertyDescriptor, final String refName) { BeanReferences references; if (refName == null || refName.isEmpty()) { references = buildDefaultReference(propertyDescriptor); } else { references = BeanReferences.of(refName); } references = references.removeDuplicateNames(); return references; }
java
{ "resource": "" }
q171561
ReferencesResolver.resolveReferenceFromValues
test
public BeanReferences[] resolveReferenceFromValues(final Executable methodOrCtor, final String... parameterReferences) { BeanReferences[] references = convertRefToReferences(parameterReferences); if (references == null || references.length == 0) { references = buildDefaultReferences(methodOrCtor); } if (methodOrCtor.getParameterTypes().length != references.length) { throw new PetiteException("Different number of method parameters and references for: " + methodOrCtor.getDeclaringClass().getName() + '#' + methodOrCtor.getName()); } removeAllDuplicateNames(references); return references; }
java
{ "resource": "" }
q171562
ReferencesResolver.readAllReferencesFromAnnotation
test
public BeanReferences[] readAllReferencesFromAnnotation(final Executable methodOrCtor) { PetiteInject petiteInject = methodOrCtor.getAnnotation(PetiteInject.class); final Parameter[] parameters = methodOrCtor.getParameters(); BeanReferences[] references; final boolean hasAnnotationOnMethodOrCtor; if (petiteInject != null) { references = convertAnnValueToReferences(petiteInject.value()); hasAnnotationOnMethodOrCtor = true; } else { references = new BeanReferences[parameters.length]; hasAnnotationOnMethodOrCtor = false; } int parametersWithAnnotationCount = 0; for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; petiteInject = parameter.getAnnotation(PetiteInject.class); if (petiteInject == null) { // no annotation on argument continue; } // there is annotation on argument, override values String annotationValue = readAnnotationValue(petiteInject); if (annotationValue != null) { references[i] = BeanReferences.of(annotationValue); } parametersWithAnnotationCount++; } if (!hasAnnotationOnMethodOrCtor) { if (parametersWithAnnotationCount == 0) { return null; } if (parametersWithAnnotationCount != parameters.length) { throw new PetiteException("All arguments must be annotated with PetiteInject"); } } references = updateReferencesWithDefaultsIfNeeded(methodOrCtor, references); removeAllDuplicateNames(references); return references; }
java
{ "resource": "" }
q171563
ReferencesResolver.buildDefaultReferences
test
private BeanReferences[] buildDefaultReferences(final Executable methodOrCtor) { final boolean useParamo = petiteConfig.getUseParamo(); final PetiteReferenceType[] lookupReferences = petiteConfig.getLookupReferences(); MethodParameter[] methodParameters = null; if (useParamo) { methodParameters = Paramo.resolveParameters(methodOrCtor); } final Class[] paramTypes = methodOrCtor.getParameterTypes(); final BeanReferences[] references = new BeanReferences[paramTypes.length]; for (int j = 0; j < paramTypes.length; j++) { String[] ref = new String[lookupReferences.length]; references[j] = BeanReferences.of(ref); for (int i = 0; i < ref.length; i++) { switch (lookupReferences[i]) { case NAME: ref[i] = methodParameters != null ? methodParameters[j].getName() : null; break; case TYPE_SHORT_NAME: ref[i] = StringUtil.uncapitalize(paramTypes[j].getSimpleName()); break; case TYPE_FULL_NAME: ref[i] = paramTypes[j].getName(); break; } } } return references; }
java
{ "resource": "" }
q171564
ReferencesResolver.buildDefaultReference
test
public BeanReferences buildDefaultReference(final PropertyDescriptor propertyDescriptor) { final PetiteReferenceType[] lookupReferences = petiteConfig.getLookupReferences(); final String[] references = new String[lookupReferences.length]; for (int i = 0; i < references.length; i++) { switch (lookupReferences[i]) { case NAME: references[i] = propertyDescriptor.getName(); break; case TYPE_SHORT_NAME: references[i] = StringUtil.uncapitalize(propertyDescriptor.getType().getSimpleName()); break; case TYPE_FULL_NAME: references[i] = propertyDescriptor.getType().getName(); break; } } return BeanReferences.of(references); }
java
{ "resource": "" }
q171565
ReferencesResolver.removeAllDuplicateNames
test
private void removeAllDuplicateNames(final BeanReferences[] allBeanReferences) { for (int i = 0; i < allBeanReferences.length; i++) { BeanReferences references = allBeanReferences[i]; allBeanReferences[i] = references.removeDuplicateNames(); } }
java
{ "resource": "" }
q171566
ReferencesResolver.convertRefToReferences
test
private BeanReferences[] convertRefToReferences(final String[] references) { if (references == null) { return null; } BeanReferences[] ref = new BeanReferences[references.length]; for (int i = 0; i < references.length; i++) { ref[i] = BeanReferences.of(references[i]); } return ref; }
java
{ "resource": "" }
q171567
ReferencesResolver.convertAnnValueToReferences
test
private BeanReferences[] convertAnnValueToReferences(String value) { if (value == null) { return null; } value = value.trim(); if (value.length() == 0) { return null; } String[] refNames = Converter.get().toStringArray(value); BeanReferences[] references = new BeanReferences[refNames.length]; for (int i = 0; i < refNames.length; i++) { references[i] = BeanReferences.of(refNames[i].trim()); } return references; }
java
{ "resource": "" }
q171568
StandaloneJoddJoy.runJoy
test
public void runJoy(final Consumer<JoddJoyRuntime> consumer) { final JoddJoy joddJoy = new JoddJoy(); final JoddJoyRuntime joyRuntime = joddJoy.startOnlyBackend(); joddJoy.withDb(joyDb -> setJtxManager(joyRuntime.getJtxManager())); final JtxTransaction tx = startRwTx(); final Print print = new Print(); try { print.line("START", 80); print.newLine(); consumer.accept(joyRuntime); print.newLine(); print.line("END", 80); if (tx != null) { tx.commit(); } } catch (Throwable throwable) { throwable.printStackTrace(); if (tx != null) { tx.rollback(); } } joddJoy.stop(); }
java
{ "resource": "" }
q171569
ClassUtil.findMethod
test
public static Method findMethod(final Class c, final String methodName) { return findDeclaredMethod(c, methodName, true); }
java
{ "resource": "" }
q171570
ClassUtil.findConstructor
test
public static <T> Constructor<T> findConstructor(final Class<T> clazz, final Class<?>... parameterTypes) { final Constructor<?>[] constructors = clazz.getConstructors(); Class<?>[] pts; for (Constructor<?> constructor : constructors) { pts = constructor.getParameterTypes(); if (isAllAssignableFrom(pts, parameterTypes)) { return (Constructor<T>) constructor; } } return null; }
java
{ "resource": "" }
q171571
ClassUtil.resolveAllInterfaces
test
public static Class[] resolveAllInterfaces(final Class type) { Set<Class> bag = new LinkedHashSet<>(); _resolveAllInterfaces(type, bag); return bag.toArray(new Class[0]); }
java
{ "resource": "" }
q171572
ClassUtil.compareParameters
test
public static boolean compareParameters(final Class[] first, final Class[] second) { if (first.length != second.length) { return false; } for (int i = 0; i < first.length; i++) { if (first[i] != second[i]) { return false; } } return true; }
java
{ "resource": "" }
q171573
ClassUtil.forceAccess
test
public static void forceAccess(final AccessibleObject accObject) { try { if (System.getSecurityManager() == null) accObject.setAccessible(true); else { AccessController.doPrivileged((PrivilegedAction) () -> { accObject.setAccessible(true); return null; }); } } catch (SecurityException sex) { // ignore } }
java
{ "resource": "" }
q171574
ClassUtil.newInstance
test
@SuppressWarnings("unchecked") public static <T> T newInstance(final Class<T> clazz, final Object... params) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (params.length == 0) { return newInstance(clazz); } final Class<?>[] paramTypes = getClasses(params); final Constructor<?> constructor = findConstructor(clazz, paramTypes); if (constructor == null) { throw new InstantiationException("No constructor matched parameter types."); } return (T) constructor.newInstance(params); }
java
{ "resource": "" }
q171575
ClassUtil.getSuperclasses
test
public static Class[] getSuperclasses(final Class type) { int i = 0; for (Class x = type.getSuperclass(); x != null; x = x.getSuperclass()) { i++; } Class[] result = new Class[i]; i = 0; for (Class x = type.getSuperclass(); x != null; x = x.getSuperclass()) { result[i] = x; i++; } return result; }
java
{ "resource": "" }
q171576
ClassUtil.childClassOf
test
public static Class<?> childClassOf(final Class<?> parentClass, final Object instance) { if (instance == null || instance == Object.class) { return null; } if (parentClass != null) { if (parentClass.isInterface()) { return null; } } Class<?> childClass = instance.getClass(); while (true) { Class<?> parent = childClass.getSuperclass(); if (parent == parentClass) { return childClass; } if (parent == null) { return null; } childClass = parent; } }
java
{ "resource": "" }
q171577
ClassUtil.jarFileOf
test
public static JarFile jarFileOf(final Class<?> klass) { URL url = klass.getResource( "/" + klass.getName().replace('.', '/') + ".class"); if (url == null) { return null; } String s = url.getFile(); int beginIndex = s.indexOf("file:") + "file:".length(); int endIndex = s.indexOf(".jar!"); if (endIndex == -1) { return null; } endIndex += ".jar".length(); String f = s.substring(beginIndex, endIndex); // decode URL string - it may contain encoded chars (e.g. whitespaces) which are not supported for file-instances f = URLDecoder.decode(f, "UTF-8"); File file = new File(f); try { return file.exists() ? new JarFile(file) : null; } catch (IOException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q171578
ThreadUtil.sleep
test
public static void sleep(final long ms) { try { Thread.sleep(ms); } catch (InterruptedException iex) { Thread.currentThread().interrupt(); } }
java
{ "resource": "" }
q171579
ThreadUtil.sleep
test
public static void sleep() { try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException iex) { Thread.currentThread().interrupt(); } }
java
{ "resource": "" }
q171580
ThreadUtil.wait
test
public static void wait(final Object obj) { synchronized (obj) { try { obj.wait(); } catch (InterruptedException inex) { Thread.currentThread().interrupt(); } } }
java
{ "resource": "" }
q171581
ThreadUtil.daemonThreadFactory
test
public static ThreadFactory daemonThreadFactory(final String name, final int priority) { return new ThreadFactory() { private AtomicInteger count = new AtomicInteger(); @Override public Thread newThread(final Runnable r) { Thread thread = new Thread(r); thread.setName(name + '-' + count.incrementAndGet()); thread.setDaemon(true); thread.setPriority(priority); return thread; } }; }
java
{ "resource": "" }
q171582
LazyValue.get
test
@Override public T get() { if (!initialized) { synchronized (this) { if (!initialized) { final T t = supplier.get(); value = t; initialized = true; supplier = null; return t; } } } return value; }
java
{ "resource": "" }
q171583
MethodVisitor.visitParameter
test
public void visitParameter(final String name, final int access) { if (api < Opcodes.ASM5) { throw new UnsupportedOperationException(REQUIRES_ASM5); } if (mv != null) { mv.visitParameter(name, access); } }
java
{ "resource": "" }
q171584
MethodVisitor.visitAnnotation
test
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { if (mv != null) { return mv.visitAnnotation(descriptor, visible); } return null; }
java
{ "resource": "" }
q171585
MethodVisitor.visitTypeAnnotation
test
public AnnotationVisitor visitTypeAnnotation( final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { if (api < Opcodes.ASM5) { throw new UnsupportedOperationException(REQUIRES_ASM5); } if (mv != null) { return mv.visitTypeAnnotation(typeRef, typePath, descriptor, visible); } return null; }
java
{ "resource": "" }
q171586
MethodVisitor.visitParameterAnnotation
test
public AnnotationVisitor visitParameterAnnotation( final int parameter, final String descriptor, final boolean visible) { if (mv != null) { return mv.visitParameterAnnotation(parameter, descriptor, visible); } return null; }
java
{ "resource": "" }
q171587
MethodVisitor.visitFieldInsn
test
public void visitFieldInsn( final int opcode, final String owner, final String name, final String descriptor) { if (mv != null) { mv.visitFieldInsn(opcode, owner, name, descriptor); } }
java
{ "resource": "" }
q171588
MethodVisitor.visitMethodInsn
test
public void visitMethodInsn( final int opcode, final String owner, final String name, final String descriptor, final boolean isInterface) { if (api < Opcodes.ASM5) { if (isInterface != (opcode == Opcodes.INVOKEINTERFACE)) { throw new IllegalArgumentException("INVOKESPECIAL/STATIC on interfaces requires ASM5"); } visitMethodInsn(opcode, owner, name, descriptor); return; } if (mv != null) { mv.visitMethodInsn(opcode, owner, name, descriptor, isInterface); } }
java
{ "resource": "" }
q171589
MethodVisitor.visitInvokeDynamicInsn
test
public void visitInvokeDynamicInsn( final String name, final String descriptor, final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) { if (api < Opcodes.ASM5) { throw new UnsupportedOperationException(REQUIRES_ASM5); } if (mv != null) { mv.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments); } }
java
{ "resource": "" }
q171590
MethodVisitor.visitJumpInsn
test
public void visitJumpInsn(final int opcode, final Label label) { if (mv != null) { mv.visitJumpInsn(opcode, label); } }
java
{ "resource": "" }
q171591
MethodVisitor.visitMultiANewArrayInsn
test
public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) { if (mv != null) { mv.visitMultiANewArrayInsn(descriptor, numDimensions); } }
java
{ "resource": "" }
q171592
MethodVisitor.visitTryCatchBlock
test
public void visitTryCatchBlock( final Label start, final Label end, final Label handler, final String type) { if (mv != null) { mv.visitTryCatchBlock(start, end, handler, type); } }
java
{ "resource": "" }
q171593
MethodVisitor.visitLocalVariableAnnotation
test
public AnnotationVisitor visitLocalVariableAnnotation( final int typeRef, final TypePath typePath, final Label[] start, final Label[] end, final int[] index, final String descriptor, final boolean visible) { if (api < Opcodes.ASM5) { throw new UnsupportedOperationException(REQUIRES_ASM5); } if (mv != null) { return mv.visitLocalVariableAnnotation( typeRef, typePath, start, end, index, descriptor, visible); } return null; }
java
{ "resource": "" }
q171594
PropertiesToProps.convertToWriter
test
void convertToWriter(final Writer writer, final Properties properties, final Map<String, Properties> profiles) throws IOException { final BufferedWriter bw = getBufferedWriter(writer); writeBaseAndProfileProperties(bw, properties, profiles); writeProfilePropertiesThatAreNotInTheBase(bw, properties, profiles); bw.flush(); }
java
{ "resource": "" }
q171595
MemoryFileUpload.processStream
test
@Override public void processStream() throws IOException { FastByteArrayOutputStream out = new FastByteArrayOutputStream(); size = 0; if (maxFileSize == -1) { size += input.copyAll(out); } else { size += input.copyMax(out, maxFileSize + 1); // one more byte to detect larger files if (size > maxFileSize) { fileTooBig = true; valid = false; input.skipToBoundary(); return; } } data = out.toByteArray(); size = data.length; valid = true; }
java
{ "resource": "" }
q171596
DbListIterator.next
test
@Override public T next() { if (hasNext == null) { hasNext = Boolean.valueOf(moveToNext()); } if (hasNext == false) { throw new NoSuchElementException(); } if (!entityAwareMode) { hasNext = null; return newElement; } count++; T result = previousElement; previousElement = newElement; hasNext = null; return result; }
java
{ "resource": "" }
q171597
DbListIterator.moveToNext
test
private boolean moveToNext() { if (last) { // last has been set to true, so no more rows to iterate - close everything if (closeOnEnd) { query.close(); } else { query.closeResultSet(resultSetMapper.getResultSet()); } return false; } while (true) { if (!resultSetMapper.next()) { // no more rows, no more parsing, previousElement is the last one to iterate last = true; return entityAwareMode; } // parse row Object[] objects = resultSetMapper.parseObjects(types); Object row = query.resolveRowResults(objects); newElement = (T) row; if (entityAwareMode) { if (count == 0 && previousElement == null) { previousElement = newElement; continue; } if (previousElement != null && newElement != null) { boolean equals; if (newElement.getClass().isArray()) { equals = Arrays.equals((Object[]) previousElement, (Object[]) newElement); } else { equals = previousElement.equals(newElement); } if (equals) { continue; } } } break; } return true; }
java
{ "resource": "" }
q171598
ArraysUtil.join
test
@SuppressWarnings({"unchecked"}) public static <T> T[] join(T[]... arrays) { Class<T> componentType = (Class<T>) arrays.getClass().getComponentType().getComponentType(); return join(componentType, arrays); }
java
{ "resource": "" }
q171599
ArraysUtil.join
test
@SuppressWarnings({"unchecked"}) public static <T> T[] join(Class<T> componentType, T[][] arrays) { if (arrays.length == 1) { return arrays[0]; } int length = 0; for (T[] array : arrays) { length += array.length; } T[] result = (T[]) Array.newInstance(componentType, length); length = 0; for (T[] array : arrays) { System.arraycopy(array, 0, result, length, array.length); length += array.length; } return result; }
java
{ "resource": "" }