_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q171000
Buffer.writeTo
test
public void writeTo(final OutputStream out, final HttpProgressListener progressListener) throws IOException { // start final int size = size(); final int callbackSize = progressListener.callbackSize(size); int count = 0; // total count int step = 0; // step is offset in current chunk progressListener.transferred(count); // loop for (Object o : list) { if (o instanceof FastByteBuffer) { FastByteBuffer fastByteBuffer = (FastByteBuffer) o; byte[] bytes = fastByteBuffer.toArray(); int offset = 0; while (offset < bytes.length) { // calc the remaining sending chunk size int chunk = callbackSize - step; // check if this chunk size fits the bytes array if (offset + chunk > bytes.length) { chunk = bytes.length - offset; } // writes the chunk out.write(bytes, offset, chunk); offset += chunk; step += chunk; count += chunk; // listener if (step >= callbackSize) { progressListener.transferred(count); step -= callbackSize; } } } else if (o instanceof Uploadable) { Uploadable uploadable = (Uploadable) o; InputStream inputStream = uploadable.openInputStream(); int remaining = uploadable.getSize(); try { while (remaining > 0) { // calc the remaining sending chunk size int chunk = callbackSize - step; // check if this chunk size fits the remaining size if (chunk > remaining) { chunk = remaining; } // writes remaining chunk StreamUtil.copy(inputStream, out, chunk); remaining -= chunk; step += chunk; count += chunk; // listener if (step >= callbackSize) { progressListener.transferred(count); step -= callbackSize; } } } finally { StreamUtil.close(inputStream); } } } // end if (step != 0) { progressListener.transferred(count); } }
java
{ "resource": "" }
q171001
JsonObject.getString
test
public String getString(final String key) { CharSequence cs = (CharSequence) map.get(key); return cs == null ? null : cs.toString(); }
java
{ "resource": "" }
q171002
JsonObject.getInteger
test
public Integer getInteger(final String key) { Number number = (Number) map.get(key); if (number == null) { return null; } if (number instanceof Integer) { return (Integer) number; } return number.intValue(); }
java
{ "resource": "" }
q171003
JsonObject.getLong
test
public Long getLong(final String key) { Number number = (Number) map.get(key); if (number == null) { return null; } if (number instanceof Long) { return (Long) number; } return number.longValue(); }
java
{ "resource": "" }
q171004
JsonObject.getDouble
test
public Double getDouble(final String key) { Number number = (Number) map.get(key); if (number == null) { return null; } if (number instanceof Double) { return (Double) number; } return number.doubleValue(); }
java
{ "resource": "" }
q171005
JsonObject.getFloat
test
public Float getFloat(final String key) { Number number = (Number) map.get(key); if (number == null) { return null; } if (number instanceof Float) { return (Float) number; } return number.floatValue(); }
java
{ "resource": "" }
q171006
JsonObject.getValue
test
@SuppressWarnings("unchecked") public <T> T getValue(final String key) { T val = (T) map.get(key); if (val instanceof Map) { return (T) new JsonObject((Map) val); } if (val instanceof List) { return (T) new JsonArray((List) val); } return val; }
java
{ "resource": "" }
q171007
JsonObject.put
test
public JsonObject put(final String key, final String value) { Objects.requireNonNull(key); map.put(key, value); return this; }
java
{ "resource": "" }
q171008
ReceiveMailSession.useFolder
test
public void useFolder(final String folderName) { closeFolderIfOpened(folder); try { this.folderName = folderName; this.folder = getService().getFolder(folderName); try { folder.open(Folder.READ_WRITE); } catch (final MailException ignore) { folder.open(Folder.READ_ONLY); } } catch (final MessagingException msgexc) { throw new MailException("Failed to connect to folder: " + folderName, msgexc); } }
java
{ "resource": "" }
q171009
ReceiveMailSession.receiveMessages
test
ReceivedEmail[] receiveMessages( final EmailFilter filter, final Flags flagsToSet, final Flags flagsToUnset, final boolean envelope, final Consumer<Message[]> processedMessageConsumer) { useAndOpenFolderIfNotSet(); final Message[] messages; try { if (filter == null) { messages = folder.getMessages(); } else { messages = folder.search(filter.getSearchTerm()); } if (messages.length == 0) { return ReceivedEmail.EMPTY_ARRAY; } if (envelope) { final FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(FetchProfile.Item.ENVELOPE); fetchProfile.add(FetchProfile.Item.FLAGS); folder.fetch(messages, fetchProfile); } // process messages final ReceivedEmail[] emails = new ReceivedEmail[messages.length]; for (int i = 0; i < messages.length; i++) { final Message msg = messages[i]; // we need to parse message BEFORE flags are set! emails[i] = new ReceivedEmail(msg, envelope, attachmentStorage); if (!EmailUtil.isEmptyFlags(flagsToSet)) { emails[i].flags(flagsToSet); msg.setFlags(flagsToSet, true); } if (!EmailUtil.isEmptyFlags(flagsToUnset)) { emails[i].flags().remove(flagsToUnset); msg.setFlags(flagsToUnset, false); } if (EmailUtil.isEmptyFlags(flagsToSet) && !emails[i].isSeen()) { msg.setFlag(Flags.Flag.SEEN, false); } } if (processedMessageConsumer != null) { processedMessageConsumer.accept(messages); } // if messages were marked to be deleted, we need to expunge the folder if (!EmailUtil.isEmptyFlags(flagsToSet)) { if (flagsToSet.contains(Flags.Flag.DELETED)) { folder.expunge(); } } return emails; } catch (final MessagingException msgexc) { throw new MailException("Failed to fetch messages", msgexc); } }
java
{ "resource": "" }
q171010
ReceiveMailSession.updateEmailFlags
test
public void updateEmailFlags(final ReceivedEmail receivedEmail) { useAndOpenFolderIfNotSet(); try { folder.setFlags(new int[] {receivedEmail.messageNumber()}, receivedEmail.flags(),true); } catch (MessagingException mex) { throw new MailException("Failed to fetch messages", mex); } }
java
{ "resource": "" }
q171011
ReceiveMailSession.closeFolderIfOpened
test
protected void closeFolderIfOpened(final Folder folder) { if (folder != null) { try { folder.close(true); } catch (final MessagingException ignore) { } } }
java
{ "resource": "" }
q171012
DbQueryParser.lookupNamedParameter
test
DbQueryNamedParameter lookupNamedParameter(final String name) { DbQueryNamedParameter p = rootNP; while (p != null) { if (p.equalsName(name)) { return p; } p = p.next; } return null; }
java
{ "resource": "" }
q171013
AppAction.alias
test
protected String alias(final String target) { return StringPool.LEFT_CHEV.concat(target).concat(StringPool.RIGHT_CHEV); }
java
{ "resource": "" }
q171014
AppAction.validateAction
test
protected boolean validateAction(final String... profiles) { prepareValidator(); vtor.useProfiles(profiles); vtor.validate(this); vtor.resetProfiles(); List<Violation> violations = vtor.getViolations(); return violations == null; }
java
{ "resource": "" }
q171015
AppAction.addViolation
test
protected void addViolation(final String name, final Object invalidValue) { prepareValidator(); vtor.addViolation(new Violation(name, this, invalidValue)); }
java
{ "resource": "" }
q171016
RawData.as
test
public RawData as(final String mimeOrExtension) { if (mimeOrExtension.contains(StringPool.SLASH)) { this.mimeType = mimeOrExtension; } else { this.mimeType = MimeTypes.getMimeType(mimeOrExtension); } return this; }
java
{ "resource": "" }
q171017
RawData.downloadableAs
test
public RawData downloadableAs(final String downloadFileName) { this.downloadFileName = downloadFileName; this.mimeType = MimeTypes.getMimeType(FileNameUtil.getExtension(downloadFileName)); return this; }
java
{ "resource": "" }
q171018
ProxettaFactory.setTarget
test
protected T setTarget(final InputStream target) { assertTargetIsNotDefined(); targetInputStream = target; targetClass = null; targetClassName = null; return _this(); }
java
{ "resource": "" }
q171019
ProxettaFactory.setTarget
test
protected T setTarget(final String targetName) { assertTargetIsNotDefined(); try { targetInputStream = ClassLoaderUtil.getClassAsStream(targetName); if (targetInputStream == null) { throw new ProxettaException("Target class not found: " + targetName); } targetClassName = targetName; targetClass = null; } catch (IOException ioex) { StreamUtil.close(targetInputStream); throw new ProxettaException("Unable to get stream class name: " + targetName, ioex); } return _this(); }
java
{ "resource": "" }
q171020
ProxettaFactory.setTarget
test
public T setTarget(final Class target) { assertTargetIsNotDefined(); try { targetInputStream = ClassLoaderUtil.getClassAsStream(target); if (targetInputStream == null) { throw new ProxettaException("Target class not found: " + target.getName()); } targetClass = target; targetClassName = target.getName(); } catch (IOException ioex) { StreamUtil.close(targetInputStream); throw new ProxettaException("Unable to stream class: " + target.getName(), ioex); } return _this(); }
java
{ "resource": "" }
q171021
ProxettaFactory.process
test
protected void process() { if (targetInputStream == null) { throw new ProxettaException("Target missing: " + targetClassName); } // create class reader final ClassReader classReader; try { classReader = new ClassReader(targetInputStream); } catch (IOException ioex) { throw new ProxettaException("Error reading class input stream", ioex); } // reads information final TargetClassInfoReader targetClassInfoReader = new TargetClassInfoReader(proxetta.getClassLoader()); classReader.accept(targetClassInfoReader, 0); this.destClassWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); // create proxy if (log.isDebugEnabled()) { log.debug("processing: " + classReader.getClassName()); } WorkData wd = process(classReader, targetClassInfoReader); // store important data proxyApplied = wd.proxyApplied; proxyClassName = wd.thisReference.replace('/', '.'); }
java
{ "resource": "" }
q171022
ProxettaFactory.create
test
public byte[] create() { process(); byte[] result = toByteArray(); dumpClassInDebugFolder(result); if ((!proxetta.isForced()) && (!isProxyApplied())) { if (log.isDebugEnabled()) { log.debug("Proxy not applied: " + StringUtil.toSafeString(targetClassName)); } return null; } if (log.isDebugEnabled()) { log.debug("Proxy created " + StringUtil.toSafeString(targetClassName)); } return result; }
java
{ "resource": "" }
q171023
ProxettaFactory.define
test
public Class define() { process(); if ((!proxetta.isForced()) && (!isProxyApplied())) { if (log.isDebugEnabled()) { log.debug("Proxy not applied: " + StringUtil.toSafeString(targetClassName)); } if (targetClass != null) { return targetClass; } if (targetClassName != null) { try { return ClassLoaderUtil.loadClass(targetClassName); } catch (ClassNotFoundException cnfex) { throw new ProxettaException(cnfex); } } } if (log.isDebugEnabled()) { log.debug("Proxy created: " + StringUtil.toSafeString(targetClassName)); } try { ClassLoader classLoader = proxetta.getClassLoader(); if (classLoader == null) { classLoader = ClassLoaderUtil.getDefaultClassLoader(); if ((classLoader == null) && (targetClass != null)) { classLoader = targetClass.getClassLoader(); } } final byte[] bytes = toByteArray(); dumpClassInDebugFolder(bytes); return DefineClass.of(getProxyClassName(), bytes, classLoader); } catch (Exception ex) { throw new ProxettaException("Class definition failed", ex); } }
java
{ "resource": "" }
q171024
ProxettaFactory.newInstance
test
public Object newInstance() { Class type = define(); try { return ClassUtil.newInstance(type); } catch (Exception ex) { throw new ProxettaException("Invalid Proxetta class", ex); } }
java
{ "resource": "" }
q171025
ProxettaFactory.dumpClassInDebugFolder
test
protected void dumpClassInDebugFolder(final byte[] bytes) { File debugFolder = proxetta.getDebugFolder(); if (debugFolder == null) { return; } if (!debugFolder.exists() || !debugFolder.isDirectory()) { log.warn("Invalid debug folder: " + debugFolder); } String fileName = proxyClassName; if (fileName == null) { fileName = "proxetta-" + System.currentTimeMillis(); } fileName += ".class"; File file = new File(debugFolder, fileName); try { FileUtil.writeBytes(file, bytes); } catch (IOException ioex) { log.warn("Error writing class as " + file, ioex); } }
java
{ "resource": "" }
q171026
CommonEmail.from
test
public T from(final String personalName, final String from) { return from(new EmailAddress(personalName, from)); }
java
{ "resource": "" }
q171027
CommonEmail.to
test
public T to(final EmailAddress to) { this.to = ArraysUtil.append(this.to, to); return _this(); }
java
{ "resource": "" }
q171028
CommonEmail.to
test
public T to(final String personalName, final String to) { return to(new EmailAddress(personalName, to)); }
java
{ "resource": "" }
q171029
CommonEmail.replyTo
test
public T replyTo(final EmailAddress... replyTo) { this.replyTo = ArraysUtil.join(this.replyTo, valueOrEmptyArray(replyTo)); return _this(); }
java
{ "resource": "" }
q171030
CommonEmail.cc
test
public T cc(final EmailAddress... ccs) { this.cc = ArraysUtil.join(this.cc, valueOrEmptyArray(ccs)); return _this(); }
java
{ "resource": "" }
q171031
CommonEmail.textMessage
test
public T textMessage(final String text, final String encoding) { return message(new EmailMessage(text, MimeTypes.MIME_TEXT_PLAIN, encoding)); }
java
{ "resource": "" }
q171032
CommonEmail.htmlMessage
test
public T htmlMessage(final String html, final String encoding) { return message(new EmailMessage(html, MimeTypes.MIME_TEXT_HTML, encoding)); }
java
{ "resource": "" }
q171033
CommonEmail.header
test
public T header(final String name, final String value) { headers.put(name, value); return _this(); }
java
{ "resource": "" }
q171034
SystemUtil.get
test
public static String get(final String name, final String defaultValue) { Objects.requireNonNull(name); String value = null; try { if (System.getSecurityManager() == null) { value = System.getProperty(name); } else { value = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(name)); } } catch (Exception ignore) { } if (value == null) { return defaultValue; } return value; }
java
{ "resource": "" }
q171035
SystemUtil.getBoolean
test
public static boolean getBoolean(final String name, final boolean defaultValue) { String value = get(name); if (value == null) { return defaultValue; } value = value.trim().toLowerCase(); switch (value) { case "true" : case "yes" : case "1" : case "on" : return true; case "false": case "no" : case "0" : case "off" : return false; default: return defaultValue; } }
java
{ "resource": "" }
q171036
SystemUtil.getInt
test
public static long getInt(final String name, final int defaultValue) { String value = get(name); if (value == null) { return defaultValue; } value = value.trim().toLowerCase(); try { return Integer.parseInt(value); } catch (NumberFormatException nfex) { return defaultValue; } }
java
{ "resource": "" }
q171037
SystemUtil.getLong
test
public static long getLong(final String name, final long defaultValue) { String value = get(name); if (value == null) { return defaultValue; } value = value.trim().toLowerCase(); try { return Long.parseLong(value); } catch (NumberFormatException nfex) { return defaultValue; } }
java
{ "resource": "" }
q171038
MethodFinder.getResolvedParameters
test
MethodParameter[] getResolvedParameters() { if (paramExtractor == null) { return MethodParameter.EMPTY_ARRAY; } if (!paramExtractor.debugInfoPresent) { throw new ParamoException("Parameter names not available for method: " + declaringClass.getName() + '#' + methodName); } return paramExtractor.getMethodParameters(); }
java
{ "resource": "" }
q171039
KeyValueJsonSerializer.serializeKeyValue
test
protected int serializeKeyValue(final JsonContext jsonContext, final Path currentPath, final Object key, final Object value, int count) { if ((value == null) && jsonContext.isExcludeNulls()) { return count; } if (key != null) { currentPath.push(key.toString()); } else { currentPath.push(StringPool.NULL); } // check if we should include the field boolean include = true; if (value != null) { // + all collections are not serialized by default include = jsonContext.matchIgnoredPropertyTypes(value.getClass(), false, include); // + path queries: excludes/includes include = jsonContext.matchPathToQueries(include); } // done if (!include) { currentPath.pop(); return count; } if (key == null) { jsonContext.pushName(null, count > 0); } else { jsonContext.pushName(key.toString(), count > 0); } jsonContext.serialize(value); if (jsonContext.isNamePopped()) { count++; } currentPath.pop(); return count; }
java
{ "resource": "" }
q171040
ResultMapper.lookupAlias
test
protected String lookupAlias(final String alias) { String value = actionsManager.lookupPathAlias(alias); if (value == null) { ActionRuntime cfg = actionsManager.lookup(alias); if (cfg != null) { value = cfg.getActionPath(); } } return value; }
java
{ "resource": "" }
q171041
ResultMapper.resolveAlias
test
protected String resolveAlias(final String value) { final StringBuilder result = new StringBuilder(value.length()); int i = 0; int len = value.length(); while (i < len) { int ndx = value.indexOf('<', i); if (ndx == -1) { // alias markers not found if (i == 0) { // try whole string as an alias String alias = lookupAlias(value); return (alias != null ? alias : value); } else { result.append(value.substring(i)); } break; } // alias marked found result.append(value.substring(i, ndx)); ndx++; int ndx2 = value.indexOf('>', ndx); String aliasName = (ndx2 == -1 ? value.substring(ndx) : value.substring(ndx, ndx2)); // process alias String alias = lookupAlias(aliasName); if (alias != null) { result.append(alias); } else { // alias not found if (log.isWarnEnabled()) { log.warn("Alias not found: " + aliasName); } } i = ndx2 + 1; } // fix prefix '//' - may happened when aliases are used i = 0; len = result.length(); while (i < len) { if (result.charAt(i) != '/') { break; } i++; } if (i > 1) { return result.substring(i - 1, len); } return result.toString(); }
java
{ "resource": "" }
q171042
ResultMapper.resolveResultPath
test
public ResultPath resolveResultPath(String path, String value) { boolean absolutePath = false; if (value != null) { // [*] resolve alias in value value = resolveAlias(value); // [*] absolute paths if (StringUtil.startsWithChar(value, '/')) { absolutePath = true; int dotNdx = value.indexOf(".."); if (dotNdx != -1) { path = value.substring(0, dotNdx); value = value.substring(dotNdx + 2); } else { path = value; value = null; } } else { // [*] resolve # in value and path int i = 0; while (i < value.length()) { if (value.charAt(i) != '#') { break; } int dotNdx = MadvocUtil.lastIndexOfSlashDot(path); if (dotNdx != -1) { // dot found path = path.substring(0, dotNdx); } i++; } if (i > 0) { // remove # from value value = value.substring(i); // [*] update path and value if (StringUtil.startsWithChar(value, '.')) { value = value.substring(1); } else { int dotNdx = value.indexOf(".."); if (dotNdx != -1) { path += '.' + value.substring(0, dotNdx); value = value.substring(dotNdx + 2); } else { if (value.length() > 0) { if (StringUtil.endsWithChar(path, '/')) { path += value; } else { path += '.' + value; } } value = null; } } } } } if (!absolutePath) { if (resultPathPrefix != null) { path = resultPathPrefix + path; } } return new ResultPath(path, value); }
java
{ "resource": "" }
q171043
ResultMapper.resolveResultPathString
test
public String resolveResultPathString(final String path, final String value) { final ResultPath resultPath = resolveResultPath(path, value); final String result = resultPath.pathValue(); return resolveAlias(result); }
java
{ "resource": "" }
q171044
MadvocUtil.lastIndexOfSlashDot
test
public static int lastIndexOfSlashDot(final String str) { int slashNdx = str.lastIndexOf('/'); int dotNdx = StringUtil.lastIndexOf(str, '.', str.length(), slashNdx); if (dotNdx == -1) { if (slashNdx == -1) { return -1; } slashNdx++; if (slashNdx < str.length() - 1) { dotNdx = slashNdx; } else { dotNdx = -1; } } return dotNdx; }
java
{ "resource": "" }
q171045
MadvocUtil.lastIndexOfDotAfterSlash
test
public static int lastIndexOfDotAfterSlash(final String str) { int slashNdx = str.lastIndexOf('/'); slashNdx++; return StringUtil.lastIndexOf(str, '.', str.length(), slashNdx); }
java
{ "resource": "" }
q171046
MadvocUtil.indexOfDotAfterSlash
test
public static int indexOfDotAfterSlash(final String str) { int slashNdx = str.lastIndexOf('/'); if (slashNdx == -1) { slashNdx = 0; } return str.indexOf('.', slashNdx); }
java
{ "resource": "" }
q171047
MadvocUtil.stripLastCamelWord
test
public static String stripLastCamelWord(String name) { int ndx = name.length() - 1; while (ndx >= 0) { if (CharUtil.isUppercaseAlpha(name.charAt(ndx))) { break; } ndx--; } if (ndx >= 0) { name = name.substring(0, ndx); } return name; }
java
{ "resource": "" }
q171048
DbMetaUtil.resolveSchemaName
test
public static String resolveSchemaName(final Class<?> type, final String defaultSchemaName) { String schemaName = null; final DbTable dbTable = type.getAnnotation(DbTable.class); if (dbTable != null) { schemaName = dbTable.schema().trim(); } if ((schemaName == null) || (schemaName.length() == 0)) { schemaName = defaultSchemaName; } return schemaName; }
java
{ "resource": "" }
q171049
DbMetaUtil.resolveColumnDescriptors
test
public static DbEntityColumnDescriptor resolveColumnDescriptors( final DbEntityDescriptor dbEntityDescriptor, final PropertyDescriptor property, final boolean isAnnotated, final ColumnNamingStrategy columnNamingStrategy) { String columnName = null; boolean isId = false; Class<? extends SqlType> sqlTypeClass = null; // read ID annotation DbId dbId = null; if (property.getFieldDescriptor() != null) { dbId = property.getFieldDescriptor().getField().getAnnotation(DbId.class); } if (dbId == null && property.getReadMethodDescriptor() != null) { dbId = property.getReadMethodDescriptor().getMethod().getAnnotation(DbId.class); } if (dbId == null && property.getWriteMethodDescriptor() != null) { dbId = property.getWriteMethodDescriptor().getMethod().getAnnotation(DbId.class); } if (dbId != null) { columnName = dbId.value().trim(); sqlTypeClass = dbId.sqlType(); isId = true; } else { DbColumn dbColumn = null; if (property.getFieldDescriptor() != null) { dbColumn = property.getFieldDescriptor().getField().getAnnotation(DbColumn.class); } if (dbColumn == null && property.getReadMethodDescriptor() != null) { dbColumn = property.getReadMethodDescriptor().getMethod().getAnnotation(DbColumn.class); } if (dbColumn == null && property.getWriteMethodDescriptor() != null) { dbColumn = property.getWriteMethodDescriptor().getMethod().getAnnotation(DbColumn.class); } if (dbColumn != null) { columnName = dbColumn.value().trim(); sqlTypeClass = dbColumn.sqlType(); } else { if (isAnnotated) { return null; } } } if (StringUtil.isEmpty(columnName)) { // default annotation value columnName = columnNamingStrategy.convertPropertyNameToColumnName(property.getName()); } else { if (!columnNamingStrategy.isStrictAnnotationNames()) { columnName = columnNamingStrategy.applyToColumnName(columnName); } } if (sqlTypeClass == SqlType.class) { sqlTypeClass = null; } return new DbEntityColumnDescriptor( dbEntityDescriptor, quoteIfRequired(columnName, columnNamingStrategy.isAlwaysQuoteNames(), columnNamingStrategy.getQuoteChar()), property.getName(), property.getType(), isId, sqlTypeClass); }
java
{ "resource": "" }
q171050
Threefish.init
test
public void init(final long[] key, final long[] tweak) { final int newNw = key.length; // only create new arrays if the value of N{w} changes (different key size) if (nw != newNw) { nw = newNw; switch (nw) { case WORDS_4: pi = PI4; rpi = RPI4; r = R4; break; case WORDS_8: pi = PI8; rpi = RPI8; r = R8; break; case WORDS_16: pi = PI16; rpi = RPI16; r = R16; break; default: throw new RuntimeException("Invalid threefish key"); } this.k = new long[nw + 1]; // instantiation of these fields here for performance reasons vd = new long[nw]; // v is the intermediate value v{d} at round d ed = new long[nw]; // ed is the value of e{d} at round d fd = new long[nw]; // fd is the value of f{d} at round d ksd = new long[nw]; // ksd is the value of k{s} at round d } System.arraycopy(key, 0, this.k, 0, key.length); long knw = EXTENDED_KEY_SCHEDULE_CONST; for (int i = 0; i < nw; i++) { knw ^= this.k[i]; } this.k[nw] = knw; // set tweak values t[0] = tweak[0]; t[1] = tweak[1]; t[2] = t[0] ^ t[1]; }
java
{ "resource": "" }
q171051
Threefish.mix
test
private void mix(final int j, final int d) { y[0] = x[0] + x[1]; final long rotl = r[d % DEPTH_OF_D_IN_R][j]; // java left rotation for a long y[1] = (x[1] << rotl) | (x[1] >>> (Long.SIZE - rotl)); y[1] ^= y[0]; }
java
{ "resource": "" }
q171052
Threefish.demix
test
private void demix(final int j, final int d) { y[1] ^= y[0]; final long rotr = r[d % DEPTH_OF_D_IN_R][j]; // NOTE performance: darn, creation on stack! // right shift x[1] = (y[1] << (Long.SIZE - rotr)) | (y[1] >>> rotr); x[0] = y[0] - x[1]; }
java
{ "resource": "" }
q171053
Threefish.keySchedule
test
private void keySchedule(final int s) { for (int i = 0; i < nw; i++) { // just put in the main key first ksd[i] = k[(s + i) % (nw + 1)]; // don't add anything for i = 0,...,Nw - 4 if (i == nw - 3) { // second to last ksd[i] += t[s % TWEAK_VALUES]; } else if (i == nw - 2) { // first to last ksd[i] += t[(s + 1) % TWEAK_VALUES]; } else if (i == nw - 1) { // last ksd[i] += s; } } }
java
{ "resource": "" }
q171054
Threefish.init
test
public void init(final String keyMessage, final long tweak1, final long tweak2) { long[] tweak = new long[] {tweak1, tweak2}; byte[] key = new byte[blockSize / Byte.SIZE]; byte[] keyData = StringUtil.getBytes(keyMessage); System.arraycopy(keyData, 0, key, 0, key.length < keyData.length ? key.length : keyData.length); init(bytesToLongs(key), tweak); }
java
{ "resource": "" }
q171055
Threefish.encryptBlock
test
@Override public byte[] encryptBlock(final byte[] content, final int offset) { long[] contentBlock = bytesToLongs(content, offset, blockSizeInBytes); long[] encryptedBlock = new long[blockSize / Long.SIZE]; blockEncrypt(contentBlock, encryptedBlock); return longsToBytes(encryptedBlock); }
java
{ "resource": "" }
q171056
Threefish.bytesToLongs
test
protected static long[] bytesToLongs(final byte[] ba, final int offset, final int size) { long[] result = new long[size >> 3]; int i8 = offset; for (int i = 0; i < result.length; i++) { result[i] = Bits.getLong(ba, i8); i8 += 8; } return result; }
java
{ "resource": "" }
q171057
RFC2822AddressParser.removeAnyBounding
test
private static String removeAnyBounding(final char s, final char e, final String str) { if (str == null || str.length() < 2) { return str; } if (str.startsWith(String.valueOf(s)) && str.endsWith(String.valueOf(e))) { return str.substring(1, str.length() - 1); } return str; }
java
{ "resource": "" }
q171058
PathResult.path
test
public String path() { if (methref != null) { final String methodName = methref.ref(); return target.getName() + '#' + methodName; } return path; }
java
{ "resource": "" }
q171059
ZipUtil.zlib
test
public static File zlib(final File file) throws IOException { if (file.isDirectory()) { throw new IOException("Can't zlib folder"); } FileInputStream fis = new FileInputStream(file); Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION); String zlibFileName = file.getAbsolutePath() + ZLIB_EXT; DeflaterOutputStream dos = new DeflaterOutputStream(new FileOutputStream(zlibFileName), deflater); try { StreamUtil.copy(fis, dos); } finally { StreamUtil.close(dos); StreamUtil.close(fis); } return new File(zlibFileName); }
java
{ "resource": "" }
q171060
ZipUtil.gzip
test
public static File gzip(final File file) throws IOException { if (file.isDirectory()) { throw new IOException("Can't gzip folder"); } FileInputStream fis = new FileInputStream(file); String gzipName = file.getAbsolutePath() + GZIP_EXT; GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(gzipName)); try { StreamUtil.copy(fis, gzos); } finally { StreamUtil.close(gzos); StreamUtil.close(fis); } return new File(gzipName); }
java
{ "resource": "" }
q171061
ZipUtil.ungzip
test
public static File ungzip(final File file) throws IOException { String outFileName = FileNameUtil.removeExtension(file.getAbsolutePath()); File out = new File(outFileName); out.createNewFile(); FileOutputStream fos = new FileOutputStream(out); GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(file)); try { StreamUtil.copy(gzis, fos); } finally { StreamUtil.close(fos); StreamUtil.close(gzis); } return out; }
java
{ "resource": "" }
q171062
ZipUtil.listZip
test
public static List<String> listZip(final File zipFile) throws IOException { List<String> entries = new ArrayList<>(); ZipFile zip = new ZipFile(zipFile); Enumeration zipEntries = zip.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipEntries.nextElement(); String entryName = entry.getName(); entries.add(entryName); } return Collections.unmodifiableList(entries); }
java
{ "resource": "" }
q171063
ZipUtil.unzip
test
public static void unzip(final String zipFile, final String destDir, final String... patterns) throws IOException { unzip(new File(zipFile), new File(destDir), patterns); }
java
{ "resource": "" }
q171064
ZipUtil.addToZip
test
public static void addToZip(final ZipOutputStream zos, final File file, String path, final String comment, final boolean recursive) throws IOException { if (!file.exists()) { throw new FileNotFoundException(file.toString()); } if (path == null) { path = file.getName(); } while (path.length() != 0 && path.charAt(0) == '/') { path = path.substring(1); } boolean isDir = file.isDirectory(); if (isDir) { // add folder record if (!StringUtil.endsWithChar(path, '/')) { path += '/'; } } ZipEntry zipEntry = new ZipEntry(path); zipEntry.setTime(file.lastModified()); if (comment != null) { zipEntry.setComment(comment); } if (isDir) { zipEntry.setSize(0); zipEntry.setCrc(0); } zos.putNextEntry(zipEntry); if (!isDir) { InputStream is = new FileInputStream(file); try { StreamUtil.copy(is, zos); } finally { StreamUtil.close(is); } } zos.closeEntry(); // continue adding if (recursive && file.isDirectory()) { boolean noRelativePath = StringUtil.isEmpty(path); final File[] children = file.listFiles(); if (children != null && children.length != 0) { for (File child : children) { String childRelativePath = (noRelativePath ? StringPool.EMPTY : path) + child.getName(); addToZip(zos, child, childRelativePath, comment, recursive); } } } }
java
{ "resource": "" }
q171065
ZipUtil.addToZip
test
public static void addToZip(final ZipOutputStream zos, final byte[] content, String path, final String comment) throws IOException { while (path.length() != 0 && path.charAt(0) == '/') { path = path.substring(1); } if (StringUtil.endsWithChar(path, '/')) { path = path.substring(0, path.length() - 1); } ZipEntry zipEntry = new ZipEntry(path); zipEntry.setTime(System.currentTimeMillis()); if (comment != null) { zipEntry.setComment(comment); } zos.putNextEntry(zipEntry); InputStream is = new ByteArrayInputStream(content); try { StreamUtil.copy(is, zos); } finally { StreamUtil.close(is); } zos.closeEntry(); }
java
{ "resource": "" }
q171066
ClassDescriptor.getFieldDescriptor
test
public FieldDescriptor getFieldDescriptor(final String name, final boolean declared) { final FieldDescriptor fieldDescriptor = getFields().getFieldDescriptor(name); if (fieldDescriptor != null) { if (!fieldDescriptor.matchDeclared(declared)) { return null; } } return fieldDescriptor; }
java
{ "resource": "" }
q171067
ClassDescriptor.getPropertyDescriptor
test
public PropertyDescriptor getPropertyDescriptor(final String name, final boolean declared) { PropertyDescriptor propertyDescriptor = getProperties().getPropertyDescriptor(name); if ((propertyDescriptor != null) && propertyDescriptor.matchDeclared(declared)) { return propertyDescriptor; } return null; }
java
{ "resource": "" }
q171068
LocalizationUtil.setRequestBundleName
test
public static void setRequestBundleName(final ServletRequest request, final String bundleName) { if (log.isDebugEnabled()) { log.debug("Bundle name for this request: " + bundleName); } request.setAttribute(REQUEST_BUNDLE_NAME_ATTR, bundleName); }
java
{ "resource": "" }
q171069
LocalizationUtil.setSessionLocale
test
public static void setSessionLocale(final HttpSession session, final String localeCode) { if (log.isDebugEnabled()) { log.debug("Locale stored to session: " + localeCode); } Locale locale = Locale.forLanguageTag(localeCode); session.setAttribute(SESSION_LOCALE_ATTR, locale); }
java
{ "resource": "" }
q171070
LocalizationUtil.getSessionLocale
test
public static Locale getSessionLocale(final HttpSession session) { Locale locale = (Locale) session.getAttribute(SESSION_LOCALE_ATTR); return locale == null ? MESSAGE_RESOLVER.getFallbackLocale() : locale; }
java
{ "resource": "" }
q171071
ParamManager.filterParametersForBeanName
test
public String[] filterParametersForBeanName(String beanName, final boolean resolveReferenceParams) { beanName = beanName + '.'; List<String> list = new ArrayList<>(); for (Map.Entry<String, Object> entry : params.entrySet()) { String key = entry.getKey(); if (!key.startsWith(beanName)) { continue; } list.add(key); if (!resolveReferenceParams) { continue; } // resolve all references String value = PropertiesUtil.resolveProperty(params, key); entry.setValue(value); } if (list.isEmpty()) { return StringPool.EMPTY_ARRAY; } else { return list.toArray(new String[0]); } }
java
{ "resource": "" }
q171072
PropsEntries.profile
test
public PropsEntries profile(final String... profiles) { if (profiles == null) { return this; } for (String profile : profiles) { addProfiles(profile); } return this; }
java
{ "resource": "" }
q171073
MurmurHash3.getLongLittleEndian
test
public static long getLongLittleEndian(final byte[] buf, final int offset) { return ((long) buf[offset + 7] << 56) // no mask needed | ((buf[offset + 6] & 0xffL) << 48) | ((buf[offset + 5] & 0xffL) << 40) | ((buf[offset + 4] & 0xffL) << 32) | ((buf[offset + 3] & 0xffL) << 24) | ((buf[offset + 2] & 0xffL) << 16) | ((buf[offset + 1] & 0xffL) << 8) | ((buf[offset] & 0xffL)); // no shift needed }
java
{ "resource": "" }
q171074
ClassReader.readStream
test
private static byte[] readStream(final InputStream inputStream, final boolean close) throws IOException { if (inputStream == null) { throw new IOException("Class not found"); } try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[INPUT_STREAM_DATA_CHUNK_SIZE]; int bytesRead; while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) { outputStream.write(data, 0, bytesRead); } outputStream.flush(); return outputStream.toByteArray(); } finally { if (close) { inputStream.close(); } } }
java
{ "resource": "" }
q171075
ClassReader.readLabel
test
protected Label readLabel(final int bytecodeOffset, final Label[] labels) { if (labels[bytecodeOffset] == null) { labels[bytecodeOffset] = new Label(); } return labels[bytecodeOffset]; }
java
{ "resource": "" }
q171076
ClassReader.getTypeAnnotationBytecodeOffset
test
private int getTypeAnnotationBytecodeOffset( final int[] typeAnnotationOffsets, final int typeAnnotationIndex) { if (typeAnnotationOffsets == null || typeAnnotationIndex >= typeAnnotationOffsets.length || readByte(typeAnnotationOffsets[typeAnnotationIndex]) < TypeReference.INSTANCEOF) { return -1; } return readUnsignedShort(typeAnnotationOffsets[typeAnnotationIndex] + 1); }
java
{ "resource": "" }
q171077
ClassReader.readElementValues
test
private int readElementValues( final AnnotationVisitor annotationVisitor, final int annotationOffset, final boolean named, final char[] charBuffer) { int currentOffset = annotationOffset; // Read the num_element_value_pairs field (or num_values field for an array_value). int numElementValuePairs = readUnsignedShort(currentOffset); currentOffset += 2; if (named) { // Parse the element_value_pairs array. while (numElementValuePairs-- > 0) { String elementName = readUTF8(currentOffset, charBuffer); currentOffset = readElementValue(annotationVisitor, currentOffset + 2, elementName, charBuffer); } } else { // Parse the array_value array. while (numElementValuePairs-- > 0) { currentOffset = readElementValue(annotationVisitor, currentOffset, /* named = */ null, charBuffer); } } if (annotationVisitor != null) { annotationVisitor.visitEnd(); } return currentOffset; }
java
{ "resource": "" }
q171078
ClassReader.readVerificationTypeInfo
test
private int readVerificationTypeInfo( final int verificationTypeInfoOffset, final Object[] frame, final int index, final char[] charBuffer, final Label[] labels) { int currentOffset = verificationTypeInfoOffset; int tag = b[currentOffset++] & 0xFF; switch (tag) { case Frame.ITEM_TOP: frame[index] = Opcodes.TOP; break; case Frame.ITEM_INTEGER: frame[index] = Opcodes.INTEGER; break; case Frame.ITEM_FLOAT: frame[index] = Opcodes.FLOAT; break; case Frame.ITEM_DOUBLE: frame[index] = Opcodes.DOUBLE; break; case Frame.ITEM_LONG: frame[index] = Opcodes.LONG; break; case Frame.ITEM_NULL: frame[index] = Opcodes.NULL; break; case Frame.ITEM_UNINITIALIZED_THIS: frame[index] = Opcodes.UNINITIALIZED_THIS; break; case Frame.ITEM_OBJECT: frame[index] = readClass(currentOffset, charBuffer); currentOffset += 2; break; case Frame.ITEM_UNINITIALIZED: frame[index] = createLabel(readUnsignedShort(currentOffset), labels); currentOffset += 2; break; default: throw new IllegalArgumentException(); } return currentOffset; }
java
{ "resource": "" }
q171079
ClassReader.readBootstrapMethodsAttribute
test
private int[] readBootstrapMethodsAttribute(final int maxStringLength) { char[] charBuffer = new char[maxStringLength]; int currentAttributeOffset = getFirstAttributeOffset(); int[] currentBootstrapMethodOffsets = null; for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8(currentAttributeOffset, charBuffer); int attributeLength = readInt(currentAttributeOffset + 2); currentAttributeOffset += 6; if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) { // Read the num_bootstrap_methods field and create an array of this size. currentBootstrapMethodOffsets = new int[readUnsignedShort(currentAttributeOffset)]; // Compute and store the offset of each 'bootstrap_methods' array field entry. int currentBootstrapMethodOffset = currentAttributeOffset + 2; for (int j = 0; j < currentBootstrapMethodOffsets.length; ++j) { currentBootstrapMethodOffsets[j] = currentBootstrapMethodOffset; // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each), // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2). currentBootstrapMethodOffset += 4 + readUnsignedShort(currentBootstrapMethodOffset + 2) * 2; } return currentBootstrapMethodOffsets; } currentAttributeOffset += attributeLength; } return null; }
java
{ "resource": "" }
q171080
Ctors.inspectConstructors
test
protected CtorDescriptor[] inspectConstructors() { Class type = classDescriptor.getType(); Constructor[] ctors = type.getDeclaredConstructors(); CtorDescriptor[] allCtors = new CtorDescriptor[ctors.length]; for (int i = 0; i < ctors.length; i++) { Constructor ctor = ctors[i]; CtorDescriptor ctorDescriptor = createCtorDescriptor(ctor); allCtors[i] = ctorDescriptor; if (ctorDescriptor.isDefault()) { defaultCtor = ctorDescriptor; } } return allCtors; }
java
{ "resource": "" }
q171081
Ctors.getCtorDescriptor
test
public CtorDescriptor getCtorDescriptor(final Class... args) { ctors: for (CtorDescriptor ctorDescriptor : allCtors) { Class[] arg = ctorDescriptor.getParameters(); if (arg.length != args.length) { continue; } for (int j = 0; j < arg.length; j++) { if (arg[j] != args[j]) { continue ctors; } } return ctorDescriptor; } return null; }
java
{ "resource": "" }
q171082
RequestScope.getRequestMap
test
@SuppressWarnings("unchecked") protected Map<String, TransientBeanData> getRequestMap(final HttpServletRequest servletRequest) { return (Map<String, TransientBeanData>) servletRequest.getAttribute(ATTR_NAME); }
java
{ "resource": "" }
q171083
RequestScope.createRequestMap
test
protected Map<String, TransientBeanData> createRequestMap(final HttpServletRequest servletRequest) { Map<String, TransientBeanData> map = new HashMap<>(); servletRequest.setAttribute(ATTR_NAME, map); return map; }
java
{ "resource": "" }
q171084
LongArrayConverter.convertArrayToArray
test
protected long[] convertArrayToArray(final Object value) { final Class valueComponentType = value.getClass().getComponentType(); final long[] result; if (valueComponentType.isPrimitive()) { result = convertPrimitiveArrayToArray(value, valueComponentType); } else { // convert object array to target array final Object[] array = (Object[]) value; result = new long[array.length]; for (int i = 0; i < array.length; i++) { result[i] = convertType(array[i]); } } return result; }
java
{ "resource": "" }
q171085
DecoraServletFilter.init
test
@Override public void init(final FilterConfig filterConfig) throws ServletException { // final String decoraManagerClass = filterConfig.getInitParameter(PARAM_DECORA_MANAGER); if (decoraManagerClass != null) { try { final Class decoraManagerType = ClassLoaderUtil.loadClass(decoraManagerClass); decoraManager = (DecoraManager) ClassUtil.newInstance(decoraManagerType); } catch (Exception ex) { log.error("Unable to load Decora manager class: " + decoraManagerClass, ex); throw new ServletException(ex); } } else { decoraManager = createDecoraManager(); } // final String decoraParserClass = filterConfig.getInitParameter(PARAM_DECORA_PARSER); if (decoraParserClass != null) { try { final Class decoraParserType = ClassLoaderUtil.loadClass(decoraParserClass); decoraParser = (DecoraParser) ClassUtil.newInstance(decoraParserType); } catch (Exception ex) { log.error("Unable to load Decora parser class: " + decoraParserClass, ex); throw new ServletException(ex); } } else { decoraParser = createDecoraParser(); } // final String decoraCache = filterConfig.getInitParameter(PARAM_DECORA_CACHE); if (decoraCache != null) { cached = Converter.get().toBoolean(decoraCache, false); } }
java
{ "resource": "" }
q171086
FindFile.onFile
test
public FindFile onFile(final Consumer<File> fileConsumer) { if (consumers == null) { consumers = Consumers.of(fileConsumer); } else { consumers.add(fileConsumer); } return this; }
java
{ "resource": "" }
q171087
FindFile.searchPath
test
public FindFile searchPath(final URI searchPath) { File file; try { file = new File(searchPath); } catch (Exception ex) { throw new FindFileException("URI error: " + searchPath, ex); } addPath(file); return this; }
java
{ "resource": "" }
q171088
FindFile.searchPath
test
public FindFile searchPath(final URL searchPath) { File file = FileUtil.toContainerFile(searchPath); if (file == null) { throw new FindFileException("URL error: " + searchPath); } addPath(file); return this; }
java
{ "resource": "" }
q171089
FindFile.include
test
public FindFile include(final String... patterns) { for (String pattern : patterns) { rules.include(pattern); } return this; }
java
{ "resource": "" }
q171090
FindFile.exclude
test
public FindFile exclude(final String... patterns) { for (String pattern : patterns) { rules.exclude(pattern); } return this; }
java
{ "resource": "" }
q171091
FindFile.addPath
test
protected void addPath(final File path) { if (!path.exists()) { return; } if (pathList == null) { pathList = new LinkedList<>(); } pathList.add(path); }
java
{ "resource": "" }
q171092
FindFile.findAll
test
public List<File> findAll() { List<File> allFiles = new ArrayList<>(); File file; while ((file = nextFile()) != null) { allFiles.add(file); } return allFiles; }
java
{ "resource": "" }
q171093
FindFile.init
test
protected void init() { rules.detectMode(); todoFiles = new LinkedList<>(); todoFolders = new LinkedList<>(); if (pathList == null) { pathList = new LinkedList<>(); return; } if (pathListOriginal == null) { pathListOriginal = (LinkedList<File>) pathList.clone(); } String[] files = new String[pathList.size()]; int index = 0; Iterator<File> iterator = pathList.iterator(); while (iterator.hasNext()) { File file = iterator.next(); if (file.isFile()) { files[index++] = file.getAbsolutePath(); iterator.remove(); } } if (index != 0) { FilesIterator filesIterator = new FilesIterator(files); todoFiles.add(filesIterator); } }
java
{ "resource": "" }
q171094
FindFile.iterator
test
@Override public Iterator<File> iterator() { return new Iterator<File>() { private File nextFile; @Override public boolean hasNext() { nextFile = nextFile(); return nextFile != null; } @Override public File next() { if (nextFile == null) { throw new NoSuchElementException(); } return nextFile; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
java
{ "resource": "" }
q171095
AnnotationResolver.resolveBeanWiringMode
test
public WiringMode resolveBeanWiringMode(final Class type) { PetiteBean petiteBean = ((Class<?>) type).getAnnotation(PetiteBean.class); return petiteBean != null ? petiteBean.wiring() : WiringMode.DEFAULT; }
java
{ "resource": "" }
q171096
AnnotationResolver.resolveBeanName
test
public String resolveBeanName(final Class type, final boolean useLongTypeName) { PetiteBean petiteBean = ((Class<?>)type).getAnnotation(PetiteBean.class); String name = null; if (petiteBean != null) { name = petiteBean.value().trim(); } if ((name == null) || (name.length() == 0)) { if (useLongTypeName) { name = type.getName(); } else { name = StringUtil.uncapitalize(type.getSimpleName()); } } return name; }
java
{ "resource": "" }
q171097
Buffer.getWriter
test
public PrintWriter getWriter() { if (outWriter == null) { if (outStream != null) { throw new IllegalStateException("Can't call getWriter() after getOutputStream()"); } bufferedWriter = new FastCharArrayWriter(); outWriter = new PrintWriter(bufferedWriter) { @Override public void close() { // do not close the print writer after rendering // since it will remove reference to bufferedWriter } }; } return outWriter; }
java
{ "resource": "" }
q171098
Buffer.getOutputStream
test
public ServletOutputStream getOutputStream() { if (outStream == null) { if (outWriter != null) { throw new IllegalStateException("Can't call getOutputStream() after getWriter()"); } bufferOutputStream = new FastByteArrayServletOutputStream(); outStream = bufferOutputStream; } return outStream; }
java
{ "resource": "" }
q171099
Type.getClassName
test
public String getClassName() { switch (sort) { case VOID: return "void"; case BOOLEAN: return "boolean"; case CHAR: return "char"; case BYTE: return "byte"; case SHORT: return "short"; case INT: return "int"; case FLOAT: return "float"; case LONG: return "long"; case DOUBLE: return "double"; case ARRAY: StringBuilder stringBuilder = new StringBuilder(getElementType().getClassName()); for (int i = getDimensions(); i > 0; --i) { stringBuilder.append("[]"); } return stringBuilder.toString(); case OBJECT: case INTERNAL: return valueBuffer.substring(valueBegin, valueEnd).replace('/', '.'); default: throw new AssertionError(); } }
java
{ "resource": "" }