_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q171800 | JoddJoy.printLogo | test | private void printLogo() {
System.out.println(Chalk256.chalk().yellow().on(Jodd.JODD));
} | java | {
"resource": ""
} |
q171801 | JoddJoy.stop | test | public void stop() {
joyProps.stop();
try {
joyDb.stop();
joyPetite.stop();
}
catch (Exception ignore) {
}
if (log != null) {
log.info("Joy is down. Bye, bye!");
}
} | java | {
"resource": ""
} |
q171802 | SocketHttpConnectionProvider.createSocket | test | protected Socket createSocket(final String host, final int port, final int connectionTimeout) throws IOException {
final SocketFactory socketFactory = getSocketFactory(proxy, false, false, connectionTimeout);
if (connectionTimeout < 0) {
return socketFactory.createSocket(host, port);
}
else {
// creates unconnected socket
Socket socket = socketFactory.createSocket();
socket.connect(new InetSocketAddress(host, port), connectionTimeout);
return socket;
}
} | java | {
"resource": ""
} |
q171803 | SocketHttpConnectionProvider.createSSLSocket | test | protected SSLSocket createSSLSocket(
final String host, final int port, final int connectionTimeout,
final boolean trustAll, final boolean verifyHttpsHost) throws IOException {
final SocketFactory socketFactory = getSocketFactory(proxy, true, trustAll, connectionTimeout);
final Socket socket;
if (connectionTimeout < 0) {
socket = socketFactory.createSocket(host, port);
}
else {
// creates unconnected socket
// unfortunately, this does not work always
// sslSocket = (SSLSocket) socketFactory.createSocket();
// sslSocket.connect(new InetSocketAddress(host, port), connectionTimeout);
//
// Note: SSLSocketFactory has several create() methods.
// Those that take arguments all connect immediately
// and have no options for specifying a connection timeout.
//
// So, we have to create a socket and connect it (with a
// connection timeout), then have the SSLSocketFactory wrap
// the already-connected socket.
//
socket = Sockets.connect(host, port, connectionTimeout);
//sock.setSoTimeout(readTimeout);
//socket.connect(new InetSocketAddress(host, port), connectionTimeout);
// continue to wrap this plain socket with ssl socket...
}
// wrap plain socket in an SSL socket
SSLSocket sslSocket;
if (socket instanceof SSLSocket) {
sslSocket = (SSLSocket) socket;
}
else {
if (socketFactory instanceof SSLSocketFactory) {
sslSocket = (SSLSocket) ((SSLSocketFactory)socketFactory).createSocket(socket, host, port, true);
}
else {
sslSocket = (SSLSocket) (getDefaultSSLSocketFactory(trustAll)).createSocket(socket, host, port, true);
}
}
// sslSocket is now ready
if (secureEnabledProtocols != null) {
final String[] values = StringUtil.splitc(secureEnabledProtocols, ',');
StringUtil.trimAll(values);
sslSocket.setEnabledProtocols(values);
}
// set SSL parameters to allow host name verifier
if (verifyHttpsHost) {
final SSLParameters sslParams = new SSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
sslSocket.setSSLParameters(sslParams);
}
return sslSocket;
} | java | {
"resource": ""
} |
q171804 | SocketHttpConnectionProvider.getDefaultSSLSocketFactory | test | protected SSLSocketFactory getDefaultSSLSocketFactory(final boolean trustAllCertificates) throws IOException {
if (trustAllCertificates) {
try {
SSLContext sc = SSLContext.getInstance(sslProtocol);
sc.init(null, TrustManagers.TRUST_ALL_CERTS, new java.security.SecureRandom());
return sc.getSocketFactory();
}
catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new IOException(e);
}
} else {
return (SSLSocketFactory) SSLSocketFactory.getDefault();
}
} | java | {
"resource": ""
} |
q171805 | SocketHttpConnectionProvider.getSocketFactory | test | protected SocketFactory getSocketFactory(
final ProxyInfo proxy,
final boolean ssl,
final boolean trustAllCertificates,
final int connectionTimeout) throws IOException {
switch (proxy.getProxyType()) {
case NONE:
if (ssl) {
return getDefaultSSLSocketFactory(trustAllCertificates);
}
else {
return SocketFactory.getDefault();
}
case HTTP:
return new HTTPProxySocketFactory(proxy, connectionTimeout);
case SOCKS4:
return new Socks4ProxySocketFactory(proxy, connectionTimeout);
case SOCKS5:
return new Socks5ProxySocketFactory(proxy, connectionTimeout);
default:
return null;
}
} | java | {
"resource": ""
} |
q171806 | RandomString.random | test | public String random(int count, final char[] chars) {
if (count == 0) {
return StringPool.EMPTY;
}
final char[] result = new char[count];
while (count-- > 0) {
result[count] = chars[rnd.nextInt(chars.length)];
}
return new String(result);
} | java | {
"resource": ""
} |
q171807 | RandomString.random | test | public String random(int count, final char start, final char end) {
if (count == 0) {
return StringPool.EMPTY;
}
final char[] result = new char[count];
final int len = end - start + 1;
while (count-- > 0) {
result[count] = (char) (rnd.nextInt(len) + start);
}
return new String(result);
} | java | {
"resource": ""
} |
q171808 | RandomString.randomRanges | test | public String randomRanges(int count, final char... ranges) {
if (count == 0) {
return StringPool.EMPTY;
}
int i = 0;
int len = 0;
final int[] lens = new int[ranges.length];
while (i < ranges.length) {
int gap = ranges[i + 1] - ranges[i] + 1;
len += gap;
lens[i] = len;
i += 2;
}
final char[] result = new char[count];
while (count-- > 0) {
char c = 0;
int r = rnd.nextInt(len);
for (i = 0; i < ranges.length; i += 2) {
if (r < lens[i]) {
r += ranges[i];
if (i != 0) {
r -= lens[i - 2];
}
c = (char) r;
break;
}
}
result[count] = c;
}
return new String(result);
} | java | {
"resource": ""
} |
q171809 | JsonParserBase.newArrayInstance | test | @SuppressWarnings("unchecked")
protected Collection<Object> newArrayInstance(final Class targetType) {
if (targetType == null ||
targetType == List.class ||
targetType == Collection.class ||
targetType.isArray()) {
return listSupplier.get();
}
if (targetType == Set.class) {
return new HashSet<>();
}
try {
return (Collection<Object>) targetType.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new JsonException(e);
}
} | java | {
"resource": ""
} |
q171810 | JsonParserBase.injectValueIntoObject | test | protected void injectValueIntoObject(final Object target, final PropertyDescriptor pd, final Object value) {
Object convertedValue = value;
if (value != null) {
Class targetClass = pd.getType();
convertedValue = convertType(value, targetClass);
}
try {
Setter setter = pd.getSetter(true);
if (setter != null) {
setter.invokeSetter(target, convertedValue);
}
} catch (Exception ex) {
throw new JsonException(ex);
}
} | java | {
"resource": ""
} |
q171811 | JsonParserBase.convertType | test | protected Object convertType(final Object value, final Class targetType) {
final Class valueClass = value.getClass();
if (valueClass == targetType) {
return value;
}
try {
return TypeConverterManager.get().convertType(value, targetType);
}
catch (Exception ex) {
if (!strictTypes) {
return null;
}
throw new JsonException("Type conversion failed", ex);
}
} | java | {
"resource": ""
} |
q171812 | ModuleVisitor.visitProvide | test | public void visitProvide(final String service, final String... providers) {
if (mv != null) {
mv.visitProvide(service, providers);
}
} | java | {
"resource": ""
} |
q171813 | TypeCache.createDefault | test | @SuppressWarnings("unchecked")
public static <A> TypeCache<A> createDefault() {
return (TypeCache<A>)Defaults.implementation.get();
} | java | {
"resource": ""
} |
q171814 | TypeCache.put | test | public T put(final Class<?> type, final T value) {
return map.put(type, value);
} | java | {
"resource": ""
} |
q171815 | Methods.getAllMethodDescriptors | test | public MethodDescriptor[] getAllMethodDescriptors() {
if (allMethods == null) {
final List<MethodDescriptor> allMethodsList = new ArrayList<>();
for (MethodDescriptor[] methodDescriptors : methodsMap.values()) {
Collections.addAll(allMethodsList, methodDescriptors);
}
final MethodDescriptor[] allMethods = allMethodsList.toArray(new MethodDescriptor[0]);
Arrays.sort(allMethods, Comparator.comparing(md -> md.getMethod().getName()));
this.allMethods = allMethods;
}
return allMethods;
} | java | {
"resource": ""
} |
q171816 | NetUtil.resolveIpAddress | test | public static String resolveIpAddress(final String hostname) {
try {
InetAddress netAddress;
if (hostname == null || hostname.equalsIgnoreCase(LOCAL_HOST)) {
netAddress = InetAddress.getLocalHost();
} else {
netAddress = Inet4Address.getByName(hostname);
}
return netAddress.getHostAddress();
} catch (UnknownHostException ignore) {
return null;
}
} | java | {
"resource": ""
} |
q171817 | NetUtil.getIpAsInt | test | public static int getIpAsInt(final String ipAddress) {
int ipIntValue = 0;
String[] tokens = StringUtil.splitc(ipAddress, '.');
for (String token : tokens) {
if (ipIntValue > 0) {
ipIntValue <<= 8;
}
ipIntValue += Integer.parseInt(token);
}
return ipIntValue;
} | java | {
"resource": ""
} |
q171818 | NetUtil.validateAgaintIPAdressV4Format | test | public static boolean validateAgaintIPAdressV4Format(final String input) {
if (input == null) {
return false;
}
int hitDots = 0;
char[] data = input.toCharArray();
for (int i = 0; i < data.length; i++) {
char c = data[i];
int b = 0;
do {
if (c < '0' || c > '9') {
return false;
}
b = (b * 10 + c) - 48;
if (++i >= data.length) {
break;
}
c = data[i];
} while (c != '.');
if (b > 255) {
return false;
}
hitDots++;
}
return hitDots == 4;
} | java | {
"resource": ""
} |
q171819 | NetUtil.resolveHostName | test | public static String resolveHostName(final byte[] ip) {
try {
InetAddress address = InetAddress.getByAddress(ip);
return address.getHostName();
} catch (UnknownHostException ignore) {
return null;
}
} | java | {
"resource": ""
} |
q171820 | NetUtil.downloadBytes | test | public static byte[] downloadBytes(final String url) throws IOException {
try (InputStream inputStream = new URL(url).openStream()) {
return StreamUtil.readBytes(inputStream);
}
} | java | {
"resource": ""
} |
q171821 | NetUtil.downloadString | test | public static String downloadString(final String url, final String encoding) throws IOException {
try (InputStream inputStream = new URL(url).openStream()) {
return new String(StreamUtil.readChars(inputStream, encoding));
}
} | java | {
"resource": ""
} |
q171822 | NetUtil.downloadFile | test | public static void downloadFile(final String url, final File file) throws IOException {
try (
InputStream inputStream = new URL(url).openStream();
ReadableByteChannel rbc = Channels.newChannel(inputStream);
FileChannel fileChannel = FileChannel.open(
file.toPath(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE)
) {
fileChannel.transferFrom(rbc, 0, Long.MAX_VALUE);
}
} | java | {
"resource": ""
} |
q171823 | ServletConfigInterceptor.inject | test | protected void inject(final ActionRequest actionRequest) {
final Targets targets = actionRequest.getTargets();
final ServletContext servletContext = actionRequest.getHttpServletRequest().getServletContext();
scopeResolver.forEachScope(madvocScope -> madvocScope.inject(servletContext, targets));
scopeResolver.forEachScope(madvocScope -> madvocScope.inject(actionRequest, targets));
} | java | {
"resource": ""
} |
q171824 | ServletConfigInterceptor.outject | test | protected void outject(final ActionRequest actionRequest) {
final Targets targets = actionRequest.getTargets();
scopeResolver.forEachScope(madvocScope -> madvocScope.outject(actionRequest, targets));
} | java | {
"resource": ""
} |
q171825 | Sockets.connect | test | public static Socket connect(final String hostname, final int port) throws IOException {
final Socket socket = new Socket();
socket.connect(new InetSocketAddress(hostname, port));
return socket;
} | java | {
"resource": ""
} |
q171826 | Sockets.connect | test | public static Socket connect(final String hostname, final int port, final int connectionTimeout) throws IOException {
final Socket socket = new Socket();
if (connectionTimeout <= 0) {
socket.connect(new InetSocketAddress(hostname, port));
}
else {
socket.connect(new InetSocketAddress(hostname, port), connectionTimeout);
}
return socket;
} | java | {
"resource": ""
} |
q171827 | DefaultClassLoaderStrategy.getPrimitiveClassNameIndex | test | private static int getPrimitiveClassNameIndex(final String className) {
int dotIndex = className.indexOf('.');
if (dotIndex != -1) {
return -1;
}
return Arrays.binarySearch(PRIMITIVE_TYPE_NAMES, className);
} | java | {
"resource": ""
} |
q171828 | DefaultClassLoaderStrategy.loadClass | test | @Override
public Class loadClass(final String className, final ClassLoader classLoader) throws ClassNotFoundException {
String arrayClassName = prepareArrayClassnameForLoading(className);
if ((className.indexOf('.') == -1) && (arrayClassName == null)) {
// maybe a primitive
int primitiveNdx = getPrimitiveClassNameIndex(className);
if (primitiveNdx >= 0) {
return PRIMITIVE_TYPES[primitiveNdx];
}
}
// try #1 - using provided class loader
if (classLoader != null) {
Class klass = loadClass(className, arrayClassName, classLoader);
if (klass != null) {
return klass;
}
}
// try #2 - using thread class loader
ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
if ((currentThreadClassLoader != null) && (currentThreadClassLoader != classLoader)) {
Class klass = loadClass(className, arrayClassName, currentThreadClassLoader);
if (klass != null) {
return klass;
}
}
// try #3 - using caller classloader, similar as Class.forName()
//Class callerClass = ReflectUtil.getCallerClass(2);
Class callerClass = ClassUtil.getCallerClass();
ClassLoader callerClassLoader = callerClass.getClassLoader();
if ((callerClassLoader != classLoader) && (callerClassLoader != currentThreadClassLoader)) {
Class klass = loadClass(className, arrayClassName, callerClassLoader);
if (klass != null) {
return klass;
}
}
// try #4 - everything failed, try alternative array loader
if (arrayClassName != null) {
try {
return loadArrayClassByComponentType(className, classLoader);
} catch (ClassNotFoundException ignore) {
}
}
throw new ClassNotFoundException("Class not found: " + className);
} | java | {
"resource": ""
} |
q171829 | DefaultClassLoaderStrategy.loadArrayClassByComponentType | test | protected Class loadArrayClassByComponentType(final String className, final ClassLoader classLoader) throws ClassNotFoundException {
int ndx = className.indexOf('[');
int multi = StringUtil.count(className, '[');
String componentTypeName = className.substring(0, ndx);
Class componentType = loadClass(componentTypeName, classLoader);
if (multi == 1) {
return Array.newInstance(componentType, 0).getClass();
}
int[] multiSizes;
if (multi == 2) {
multiSizes = new int[] {0, 0};
} else if (multi == 3) {
multiSizes = new int[] {0, 0, 0};
} else {
multiSizes = (int[]) Array.newInstance(int.class, multi);
}
return Array.newInstance(componentType, multiSizes).getClass();
} | java | {
"resource": ""
} |
q171830 | SingletonScope.shutdown | test | @Override
public void shutdown() {
for (final BeanData beanData : instances.values()) {
beanData.callDestroyMethods();
}
instances.clear();
} | java | {
"resource": ""
} |
q171831 | BinarySearch.forArray | test | public static <T extends Comparable> BinarySearch<T> forArray(final T[] array) {
return new BinarySearch<T>() {
@Override
@SuppressWarnings( {"unchecked"})
protected int compare(final int index, final T element) {
return array[index].compareTo(element);
}
@Override
protected int getLastIndex() {
return array.length - 1;
}
};
} | java | {
"resource": ""
} |
q171832 | BinarySearch.forArray | test | public static <T> BinarySearch<T> forArray(final T[] array, final Comparator<T> comparator) {
return new BinarySearch<T>() {
@Override
@SuppressWarnings( {"unchecked"})
protected int compare(final int index, final T element) {
return comparator.compare(array[index], element);
}
@Override
protected int getLastIndex() {
return array.length - 1;
}
};
} | java | {
"resource": ""
} |
q171833 | BeanVisitorImplBase.exclude | test | public T exclude(final String... excludes) {
for (String ex : excludes) {
rules.exclude(ex);
}
return _this();
} | java | {
"resource": ""
} |
q171834 | BeanVisitorImplBase.include | test | public T include(final String... includes) {
for (String in : includes) {
rules.include(in);
}
return _this();
} | java | {
"resource": ""
} |
q171835 | BeanVisitorImplBase.includeAs | test | public T includeAs(final Class template) {
blacklist = false;
String[] properties = getAllBeanPropertyNames(template, false);
include(properties);
return _this();
} | java | {
"resource": ""
} |
q171836 | ParsedTag.start | test | public void start(final int startIndex) {
this.tagStartIndex = startIndex;
this.name = null;
this.idNdx = -1;
this.attributesCount = 0;
this.tagLength = 0;
this.modified = false;
this.type = TagType.START;
this.rawTag = false;
} | java | {
"resource": ""
} |
q171837 | MadvocContainer.registerComponent | test | public <T> void registerComponent(final String name, final Class<T> component, final Consumer<T> consumer) {
log.debug(() -> "Madvoc WebApp component: [" + name + "] --> " + component.getName());
madpc.removeBean(name);
madpc.registerPetiteBean(component, name, null, null, false, consumer);
} | java | {
"resource": ""
} |
q171838 | DbOomQuery.resolveColumnDbSqlType | test | protected void resolveColumnDbSqlType(final Connection connection, final DbEntityColumnDescriptor dec) {
if (dec.dbSqlType != SqlType.DB_SQLTYPE_UNKNOWN) {
return;
}
ResultSet rs = null;
DbEntityDescriptor ded = dec.getDbEntityDescriptor();
try {
DatabaseMetaData dmd = connection.getMetaData();
rs = dmd.getColumns(null, ded.getSchemaName(), ded.getTableName(), dec.getColumnName());
if (rs.next()) {
dec.dbSqlType = rs.getInt("DATA_TYPE");
} else {
dec.dbSqlType = SqlType.DB_SQLTYPE_NOT_AVAILABLE;
if (log.isWarnEnabled()) {
log.warn("Column SQL type not available: " + ded.toString() + '.' + dec.getColumnName());
}
}
} catch (SQLException sex) {
dec.dbSqlType = SqlType.DB_SQLTYPE_NOT_AVAILABLE;
if (log.isWarnEnabled()) {
log.warn("Column SQL type not resolved: " + ded.toString() + '.' + dec.getColumnName(), sex);
}
} finally {
DbUtil.close(rs);
}
} | java | {
"resource": ""
} |
q171839 | DbOomQuery.preprocessSql | test | protected String preprocessSql(String sqlString) {
// detects callable statement
if (sqlString.charAt(0) == '{') {
return sqlString;
}
// quickly detect if SQL string is a key
if (!CharUtil.isAlpha(sqlString.charAt(0))) {
sqlString = sqlString.substring(1);
}
else if (sqlString.indexOf(' ') != -1) {
return sqlString;
}
final String sqlFromMap = dbOom.queryMap().getQuery(sqlString);
if (sqlFromMap != null) {
sqlString = sqlFromMap.trim();
}
return sqlString;
} | java | {
"resource": ""
} |
q171840 | DbOomQuery.createResultSetMapper | test | protected ResultSetMapper createResultSetMapper(final ResultSet resultSet) {
final Map<String, ColumnData> columnAliases = sqlgen != null ? sqlgen.getColumnData() : null;
return new DefaultResultSetMapper(dbOom, resultSet, columnAliases, cacheEntities, this);
} | java | {
"resource": ""
} |
q171841 | DbOomQuery.findGeneratedKey | test | public <T> T findGeneratedKey(final Class<T> type) {
return find(new Class[] {type}, false, getGeneratedColumns());
} | java | {
"resource": ""
} |
q171842 | DbOomQuery.populateGeneratedKeys | test | public void populateGeneratedKeys(final Object entity) {
final String[] generatedColumns = getGeneratedColumnNames();
if (generatedColumns == null) {
return;
}
DbEntityDescriptor ded = dbOom.entityManager().lookupType(entity.getClass());
// prepare key types
Class[] keyTypes = new Class[generatedColumns.length];
String[] properties = new String[generatedColumns.length];
for (int i = 0; i < generatedColumns.length; i++) {
String column = generatedColumns[i];
DbEntityColumnDescriptor decd = ded.findByColumnName(column);
if (decd != null) {
keyTypes[i] = decd.getPropertyType();
properties[i] = decd.getPropertyName();
}
}
final Object keyValues = findGeneratedColumns(keyTypes);
if (!keyValues.getClass().isArray()) {
BeanUtil.declared.setProperty(entity, properties[0], keyValues);
} else {
for (int i = 0; i < properties.length; i++) {
BeanUtil.declared.setProperty(entity, properties[i], ((Object[]) keyValues)[i]);
}
}
} | java | {
"resource": ""
} |
q171843 | PetiteInterceptorManager.createWrapper | test | @Override
protected <R extends ActionInterceptor> R createWrapper(final Class<R> wrapperClass) {
return petiteContainer.createBean(wrapperClass);
} | java | {
"resource": ""
} |
q171844 | DbQuery.setBean | test | public Q setBean(final String beanName, final Object bean) {
if (bean == null) {
return _this();
}
init();
final String beanNamePrefix = beanName + '.';
query.forEachNamedParameter(p -> {
final String paramName = p.name;
if (paramName.startsWith(beanNamePrefix)) {
final String propertyName = paramName.substring(beanNamePrefix.length());
if (BeanUtil.declared.hasRootProperty(bean, propertyName)) {
final Object value = BeanUtil.declared.getProperty(bean, propertyName);
setObject(paramName, value);
}
}
});
return _this();
} | java | {
"resource": ""
} |
q171845 | DbQuery.setMap | test | public Q setMap(final Map parameters) {
if (parameters == null) {
return _this();
}
init();
query.forEachNamedParameter(p -> {
final String paramName = p.name;
setObject(paramName, parameters.get(paramName));
});
return _this();
} | java | {
"resource": ""
} |
q171846 | DbQuery.setObjects | test | public Q setObjects(final Object... objects) {
int index = 1;
for (final Object object : objects) {
setObject(index++, object);
}
return _this();
} | java | {
"resource": ""
} |
q171847 | SqlChunk.insertChunkAfter | test | public void insertChunkAfter(final SqlChunk previous) {
SqlChunk next = previous.nextChunk;
previous.nextChunk = this;
this.previousChunk = previous;
if (next != null) {
next.previousChunk = this;
this.nextChunk = next;
}
} | java | {
"resource": ""
} |
q171848 | SqlChunk.lookupType | test | protected DbEntityDescriptor lookupType(final Class entity) {
final DbEntityDescriptor ded = dbEntityManager.lookupType(entity);
if (ded == null) {
throw new DbSqlBuilderException("Invalid or not-persistent entity: " + entity.getName());
}
return ded;
} | java | {
"resource": ""
} |
q171849 | SqlChunk.findColumnRef | test | protected DbEntityDescriptor findColumnRef(final String columnRef) {
DbEntityDescriptor ded = templateData.findTableDescriptorByColumnRef(columnRef);
if (ded == null) {
throw new DbSqlBuilderException("Invalid column reference: [" + columnRef + "]");
}
return ded;
} | java | {
"resource": ""
} |
q171850 | SqlChunk.resolveTable | test | protected String resolveTable(final String tableRef, final DbEntityDescriptor ded) {
String tableAlias = templateData.getTableAlias(tableRef);
if (tableAlias != null) {
return tableAlias;
}
return ded.getTableNameForQuery();
} | java | {
"resource": ""
} |
q171851 | SqlChunk.resolveClass | test | protected static Class resolveClass(final Object object) {
Class type = object.getClass();
return type == Class.class ? (Class) object : type;
} | java | {
"resource": ""
} |
q171852 | SqlChunk.appendMissingSpace | test | protected void appendMissingSpace(final StringBuilder out) {
int len = out.length();
if (len == 0) {
return;
}
len--;
if (!CharUtil.isWhitespace(out.charAt(len))) {
out.append(' ');
}
} | java | {
"resource": ""
} |
q171853 | MultipartRequestWrapper.getFileParameterNames | test | public Enumeration<String> getFileParameterNames() {
if (mreq == null) {
return null;
}
return Collections.enumeration(mreq.getFileParameterNames());
} | java | {
"resource": ""
} |
q171854 | DispatcherUtil.include | test | public static boolean include(final ServletRequest request, final ServletResponse response, final String page) throws IOException, ServletException {
RequestDispatcher dispatcher = request.getRequestDispatcher(page);
if (dispatcher != null) {
dispatcher.include(request, response);
return true;
}
return false;
} | java | {
"resource": ""
} |
q171855 | DispatcherUtil.getUrl | test | public static String getUrl(final HttpServletRequest request) {
String servletPath = request.getServletPath();
String query = request.getQueryString();
if ((query != null) && (query.length() != 0)) {
servletPath += '?' + query;
}
return servletPath;
} | java | {
"resource": ""
} |
q171856 | DispatcherUtil.getRequestUri | test | public static String getRequestUri(final HttpServletRequest request) {
String result = getIncludeRequestUri(request);
if (result == null) {
result = request.getRequestURI();
}
return result;
} | java | {
"resource": ""
} |
q171857 | ActionMethodParamNameResolver.resolveParamNames | test | public String[] resolveParamNames(final Method actionClassMethod) {
MethodParameter[] methodParameters = Paramo.resolveParameters(actionClassMethod);
String[] names = new String[methodParameters.length];
for (int i = 0; i < methodParameters.length; i++) {
names[i] = methodParameters[i].getName();
}
return names;
} | java | {
"resource": ""
} |
q171858 | JoyPetite.start | test | @Override
public void start() {
initLogger();
log.info("PETITE start ----------");
petiteContainer = createPetiteContainer();
if (externalsCache) {
petiteContainer.setExternalsCache(TypeCache.createDefault());
}
log.info("Web application? " + isWebApplication);
if (!isWebApplication) {
// make session scope to act as singleton scope
// if this is not a web application (and http session is not available).
petiteContainer.registerScope(SessionScope.class, new SingletonScope(petiteContainer));
}
// load parameters from properties files
petiteContainer.defineParameters(joyPropsSupplier.get().getProps());
// automagic configuration
if (autoConfiguration) {
final AutomagicPetiteConfigurator automagicPetiteConfigurator =
new AutomagicPetiteConfigurator(petiteContainer);
automagicPetiteConfigurator.registerAsConsumer(joyScannerSupplier.get().getClassScanner());
}
petiteContainerConsumers.accept(this.petiteContainer);
log.info("PETITE OK!");
} | java | {
"resource": ""
} |
q171859 | JoyPetite.stop | test | @Override
public void stop() {
if (log != null) {
log.info("PETITE stop");
}
if (petiteContainer != null) {
petiteContainer.shutdown();
}
petiteContainer = null;
} | java | {
"resource": ""
} |
q171860 | EmailFilter.subject | test | public EmailFilter subject(final String subject) {
final SearchTerm subjectTerm = new SubjectTerm(subject);
concat(subjectTerm);
return this;
} | java | {
"resource": ""
} |
q171861 | EmailFilter.messageId | test | public EmailFilter messageId(final String messageId) {
final SearchTerm msgIdTerm = new MessageIDTerm(messageId);
concat(msgIdTerm);
return this;
} | java | {
"resource": ""
} |
q171862 | EmailFilter.from | test | public EmailFilter from(final String fromAddress) {
final SearchTerm fromTerm = new FromStringTerm(fromAddress);
concat(fromTerm);
return this;
} | java | {
"resource": ""
} |
q171863 | EmailFilter.to | test | public EmailFilter to(final String toAddress) {
final SearchTerm toTerm = new RecipientStringTerm(RecipientType.TO, toAddress);
concat(toTerm);
return this;
} | java | {
"resource": ""
} |
q171864 | EmailFilter.cc | test | public EmailFilter cc(final String ccAddress) {
final SearchTerm toTerm = new RecipientStringTerm(RecipientType.CC, ccAddress);
concat(toTerm);
return this;
} | java | {
"resource": ""
} |
q171865 | EmailFilter.bcc | test | public EmailFilter bcc(final String bccAddress) {
final SearchTerm toTerm = new RecipientStringTerm(RecipientType.BCC, bccAddress);
concat(toTerm);
return this;
} | java | {
"resource": ""
} |
q171866 | EmailFilter.flags | test | public EmailFilter flags(final Flags flags, final boolean value) {
final SearchTerm flagTerm = new FlagTerm(flags, value);
concat(flagTerm);
return this;
} | java | {
"resource": ""
} |
q171867 | EmailFilter.flag | test | public EmailFilter flag(final Flag flag, final boolean value) {
final Flags flags = new Flags();
flags.add(flag);
return flags(flags, value);
} | java | {
"resource": ""
} |
q171868 | EmailFilter.receivedDate | test | public EmailFilter receivedDate(final Operator operator, final long milliseconds) {
final SearchTerm term = new ReceivedDateTerm(operator.value, new Date(milliseconds));
concat(term);
return this;
} | java | {
"resource": ""
} |
q171869 | EmailFilter.sentDate | test | public EmailFilter sentDate(final Operator operator, final long milliseconds) {
final SearchTerm term = new SentDateTerm(operator.value, new Date(milliseconds));
concat(term);
return this;
} | java | {
"resource": ""
} |
q171870 | EmailFilter.size | test | public EmailFilter size(final Operator comparison, final int size) {
final SearchTerm term = new SizeTerm(comparison.value, size);
concat(term);
return this;
} | java | {
"resource": ""
} |
q171871 | EmailFilter.and | test | public EmailFilter and(final EmailFilter... emailFilters) {
final SearchTerm[] searchTerms = new SearchTerm[emailFilters.length];
for (int i = 0; i < emailFilters.length; i++) {
searchTerms[i] = emailFilters[i].searchTerm;
}
concat(new AndTerm(searchTerms));
return this;
} | java | {
"resource": ""
} |
q171872 | EmailFilter.or | test | public EmailFilter or(final EmailFilter... emailFilters) {
final SearchTerm[] searchTerms = new SearchTerm[emailFilters.length];
for (int i = 0; i < emailFilters.length; i++) {
searchTerms[i] = emailFilters[i].searchTerm;
}
concat(new OrTerm(searchTerms));
return this;
} | java | {
"resource": ""
} |
q171873 | EmailFilter.not | test | public EmailFilter not(final EmailFilter emailFilter) {
final SearchTerm searchTerm = new NotTerm(emailFilter.searchTerm);
concat(searchTerm);
return this;
} | java | {
"resource": ""
} |
q171874 | EmailFilter.concat | test | protected void concat(SearchTerm searchTerm) {
if (nextIsNot) {
searchTerm = new NotTerm(searchTerm);
nextIsNot = false;
}
if (operatorAnd) {
and(searchTerm);
} else {
or(searchTerm);
}
} | java | {
"resource": ""
} |
q171875 | Base32.encode | test | public static String encode(final byte[] bytes) {
StringBuilder base32 = new StringBuilder((bytes.length * 8 + 4) / 5);
int currByte, digit, i = 0;
while (i < bytes.length) {
// STEP 0; insert new 5 bits, leave 3 bits
currByte = bytes[i++] & 255;
base32.append(CHARS[currByte >> 3]);
digit = (currByte & 7) << 2;
if (i >= bytes.length) {
base32.append(CHARS[digit]);
break;
}
// STEP 3: insert 2 new bits, then 5 bits, leave 1 bit
currByte = bytes[i++] & 255;
base32.append(CHARS[digit | (currByte >> 6)]);
base32.append(CHARS[(currByte >> 1) & 31]);
digit = (currByte & 1) << 4;
if (i >= bytes.length) {
base32.append(CHARS[digit]);
break;
}
// STEP 1: insert 4 new bits, leave 4 bit
currByte = bytes[i++] & 255;
base32.append(CHARS[digit | (currByte >> 4)]);
digit = (currByte & 15) << 1;
if (i >= bytes.length) {
base32.append(CHARS[digit]);
break;
}
// STEP 4: insert 1 new bit, then 5 bits, leave 2 bits
currByte = bytes[i++] & 255;
base32.append(CHARS[digit | (currByte >> 7)]);
base32.append(CHARS[(currByte >> 2) & 31]);
digit = (currByte & 3) << 3;
if (i >= bytes.length) {
base32.append(CHARS[digit]);
break;
}
// STEP 2: insert 3 new bits, then 5 bits, leave 0 bit
currByte = bytes[i++] & 255;
base32.append(CHARS[digit | (currByte >> 5)]);
base32.append(CHARS[currByte & 31]);
}
return base32.toString();
} | java | {
"resource": ""
} |
q171876 | ByteArrayConverter.convertValueToArray | test | protected byte[] convertValueToArray(final Object value) {
if (value instanceof Blob) {
final Blob blob = (Blob) value;
try {
final long length = blob.length();
if (length > Integer.MAX_VALUE) {
throw new TypeConversionException("Blob is too big.");
}
return blob.getBytes(1, (int) length);
} catch (SQLException sex) {
throw new TypeConversionException(value, sex);
}
}
if (value instanceof File) {
try {
return FileUtil.readBytes((File) value);
} catch (IOException ioex) {
throw new TypeConversionException(value, ioex);
}
}
if (value instanceof Collection) {
final Collection collection = (Collection) value;
final byte[] target = new byte[collection.size()];
int i = 0;
for (final Object element : collection) {
target[i] = convertType(element);
i++;
}
return target;
}
if (value instanceof Iterable) {
final Iterable iterable = (Iterable) value;
final ArrayList<Byte> byteArrayList = new ArrayList<>();
for (final Object element : iterable) {
final byte convertedValue = convertType(element);
byteArrayList.add(Byte.valueOf(convertedValue));
}
final byte[] array = new byte[byteArrayList.size()];
for (int i = 0; i < byteArrayList.size(); i++) {
final Byte b = byteArrayList.get(i);
array[i] = b.byteValue();
}
return array;
}
if (value instanceof CharSequence) {
final String[] strings = StringUtil.splitc(value.toString(), ArrayConverter.NUMBER_DELIMITERS);
return convertArrayToArray(strings);
}
// everything else:
return convertToSingleElementArray(value);
} | java | {
"resource": ""
} |
q171877 | GzipFilter.isGzipEligible | test | protected boolean isGzipEligible(final HttpServletRequest request) {
// request parameter name
if (requestParameterName.length() != 0) {
String forceGzipString = request.getParameter(requestParameterName);
if (forceGzipString != null) {
return Converter.get().toBooleanValue(forceGzipString, false);
}
}
// extract uri
String uri = request.getRequestURI();
if (uri == null) {
return false;
}
uri = uri.toLowerCase();
boolean result = false;
// check uri
if (matches == null) { // match == *
if (extensions == null) { // extensions == *
return true;
}
// extension
String extension = FileNameUtil.getExtension(uri);
if (extension.length() > 0) {
extension = extension.toLowerCase();
if (StringUtil.equalsOne(extension, extensions) != -1) {
result = true;
}
}
} else {
if (wildcards) {
result = Wildcard.matchPathOne(uri, matches) != -1;
} else {
for (String match : matches) {
if (uri.contains(match)) {
result = true;
break;
}
}
}
}
if ((result) && (excludes != null)) {
if (wildcards) {
if (Wildcard.matchPathOne(uri, excludes) != -1) {
result = false;
}
} else {
for (String exclude : excludes) {
if (uri.contains(exclude)) {
result = false; // excludes founded
break;
}
}
}
}
return result;
} | java | {
"resource": ""
} |
q171878 | Vtor.validate | test | public List<Violation> validate(final Object target) {
return validate(ValidationContext.resolveFor(target.getClass()), target);
} | java | {
"resource": ""
} |
q171879 | Vtor.validate | test | public List<Violation> validate(final ValidationContext ctx, final Object target, final String targetName) {
for (Map.Entry<String, List<Check>> entry : ctx.map.entrySet()) {
String name = entry.getKey();
Object value = BeanUtil.declaredSilent.getProperty(target, name);
String valueName = targetName != null ? (targetName + '.' + name) : name; // move up
ValidationConstraintContext vcc = new ValidationConstraintContext(this, target, valueName);
for (Check check : entry.getValue()) {
String[] checkProfiles = check.getProfiles();
if (!matchProfiles(checkProfiles)) {
continue;
}
if (check.getSeverity() < severity) {
continue;
}
ValidationConstraint constraint = check.getConstraint();
if (!constraint.isValid(vcc, value)) {
addViolation(new Violation(valueName, target, value, check));
}
}
}
return getViolations();
} | java | {
"resource": ""
} |
q171880 | Vtor.useProfile | test | public void useProfile(final String profile) {
if (profile == null) {
return;
}
if (this.enabledProfiles == null) {
this.enabledProfiles = new HashSet<>();
}
this.enabledProfiles.add(profile);
} | java | {
"resource": ""
} |
q171881 | Vtor.useProfiles | test | public void useProfiles(final String... enabledProfiles) {
if (enabledProfiles == null) {
return;
}
if (this.enabledProfiles == null) {
this.enabledProfiles = new HashSet<>();
}
Collections.addAll(this.enabledProfiles, enabledProfiles);
} | java | {
"resource": ""
} |
q171882 | Vtor.matchProfiles | test | protected boolean matchProfiles(final String[] checkProfiles) {
// test for all profiles
if ((checkProfiles != null) && (checkProfiles.length == 1) && checkProfiles[0].equals(ALL_PROFILES)) {
return true;
}
if (enabledProfiles == null || enabledProfiles.isEmpty()) {
if (validateAllProfilesByDefault) {
return true; // all profiles are considered as enabled
}
// only default profile is enabled
if ((checkProfiles == null) || (checkProfiles.length == 0)) {
return true;
}
for (String profile : checkProfiles) {
if (StringUtil.isEmpty(profile)) {
return true; // default profile
}
if (profile.equals(DEFAULT_PROFILE)) {
return true;
}
}
return false;
}
// there are enabled profiles
if ((checkProfiles == null) || (checkProfiles.length == 0)) {
return enabledProfiles.contains(DEFAULT_PROFILE);
}
boolean result = false;
for (String profile : checkProfiles) {
boolean b = true;
boolean must = false;
if (StringUtil.isEmpty(profile)) {
profile = DEFAULT_PROFILE;
} else if (profile.charAt(0) == '-') {
profile = profile.substring(1);
b = false;
} else if (profile.charAt(0) == '+') {
profile = profile.substring(1);
must = true;
}
if (enabledProfiles.contains(profile)) {
if (!b) {
return false;
}
result = true;
} else {
if (must) {
return false;
}
}
}
return result;
} | java | {
"resource": ""
} |
q171883 | JsonBodyScope.parseRequestBody | test | protected Object parseRequestBody(final String body, final Class targetType) {
return JsonParser.create().parse(body, targetType);
} | java | {
"resource": ""
} |
q171884 | JulianDate.toMilliseconds | test | public long toMilliseconds() {
double then = (fraction - JD_1970.fraction) * MILLIS_IN_DAY;
then += (integer - JD_1970.integer) * MILLIS_IN_DAY;
then += then > 0 ? 1.0e-6 : -1.0e-6;
return (long) then;
} | java | {
"resource": ""
} |
q171885 | JulianDate.add | test | public JulianDate add(final JulianDate jds) {
int i = this.integer + jds.integer;
double f = this.fraction + jds.fraction;
return new JulianDate(i, f);
} | java | {
"resource": ""
} |
q171886 | JulianDate.sub | test | public JulianDate sub(final JulianDate jds) {
int i = this.integer - jds.integer;
double f = this.fraction -jds.fraction;
return new JulianDate(i, f);
} | java | {
"resource": ""
} |
q171887 | JulianDate.set | test | private void set(final int i, double f) {
integer = i;
int fi = (int) f;
f -= fi;
integer += fi;
if (f < 0) {
f += 1;
integer--;
}
this.fraction = f;
} | java | {
"resource": ""
} |
q171888 | LagartoParser.initialize | test | @Override
protected void initialize(final char[] input) {
super.initialize(input);
this.tag = new ParsedTag();
this.doctype = new ParsedDoctype();
this.text = new char[1024];
this.textLen = 0;
this.parsingTime = -1;
} | java | {
"resource": ""
} |
q171889 | LagartoParser.emitComment | test | protected void emitComment(final int from, final int to) {
if (config.enableConditionalComments) {
// CC: downlevel-hidden starting
if (match(CC_IF, from)) {
int endBracketNdx = find(']', from + 3, to);
CharSequence expression = charSequence(from + 1, endBracketNdx);
ndx = endBracketNdx + 1;
char c = input[ndx];
if (c != '>') {
errorInvalidToken();
}
visitor.condComment(expression, true, true, false);
state = DATA_STATE;
return;
}
if (to > CC_ENDIF2.length && match(CC_ENDIF2, to - CC_ENDIF2.length)) {
// CC: downlevel-hidden ending
visitor.condComment(_ENDIF, false, true, true);
state = DATA_STATE;
return;
}
}
CharSequence comment = charSequence(from, to);
visitor.comment(comment);
commentStart = -1;
} | java | {
"resource": ""
} |
q171890 | LagartoParser._error | test | protected void _error(String message) {
if (config.calculatePosition) {
Position currentPosition = position(ndx);
message = message
.concat(StringPool.SPACE)
.concat(currentPosition.toString());
} else {
message = message
.concat(" [@")
.concat(Integer.toString(ndx))
.concat(StringPool.RIGHT_SQ_BRACKET);
}
visitor.error(message);
} | java | {
"resource": ""
} |
q171891 | PBKDF2Hash.createHash | test | public String createHash(final char[] password) {
// Generate a random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[saltBytes];
random.nextBytes(salt);
// Hash the password
byte[] hash = pbkdf2(password, salt, pbkdf2Iterations, hashBytes);
// format iterations:salt:hash
return pbkdf2Iterations + ":" + StringUtil.toHexString(salt) + ":" + StringUtil.toHexString(hash);
} | java | {
"resource": ""
} |
q171892 | PBKDF2Hash.pbkdf2 | test | private static byte[] pbkdf2(final char[] password, final byte[] salt, final int iterations, final int bytes) {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
try {
SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
return skf.generateSecret(spec).getEncoded();
}
catch (NoSuchAlgorithmException ignore) {
return null;
}
catch (InvalidKeySpecException e) {
throw new IllegalArgumentException(e);
}
} | java | {
"resource": ""
} |
q171893 | PBKDF2Hash.fromHex | test | private static byte[] fromHex(final String hex) {
final byte[] binary = new byte[hex.length() / 2];
for (int i = 0; i < binary.length; i++) {
binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return binary;
} | java | {
"resource": ""
} |
q171894 | PetiteResolvers.resolveProviderDefinitions | test | public ProviderDefinition[] resolveProviderDefinitions(final Class type, final String name) {
return providerResolver.resolve(type, name);
} | java | {
"resource": ""
} |
q171895 | EmailAttachmentBuilder.name | test | public EmailAttachmentBuilder name(final String name) {
if (name != null && !name.trim().isEmpty()) {
this.name = name;
}
return this;
} | java | {
"resource": ""
} |
q171896 | EmailAttachmentBuilder.setContentIdFromNameIfMissing | test | protected EmailAttachmentBuilder setContentIdFromNameIfMissing() {
if (contentId == null) {
if (name != null) {
contentId(FileNameUtil.getName(name));
} else {
contentId(NO_NAME);
}
}
return this;
} | java | {
"resource": ""
} |
q171897 | EmailAttachmentBuilder.resolveContentType | test | protected String resolveContentType(final String contentType) {
if (contentType != null) {
return contentType;
}
if (name == null) {
return MimeTypes.MIME_APPLICATION_OCTET_STREAM;
}
final String extension = FileNameUtil.getExtension(name);
return MimeTypes.getMimeType(extension);
} | java | {
"resource": ""
} |
q171898 | SignatureReader.parseType | test | private static int parseType(
final String signature, final int startOffset, final SignatureVisitor signatureVisitor) {
int offset = startOffset; // Current offset in the parsed signature.
char currentChar = signature.charAt(offset++); // The signature character at 'offset'.
// Switch based on the first character of the JavaTypeSignature, which indicates its kind.
switch (currentChar) {
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
case 'F':
case 'J':
case 'D':
case 'V':
// Case of a BaseType or a VoidDescriptor.
signatureVisitor.visitBaseType(currentChar);
return offset;
case '[':
// Case of an ArrayTypeSignature, a '[' followed by a JavaTypeSignature.
return parseType(signature, offset, signatureVisitor.visitArrayType());
case 'T':
// Case of TypeVariableSignature, an identifier between 'T' and ';'.
int endOffset = signature.indexOf(';', offset);
signatureVisitor.visitTypeVariable(signature.substring(offset, endOffset));
return endOffset + 1;
case 'L':
// Case of a ClassTypeSignature, which ends with ';'.
// These signatures have a main class type followed by zero or more inner class types
// (separated by '.'). Each can have type arguments, inside '<' and '>'.
int start = offset; // The start offset of the currently parsed main or inner class name.
boolean visited = false; // Whether the currently parsed class name has been visited.
boolean inner = false; // Whether we are currently parsing an inner class type.
// Parses the signature, one character at a time.
while (true) {
currentChar = signature.charAt(offset++);
if (currentChar == '.' || currentChar == ';') {
// If a '.' or ';' is encountered, this means we have fully parsed the main class name
// or an inner class name. This name may already have been visited it is was followed by
// type arguments between '<' and '>'. If not, we need to visit it here.
if (!visited) {
String name = signature.substring(start, offset - 1);
if (inner) {
signatureVisitor.visitInnerClassType(name);
} else {
signatureVisitor.visitClassType(name);
}
}
// If we reached the end of the ClassTypeSignature return, otherwise start the parsing
// of a new class name, which is necessarily an inner class name.
if (currentChar == ';') {
signatureVisitor.visitEnd();
break;
}
start = offset;
visited = false;
inner = true;
} else if (currentChar == '<') {
// If a '<' is encountered, this means we have fully parsed the main class name or an
// inner class name, and that we now need to parse TypeArguments. First, we need to
// visit the parsed class name.
String name = signature.substring(start, offset - 1);
if (inner) {
signatureVisitor.visitInnerClassType(name);
} else {
signatureVisitor.visitClassType(name);
}
visited = true;
// Now, parse the TypeArgument(s), one at a time.
while ((currentChar = signature.charAt(offset)) != '>') {
switch (currentChar) {
case '*':
// Unbounded TypeArgument.
++offset;
signatureVisitor.visitTypeArgument();
break;
case '+':
case '-':
// Extends or Super TypeArgument. Use offset + 1 to skip the '+' or '-'.
offset =
parseType(
signature, offset + 1, signatureVisitor.visitTypeArgument(currentChar));
break;
default:
// Instanceof TypeArgument. The '=' is implicit.
offset = parseType(signature, offset, signatureVisitor.visitTypeArgument('='));
break;
}
}
}
}
return offset;
default:
throw new IllegalArgumentException();
}
} | java | {
"resource": ""
} |
q171899 | ModuleWriter.computeAttributesSize | test | int computeAttributesSize() {
symbolTable.addConstantUtf8(Constants.MODULE);
// 6 attribute header bytes, 6 bytes for name, flags and version, and 5 * 2 bytes for counts.
int size =
22 + requires.length + exports.length + opens.length + usesIndex.length + provides.length;
if (packageCount > 0) {
symbolTable.addConstantUtf8(Constants.MODULE_PACKAGES);
// 6 attribute header bytes, and 2 bytes for package_count.
size += 8 + packageIndex.length;
}
if (mainClassIndex > 0) {
symbolTable.addConstantUtf8(Constants.MODULE_MAIN_CLASS);
// 6 attribute header bytes, and 2 bytes for main_class_index.
size += 8;
}
return size;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.