_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q171400
UserSession.start
test
public void start(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) { final HttpSession httpSession = httpServletRequest.getSession(true); httpSession.setAttribute(AUTH_SESSION_NAME, this); final Cookie cookie = new Cookie(AUTH_COOKIE_NAME, authTokenValue); //cookie.setDomain(SSORealm.SSO_DOMAIN); cookie.setMaxAge(cookieMaxAge); cookie.setPath("/"); httpServletResponse.addCookie(cookie); }
java
{ "resource": "" }
q171401
TimeUtil.toDate
test
public static Date toDate(final LocalDate localDate) { return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); }
java
{ "resource": "" }
q171402
TimeUtil.toCalendar
test
public static Calendar toCalendar(final LocalDateTime localDateTime) { return GregorianCalendar.from(ZonedDateTime.of(localDateTime, ZoneId.systemDefault())); }
java
{ "resource": "" }
q171403
MethrefProxetta.defineProxy
test
public Class defineProxy(final Class target) { ProxyProxettaFactory builder = proxetta.proxy(); builder.setTarget(target); return builder.define(); }
java
{ "resource": "" }
q171404
ValidationContext.add
test
public void add(final Check check) { String name = check.getName(); List<Check> list = map.computeIfAbsent(name, k -> new ArrayList<>()); list.add(check); }
java
{ "resource": "" }
q171405
ValidationContext.resolveFor
test
public static ValidationContext resolveFor(final Class<?> target) { ValidationContext vc = new ValidationContext(); vc.addClassChecks(target); return vc; }
java
{ "resource": "" }
q171406
ValidationContext.addClassChecks
test
public void addClassChecks(final Class target) { final List<Check> list = cache.get(target, () -> { final List<Check> newList = new ArrayList<>(); final ClassDescriptor cd = ClassIntrospector.get().lookup(target); final PropertyDescriptor[] allProperties = cd.getAllPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : allProperties) { collectPropertyAnnotationChecks(newList, propertyDescriptor); } return newList; }); addAll(list); }
java
{ "resource": "" }
q171407
ValidationContext.collectPropertyAnnotationChecks
test
protected void collectPropertyAnnotationChecks(final List<Check> annChecks, final PropertyDescriptor propertyDescriptor) { FieldDescriptor fd = propertyDescriptor.getFieldDescriptor(); if (fd != null) { Annotation[] annotations = fd.getField().getAnnotations(); collectAnnotationChecks(annChecks, propertyDescriptor.getType(), propertyDescriptor.getName(), annotations); } MethodDescriptor md = propertyDescriptor.getReadMethodDescriptor(); if (md != null) { Annotation[] annotations = md.getMethod().getAnnotations(); collectAnnotationChecks(annChecks, propertyDescriptor.getType(), propertyDescriptor.getName(), annotations); } md = propertyDescriptor.getWriteMethodDescriptor(); if (md != null) { Annotation[] annotations = md.getMethod().getAnnotations(); collectAnnotationChecks(annChecks, propertyDescriptor.getType(), propertyDescriptor.getName(), annotations); } }
java
{ "resource": "" }
q171408
ValidationContext.collectAnnotationChecks
test
@SuppressWarnings({"unchecked"}) protected void collectAnnotationChecks(final List<Check> annChecks, final Class targetType, final String targetName, final Annotation[] annotations) { for (Annotation annotation : annotations) { Constraint c = annotation.annotationType().getAnnotation(Constraint.class); Class<? extends ValidationConstraint> constraintClass; if (c == null) { // if constraint is not available, try lookup String constraintClassName = annotation.annotationType().getName() + "Constraint"; try { constraintClass = ClassLoaderUtil.loadClass(constraintClassName, this.getClass().getClassLoader()); } catch (ClassNotFoundException ingore) { continue; } } else { constraintClass = c.value(); } ValidationConstraint vc; try { vc = newConstraint(constraintClass, targetType); } catch (Exception ex) { throw new VtorException("Invalid constraint: " + constraintClass.getClass().getName(), ex); } vc.configure(annotation); Check check = new Check(targetName, vc); copyDefaultCheckProperties(check, annotation); annChecks.add(check); } }
java
{ "resource": "" }
q171409
ValidationContext.copyDefaultCheckProperties
test
protected void copyDefaultCheckProperties(final Check destCheck, final Annotation annotation) { Integer severity = (Integer) ClassUtil.readAnnotationValue(annotation, ANN_SEVERITY); destCheck.setSeverity(severity.intValue()); String[] profiles = (String[]) ClassUtil.readAnnotationValue(annotation, ANN_PROFILES); destCheck.setProfiles(profiles); String message = (String) ClassUtil.readAnnotationValue(annotation, ANN_MESSAGE); destCheck.setMessage(message); }
java
{ "resource": "" }
q171410
URLCoder.encodeUriComponent
test
private static String encodeUriComponent(final String source, final String encoding, final URIPart uriPart) { if (source == null) { return null; } byte[] bytes = encodeBytes(StringUtil.getBytes(source, encoding), uriPart); char[] chars = new char[bytes.length]; for (int i = 0; i < bytes.length; i++) { chars[i] = (char) bytes[i]; } return new String(chars); }
java
{ "resource": "" }
q171411
URLCoder.encode
test
public static String encode(final String string, final String encoding) { return encodeUriComponent(string, encoding, URIPart.UNRESERVED); }
java
{ "resource": "" }
q171412
URLCoder.encodeScheme
test
public static String encodeScheme(final String scheme, final String encoding) { return encodeUriComponent(scheme, encoding, URIPart.SCHEME); }
java
{ "resource": "" }
q171413
URLCoder.encodeHost
test
public static String encodeHost(final String host, final String encoding) { return encodeUriComponent(host, encoding, URIPart.HOST); }
java
{ "resource": "" }
q171414
URLCoder.encodePort
test
public static String encodePort(final String port, final String encoding) { return encodeUriComponent(port, encoding, URIPart.PORT); }
java
{ "resource": "" }
q171415
URLCoder.encodePath
test
public static String encodePath(final String path, final String encoding) { return encodeUriComponent(path, encoding, URIPart.PATH); }
java
{ "resource": "" }
q171416
URLCoder.encodeQuery
test
public static String encodeQuery(final String query, final String encoding) { return encodeUriComponent(query, encoding, URIPart.QUERY); }
java
{ "resource": "" }
q171417
URLCoder.encodeQueryParam
test
public static String encodeQueryParam(final String queryParam, final String encoding) { return encodeUriComponent(queryParam, encoding, URIPart.QUERY_PARAM); }
java
{ "resource": "" }
q171418
URLCoder.encodeFragment
test
public static String encodeFragment(final String fragment, final String encoding) { return encodeUriComponent(fragment, encoding, URIPart.FRAGMENT); }
java
{ "resource": "" }
q171419
Properties.inspectProperties
test
protected HashMap<String, PropertyDescriptor> inspectProperties() { boolean scanAccessible = classDescriptor.isScanAccessible(); Class type = classDescriptor.getType(); HashMap<String, PropertyDescriptor> map = new HashMap<>(); Method[] methods = scanAccessible ? ClassUtil.getAccessibleMethods(type) : ClassUtil.getSupportedMethods(type); for (int iteration = 0; iteration < 2; iteration++) { // first find the getters, and then the setters! for (Method method : methods) { if (Modifier.isStatic(method.getModifiers())) { continue; // ignore static methods } boolean add = false; boolean issetter = false; String propertyName; if (iteration == 0) { propertyName = ClassUtil.getBeanPropertyGetterName(method); if (propertyName != null) { add = true; issetter = false; } } else { propertyName = ClassUtil.getBeanPropertySetterName(method); if (propertyName != null) { add = true; issetter = true; } } if (add) { MethodDescriptor methodDescriptor = classDescriptor.getMethodDescriptor(method.getName(), method.getParameterTypes(), true); addProperty(map, propertyName, methodDescriptor, issetter); } } } if (classDescriptor.isIncludeFieldsAsProperties()) { FieldDescriptor[] fieldDescriptors = classDescriptor.getAllFieldDescriptors(); String[] prefix = classDescriptor.getPropertyFieldPrefix(); for (FieldDescriptor fieldDescriptor : fieldDescriptors) { Field field = fieldDescriptor.getField(); if (Modifier.isStatic(field.getModifiers())) { continue; // ignore static fields } String name = field.getName(); if (prefix != null) { for (String p : prefix) { if (!name.startsWith(p)) { continue; } name = name.substring(p.length()); break; } } if (!map.containsKey(name)) { // add missing field as a potential property map.put(name, createPropertyDescriptor(name, fieldDescriptor)); } } } return map; }
java
{ "resource": "" }
q171420
Properties.getAllPropertyDescriptors
test
public PropertyDescriptor[] getAllPropertyDescriptors() { if (allProperties == null) { PropertyDescriptor[] allProperties = new PropertyDescriptor[propertyDescriptors.size()]; int index = 0; for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) { allProperties[index] = propertyDescriptor; index++; } Arrays.sort(allProperties, new Comparator<PropertyDescriptor>() { @Override public int compare(final PropertyDescriptor pd1, final PropertyDescriptor pd2) { return pd1.getName().compareTo(pd2.getName()); } }); this.allProperties = allProperties; } return allProperties; }
java
{ "resource": "" }
q171421
HttpResponse.cookies
test
public Cookie[] cookies() { List<String> newCookies = headers("set-cookie"); if (newCookies == null) { return new Cookie[0]; } List<Cookie> cookieList = new ArrayList<>(newCookies.size()); for (String cookieValue : newCookies) { try { Cookie cookie = new Cookie(cookieValue); cookieList.add(cookie); } catch (Exception ex) { // ignore } } return cookieList.toArray(new Cookie[0]); }
java
{ "resource": "" }
q171422
HttpResponse.unzip
test
public HttpResponse unzip() { String contentEncoding = contentEncoding(); if (contentEncoding != null && contentEncoding().equals("gzip")) { if (body != null) { headerRemove(HEADER_CONTENT_ENCODING); try { ByteArrayInputStream in = new ByteArrayInputStream(body.getBytes(StringPool.ISO_8859_1)); GZIPInputStream gzipInputStream = new GZIPInputStream(in); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamUtil.copy(gzipInputStream, out); body(out.toString(StringPool.ISO_8859_1)); } catch (IOException ioex) { throw new HttpException(ioex); } } } return this; }
java
{ "resource": "" }
q171423
HttpResponse.close
test
public HttpResponse close() { HttpConnection httpConnection = httpRequest.httpConnection; if (httpConnection != null) { httpConnection.close(); httpRequest.httpConnection = null; } return this; }
java
{ "resource": "" }
q171424
ThreadLocalScope.accept
test
@Override public boolean accept(final Scope referenceScope) { Class<? extends Scope> refScopeType = referenceScope.getClass(); if (refScopeType == ProtoScope.class) { return true; } if (refScopeType == SingletonScope.class) { return true; } if (refScopeType == ThreadLocalScope.class) { return true; } return false; }
java
{ "resource": "" }
q171425
JoyMadvoc.printRoutes
test
protected void printRoutes(final int width) { final ActionsManager actionsManager = webApp.madvocContainer().lookupComponent(ActionsManager.class); final List<ActionRuntime> actions = actionsManager.getAllActionRuntimes(); final Map<String, String> aliases = actionsManager.getAllAliases(); if (actions.isEmpty()) { return; } final Print print = new Print(); print.line("Routes", width); actions.stream() .sorted(Comparator.comparing( actionRuntime -> actionRuntime.getActionPath() + ' ' + actionRuntime.getActionMethod())) .forEach(ar -> { final String actionMethod = ar.getActionMethod(); print.out(Chalk256.chalk().yellow(), actionMethod == null ? "*" : actionMethod, 7); print.space(); final String signature = ClassUtil.getShortClassName( ProxettaUtil.resolveTargetClass(ar.getActionClass()), 2) + '#' + ar.getActionClassMethod().getName(); print.outLeftRightNewLine( Chalk256.chalk().green(), ar.getActionPath(), Chalk256.chalk().blue(), signature, width - 7 - 1 ); }); if (!aliases.isEmpty()) { print.line("Aliases", width); actions.stream() .sorted(Comparator.comparing( actionRuntime -> actionRuntime.getActionPath() + ' ' + actionRuntime.getActionMethod())) .forEach(ar -> { final String actionPath = ar.getActionPath(); for (final Map.Entry<String, String> entry : aliases.entrySet()) { if (entry.getValue().equals(actionPath)) { print.space(8); print.outLeftRightNewLine( Chalk256.chalk().green(), entry.getValue(), Chalk256.chalk().blue(), entry.getKey(), width - 8 ); } } }); } print.line(width); }
java
{ "resource": "" }
q171426
BlockCipher.encrypt
test
public byte[] encrypt(final byte[] content) { FastByteBuffer fbb = new FastByteBuffer(); int length = content.length + 1; int blockCount = length / blockSizeInBytes; int remaining = length; int offset = 0; for (int i = 0; i < blockCount; i++) { if (remaining == blockSizeInBytes) { break; } byte[] encrypted = encryptBlock(content, offset); fbb.append(encrypted); offset += blockSizeInBytes; remaining -= blockSizeInBytes; } if (remaining != 0) { // process remaining bytes byte[] block = new byte[blockSizeInBytes]; System.arraycopy(content, offset, block, 0, remaining - 1); block[remaining - 1] = TERMINATOR; byte[] encrypted = encryptBlock(block, 0); fbb.append(encrypted); } return fbb.toArray(); }
java
{ "resource": "" }
q171427
BlockCipher.decrypt
test
public byte[] decrypt(final byte[] encryptedContent) { FastByteBuffer fbb = new FastByteBuffer(); int length = encryptedContent.length; int blockCount = length / blockSizeInBytes; int offset = 0; for (int i = 0; i < blockCount - 1; i++) { byte[] decrypted = decryptBlock(encryptedContent, offset); fbb.append(decrypted); offset += blockSizeInBytes; } // process last block byte[] decrypted = decryptBlock(encryptedContent, offset); // find terminator int ndx = blockSizeInBytes - 1; while (ndx >= 0) { if (decrypted[ndx] == TERMINATOR) { break; } ndx--; } fbb.append(decrypted, 0, ndx); return fbb.toArray(); }
java
{ "resource": "" }
q171428
MapToBean.map2bean
test
public Object map2bean(final Map map, Class targetType) { Object target = null; // create targets type String className = (String) map.get(classMetadataName); if (className == null) { if (targetType == null) { // nothing to do, no information about target type found target = map; } } else { checkClassName(jsonParser.classnameWhitelist, className); try { targetType = ClassLoaderUtil.loadClass(className); } catch (ClassNotFoundException cnfex) { throw new JsonException(cnfex); } } if (target == null) { target = jsonParser.newObjectInstance(targetType); } ClassDescriptor cd = ClassIntrospector.get().lookup(target.getClass()); boolean targetIsMap = target instanceof Map; for (Object key : map.keySet()) { String keyName = key.toString(); if (classMetadataName != null) { if (keyName.equals(classMetadataName)) { continue; } } PropertyDescriptor pd = cd.getPropertyDescriptor(keyName, declared); if (!targetIsMap && pd == null) { // target property does not exist, continue continue; } // value is one of JSON basic types, like Number, Map, List... Object value = map.get(key); Class propertyType = pd == null ? null : pd.getType(); Class componentType = pd == null ? null : pd.resolveComponentType(true); if (value != null) { if (value instanceof List) { if (componentType != null && componentType != String.class) { value = generifyList((List) value, componentType); } } else if (value instanceof Map) { // if the value we want to inject is a Map... if (!ClassUtil.isTypeOf(propertyType, Map.class)) { // ... and if target is NOT a map value = map2bean((Map) value, propertyType); } else { // target is also a Map, but we might need to generify it Class keyType = pd == null ? null : pd.resolveKeyType(true); if (keyType != String.class || componentType != String.class) { // generify value = generifyMap((Map) value, keyType, componentType); } } } } if (targetIsMap) { ((Map)target).put(keyName, value); } else { try { setValue(target, pd, value); } catch (Exception ignore) { ignore.printStackTrace(); } } } return target; }
java
{ "resource": "" }
q171429
MapToBean.generifyList
test
private Object generifyList(final List list, final Class componentType) { for (int i = 0; i < list.size(); i++) { Object element = list.get(i); if (element != null) { if (element instanceof Map) { Object bean = map2bean((Map) element, componentType); list.set(i, bean); } else { Object value = convert(element, componentType); list.set(i, value); } } } return list; }
java
{ "resource": "" }
q171430
MapToBean.setValue
test
private void setValue(final Object target, final PropertyDescriptor pd, Object value) throws InvocationTargetException, IllegalAccessException { Class propertyType; Setter setter = pd.getSetter(true); if (setter != null) { if (value != null) { propertyType = setter.getSetterRawType(); value = jsonParser.convertType(value, propertyType); } setter.invokeSetter(target, value); } }
java
{ "resource": "" }
q171431
MapToBean.generifyMap
test
protected <K,V> Map<K, V> generifyMap(final Map<Object, Object> map, final Class<K> keyType, final Class<V> valueType) { if (keyType == String.class) { // only value type is changed, we can make value replacements for (Map.Entry<Object, Object> entry : map.entrySet()) { Object value = entry.getValue(); Object newValue = convert(value, valueType); if (value != newValue) { entry.setValue(newValue); } } return (Map<K, V>) map; } // key is changed too, we need a new map Map<K, V> newMap = new HashMap<>(map.size()); for (Map.Entry<Object, Object> entry : map.entrySet()) { Object key = entry.getKey(); Object newKey = convert(key, keyType); Object value = entry.getValue(); Object newValue = convert(value, valueType); newMap.put((K)newKey, (V)newValue); } return newMap; }
java
{ "resource": "" }
q171432
DbEntityColumnDescriptor.compareTo
test
@Override public int compareTo(final Object o) { DbEntityColumnDescriptor that = (DbEntityColumnDescriptor) o; if (this.isId != that.isId) { return this.isId ? -1 : 1; // IDs should be the first in the array } return this.columnName.compareTo(that.columnName); }
java
{ "resource": "" }
q171433
HttpBrowser.setDefaultHeader
test
public HttpBrowser setDefaultHeader(final String name, final String value) { defaultHeaders.addHeader(name, value); return this; }
java
{ "resource": "" }
q171434
HttpBrowser.sendRequest
test
public HttpResponse sendRequest(HttpRequest httpRequest) { elapsedTime = System.currentTimeMillis(); // send request httpRequest.followRedirects(false); while (true) { this.httpRequest = httpRequest; HttpResponse previousResponse = this.httpResponse; this.httpResponse = null; addDefaultHeaders(httpRequest); addCookies(httpRequest); // send request if (catchTransportExceptions) { try { this.httpResponse = _sendRequest(httpRequest, previousResponse); } catch (HttpException httpException) { httpResponse = new HttpResponse(); httpResponse.assignHttpRequest(httpRequest); httpResponse.statusCode(503); httpResponse.statusPhrase("Service unavailable. " + ExceptionUtil.message(httpException)); } } else { this.httpResponse =_sendRequest(httpRequest, previousResponse); } readCookies(httpResponse); int statusCode = httpResponse.statusCode(); // 301: moved permanently if (statusCode == 301) { String newPath = httpResponse.location(); if (newPath == null) { break; } httpRequest = HttpRequest.get(newPath); continue; } // 302: redirect, 303: see other if (statusCode == 302 || statusCode == 303) { String newPath = httpResponse.location(); if (newPath == null) { break; } httpRequest = HttpRequest.get(newPath); continue; } // 307: temporary redirect, 308: permanent redirect if (statusCode == 307 || statusCode == 308) { String newPath = httpResponse.location(); if (newPath == null) { break; } String originalMethod = httpRequest.method(); httpRequest = new HttpRequest() .method(originalMethod) .set(newPath); continue; } break; } elapsedTime = System.currentTimeMillis() - elapsedTime; return this.httpResponse; }
java
{ "resource": "" }
q171435
HttpBrowser._sendRequest
test
protected HttpResponse _sendRequest(final HttpRequest httpRequest, final HttpResponse previouseResponse) { if (!keepAlive) { httpRequest.open(httpConnectionProvider); } else { // keeping alive if (previouseResponse == null) { httpRequest.open(httpConnectionProvider).connectionKeepAlive(true); } else { httpRequest.keepAlive(previouseResponse, true); } } return httpRequest.send(); }
java
{ "resource": "" }
q171436
HttpBrowser.addDefaultHeaders
test
protected void addDefaultHeaders(final HttpRequest httpRequest) { for (Map.Entry<String, String> entry : defaultHeaders.entries()) { String name = entry.getKey(); if (!httpRequest.headers.contains(name)) { httpRequest.headers.add(name, entry.getValue()); } } }
java
{ "resource": "" }
q171437
HttpBrowser.readCookies
test
protected void readCookies(final HttpResponse httpResponse) { Cookie[] newCookies = httpResponse.cookies(); for (Cookie cookie : newCookies) { cookies.add(cookie.getName(), cookie); } }
java
{ "resource": "" }
q171438
HttpBrowser.addCookies
test
protected void addCookies(final HttpRequest httpRequest) { // prepare all cookies List<Cookie> cookiesList = new ArrayList<>(); if (!cookies.isEmpty()) { for (Map.Entry<String, Cookie> cookieEntry : cookies) { cookiesList.add(cookieEntry.getValue()); } httpRequest.cookies(cookiesList.toArray(new Cookie[0])); } }
java
{ "resource": "" }
q171439
SendMailSession.sendMail
test
public String sendMail(final Email email) { try { final MimeMessage msg = createMessage(email); getService().sendMessage(msg, msg.getAllRecipients()); return msg.getMessageID(); } catch (final MessagingException msgexc) { throw new MailException("Failed to send email: " + email, msgexc); } }
java
{ "resource": "" }
q171440
SendMailSession.setSubject
test
private void setSubject(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException { if (emailWithData.subjectEncoding() != null) { msgToSet.setSubject(emailWithData.subject(), emailWithData.subjectEncoding()); } else { msgToSet.setSubject(emailWithData.subject()); } }
java
{ "resource": "" }
q171441
SendMailSession.setSentDate
test
private void setSentDate(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException { Date date = emailWithData.sentDate(); if (date == null) { date = new Date(); } msgToSet.setSentDate(date); }
java
{ "resource": "" }
q171442
SendMailSession.setHeaders
test
private void setHeaders(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException { final Map<String, String> headers = emailWithData.headers(); if (headers != null) { for (final Map.Entry<String, String> entry : headers.entrySet()) { msgToSet.setHeader(entry.getKey(), entry.getValue()); } } }
java
{ "resource": "" }
q171443
SendMailSession.setPeople
test
private void setPeople(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException { msgToSet.setFrom(emailWithData.from().toInternetAddress()); msgToSet.setReplyTo(EmailAddress.convert(emailWithData.replyTo())); setRecipients(emailWithData, msgToSet); }
java
{ "resource": "" }
q171444
SendMailSession.setRecipients
test
private void setRecipients(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException { // TO final InternetAddress[] to = EmailAddress.convert(emailWithData.to()); if (to.length > 0) { msgToSet.setRecipients(RecipientType.TO, to); } // CC final InternetAddress[] cc = EmailAddress.convert(emailWithData.cc()); if (cc.length > 0) { msgToSet.setRecipients(RecipientType.CC, cc); } // BCC final InternetAddress[] bcc = EmailAddress.convert(emailWithData.bcc()); if (bcc.length > 0) { msgToSet.setRecipients(RecipientType.BCC, bcc); } }
java
{ "resource": "" }
q171445
SendMailSession.addBodyData
test
private void addBodyData(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException { final List<EmailMessage> messages = emailWithData.messages(); final int totalMessages = messages.size(); // Need to use new list since filterEmbeddedAttachments(List) removes attachments from the source List final List<EmailAttachment<? extends DataSource>> attachments = new ArrayList<>(emailWithData.attachments()); if (attachments.isEmpty() && totalMessages == 1) { // special case: no attachments and just one content setContent(messages.get(0), msgToSet); } else { final MimeMultipart multipart = new MimeMultipart(); final MimeMultipart msgMultipart = new MimeMultipart(ALTERNATIVE); multipart.addBodyPart(getBaseBodyPart(msgMultipart)); for (final EmailMessage emailMessage : messages) { msgMultipart.addBodyPart(getBodyPart(emailMessage, attachments)); } addAnyAttachments(attachments, multipart); msgToSet.setContent(multipart); } }
java
{ "resource": "" }
q171446
SendMailSession.setContent
test
private void setContent(final EmailMessage emailWithData, final Part partToSet) throws MessagingException { partToSet.setContent(emailWithData.getContent(), emailWithData.getMimeType() + CHARSET + emailWithData.getEncoding()); }
java
{ "resource": "" }
q171447
SendMailSession.createAttachmentBodyPart
test
protected MimeBodyPart createAttachmentBodyPart(final EmailAttachment<? extends DataSource> attachment) throws MessagingException { final MimeBodyPart part = new MimeBodyPart(); final String attachmentName = attachment.getEncodedName(); if (attachmentName != null) { part.setFileName(attachmentName); } part.setDataHandler(new DataHandler(attachment.getDataSource())); if (attachment.getContentId() != null) { part.setContentID(StringPool.LEFT_CHEV + attachment.getContentId() + StringPool.RIGHT_CHEV); } if (attachment.isInline()) { part.setDisposition(INLINE); } return part; }
java
{ "resource": "" }
q171448
FileUploadHeader.getContentType
test
private String getContentType(final String dataHeader) { String token = "Content-Type:"; int start = dataHeader.indexOf(token); if (start == -1) { return StringPool.EMPTY; } start += token.length(); return dataHeader.substring(start).trim(); }
java
{ "resource": "" }
q171449
DbQueryBase.saveResultSet
test
protected void saveResultSet(final ResultSet rs) { if (resultSets == null) { resultSets = new HashSet<>(); } resultSets.add(rs); }
java
{ "resource": "" }
q171450
DbQueryBase.closeAllResultSets
test
public Q closeAllResultSets() { final SQLException sex = closeQueryResultSets(); if (sex != null) { throw new DbSqlException("Close associated ResultSets error", sex); } return _this(); }
java
{ "resource": "" }
q171451
DbQueryBase.closeQuery
test
protected SQLException closeQuery() { SQLException sqlException = closeQueryResultSets(); if (statement != null) { try { statement.close(); } catch (SQLException sex) { if (sqlException == null) { sqlException = sex; } else { sqlException.setNextException(sex); } } statement = null; } query = null; queryState = CLOSED; return sqlException; }
java
{ "resource": "" }
q171452
DbQueryBase.close
test
@Override @SuppressWarnings({"ClassReferencesSubclass"}) public void close() { final SQLException sqlException = closeQuery(); connection = null; if (this.session != null) { this.session.detachQuery(this); } if (sqlException != null) { throw new DbSqlException("Close query error", sqlException); } }
java
{ "resource": "" }
q171453
DbQueryBase.setFetchSize
test
public Q setFetchSize(final int rows) { checkNotClosed(); this.fetchSize = rows; if (statement != null) { try { statement.setFetchSize(fetchSize); } catch (SQLException sex) { throw new DbSqlException(this, "Unable to set fetch size: " + fetchSize, sex); } } return _this(); }
java
{ "resource": "" }
q171454
DbQueryBase.setMaxRows
test
public Q setMaxRows(final int maxRows) { checkNotClosed(); this.maxRows = maxRows; if (statement != null) { try { statement.setMaxRows(maxRows); } catch (SQLException sex) { throw new DbSqlException(this, "Unable to set max rows: " + maxRows, sex); } } return _this(); }
java
{ "resource": "" }
q171455
DbQueryBase.executeUpdate
test
protected int executeUpdate(final boolean closeQuery) { start = System.currentTimeMillis(); init(); final int result; if (log.isDebugEnabled()) { log.debug("Executing update: " + getQueryString()); } try { if (preparedStatement == null) { if (generatedColumns != null) { if (generatedColumns.length == 0) { result = statement.executeUpdate(query.sql, Statement.RETURN_GENERATED_KEYS); } else { result = statement.executeUpdate(query.sql, generatedColumns); } } else { result = statement.executeUpdate(query.sql); } } else { result = preparedStatement.executeUpdate(); } } catch (SQLException sex) { throw new DbSqlException(this, "Query execution failed", sex); } if (closeQuery) { close(); } elapsed = System.currentTimeMillis() - start; if (log.isDebugEnabled()) { log.debug("execution time: " + elapsed + "ms"); } return result; }
java
{ "resource": "" }
q171456
DbQueryBase.executeCount
test
protected long executeCount(final boolean close) { start = System.currentTimeMillis(); init(); ResultSet rs = null; if (log.isDebugEnabled()) { log.debug("Executing prepared count: " + getQueryString()); } try { if (preparedStatement == null) { rs = statement.executeQuery(query.sql); } else { rs = preparedStatement.executeQuery(); } final long firstLong = DbUtil.getFirstLong(rs); elapsed = System.currentTimeMillis() - start; if (log.isDebugEnabled()) { log.debug("execution time: " + elapsed + "ms"); } return firstLong; } catch (SQLException sex) { throw new DbSqlException(this, "Count query failed", sex); } finally { DbUtil.close(rs); if (close) { close(); } } }
java
{ "resource": "" }
q171457
DbQueryBase.getGeneratedColumns
test
public ResultSet getGeneratedColumns() { checkInitialized(); if (generatedColumns == null) { throw new DbSqlException(this, "No column is specified as auto-generated"); } final ResultSet rs; try { rs = statement.getGeneratedKeys(); } catch (SQLException sex) { throw new DbSqlException(this, "No generated keys", sex); } saveResultSet(rs); totalOpenResultSetCount++; return rs; }
java
{ "resource": "" }
q171458
DbQueryBase.getQueryString
test
public String getQueryString() { if (debug) { if ((callableStatement != null)) { if (preparedStatement instanceof LoggableCallableStatement) { return ((LoggableCallableStatement) callableStatement).getQueryString(); } } if (preparedStatement != null) { if (preparedStatement instanceof LoggablePreparedStatement) { return ((LoggablePreparedStatement) preparedStatement).getQueryString(); } } } if (query != null) { return query.sql; } return sqlString; }
java
{ "resource": "" }
q171459
AopProxy.proxyOf
test
@SuppressWarnings("unchecked") public static <T> T proxyOf(final T target, final Class<? extends Aspect> aspectClass) { final Aspect aspect; try { aspect = ClassUtil.newInstance(aspectClass, target); } catch (Exception e) { throw new IllegalArgumentException("Can't create new instance of aspect class", e); } return (T) newProxyInstance(target.getClass().getClassLoader(), aspect, target.getClass().getInterfaces()); }
java
{ "resource": "" }
q171460
CollectionUtil.collectionOf
test
public static <T> Collection<T> collectionOf(final Iterator<? extends T> iterator) { final List<T> list = new ArrayList<>(); while (iterator.hasNext()) { list.add(iterator.next()); } return list; }
java
{ "resource": "" }
q171461
CollectionUtil.streamOf
test
public static <T> Stream<T> streamOf(final Iterator<T> iterator) { return StreamSupport.stream(((Iterable<T>) () -> iterator).spliterator(), false); }
java
{ "resource": "" }
q171462
MultiComparator.compare
test
@Override public int compare(final T o1, final T o2) { for (Comparator<T> comparator : comparators) { int result = comparator.compare(o1, o2); if (result != 0) { return result; } } return 0; }
java
{ "resource": "" }
q171463
PetiteConfig.setDefaultWiringMode
test
public PetiteConfig setDefaultWiringMode(final WiringMode defaultWiringMode) { if ((defaultWiringMode == null) || (defaultWiringMode == WiringMode.DEFAULT)) { throw new PetiteException("Invalid default wiring mode: " + defaultWiringMode); } this.defaultWiringMode = defaultWiringMode; return this; }
java
{ "resource": "" }
q171464
SimpleLogger.print
test
protected void print(final Level level, final String message, final Throwable throwable) { if (!isEnabled(level)) { return; } StringBuilder msg = new StringBuilder() .append(slf.getElapsedTime()).append(' ').append('[') .append(level).append(']').append(' ') .append(getCallerClass()).append(' ').append('-') .append(' ').append(message); System.out.println(msg.toString()); if (throwable != null) { throwable.printStackTrace(System.out); } }
java
{ "resource": "" }
q171465
SimpleLogger.getCallerClass
test
protected String getCallerClass() { Exception exception = new Exception(); StackTraceElement[] stackTrace = exception.getStackTrace(); for (StackTraceElement stackTraceElement : stackTrace) { String className = stackTraceElement.getClassName(); if (className.equals(SimpleLoggerProvider.class.getName())) { continue; } if (className.equals(SimpleLogger.class.getName())) { continue; } if (className.equals(Logger.class.getName())) { continue; } return shortenClassName(className) + '.' + stackTraceElement.getMethodName() + ':' + stackTraceElement.getLineNumber(); } return "N/A"; }
java
{ "resource": "" }
q171466
SimpleLogger.shortenClassName
test
protected String shortenClassName(final String className) { int lastDotIndex = className.lastIndexOf('.'); if (lastDotIndex == -1) { return className; } StringBuilder shortClassName = new StringBuilder(className.length()); int start = 0; while(true) { shortClassName.append(className.charAt(start)); int next = className.indexOf('.', start); if (next == lastDotIndex) { break; } start = next + 1; shortClassName.append('.'); } shortClassName.append(className.substring(lastDotIndex)); return shortClassName.toString(); }
java
{ "resource": "" }
q171467
JsonSerializer.excludeTypes
test
public JsonSerializer excludeTypes(final Class... types) { if (excludedTypes == null) { excludedTypes = types; } else { excludedTypes = ArraysUtil.join(excludedTypes, types); } return this; }
java
{ "resource": "" }
q171468
JsonSerializer.serialize
test
public void serialize(final Object source, final Appendable target) { JsonContext jsonContext = createJsonContext(target); jsonContext.serialize(source); }
java
{ "resource": "" }
q171469
JsonSerializer.serialize
test
public String serialize(final Object source) { FastCharBuffer fastCharBuffer = new FastCharBuffer(); serialize(source, fastCharBuffer); return fastCharBuffer.toString(); }
java
{ "resource": "" }
q171470
ObjectUtil.cloneViaSerialization
test
public static <T extends Serializable> T cloneViaSerialization(final T obj) throws IOException, ClassNotFoundException { FastByteArrayOutputStream bos = new FastByteArrayOutputStream(); ObjectOutputStream out = null; ObjectInputStream in = null; Object objCopy = null; try { out = new ObjectOutputStream(bos); out.writeObject(obj); out.flush(); byte[] bytes = bos.toByteArray(); in = new ObjectInputStream(new ByteArrayInputStream(bytes)); objCopy = in.readObject(); } finally { StreamUtil.close(out); StreamUtil.close(in); } return (T) objCopy; }
java
{ "resource": "" }
q171471
ObjectUtil.writeObject
test
public static void writeObject(final File dest, final Object object) throws IOException { FileOutputStream fos = null; BufferedOutputStream bos = null; ObjectOutputStream oos = null; try { fos = new FileOutputStream(dest); bos = new BufferedOutputStream(fos); oos = new ObjectOutputStream(bos); oos.writeObject(object); } finally { StreamUtil.close(oos); StreamUtil.close(bos); StreamUtil.close(fos); } }
java
{ "resource": "" }
q171472
ObjectUtil.readObject
test
public static Object readObject(final File source) throws IOException, ClassNotFoundException { Object result = null; FileInputStream fis = null; BufferedInputStream bis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(source); bis = new BufferedInputStream(fis); ois = new ObjectInputStream(bis); result = ois.readObject(); } finally { StreamUtil.close(ois); StreamUtil.close(bis); StreamUtil.close(fis); } return result; }
java
{ "resource": "" }
q171473
ObjectUtil.objectToByteArray
test
public static byte[] objectToByteArray(final Object obj) throws IOException { FastByteArrayOutputStream bos = new FastByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(bos); oos.writeObject(obj); } finally { StreamUtil.close(oos); } return bos.toByteArray(); }
java
{ "resource": "" }
q171474
ObjectUtil.byteArrayToObject
test
public static Object byteArrayToObject(final byte[] data) throws IOException, ClassNotFoundException { Object retObj = null; ByteArrayInputStream bais = new ByteArrayInputStream(data); ObjectInputStream ois = null; try { ois = new ObjectInputStream(bais); retObj = ois.readObject(); } finally { StreamUtil.close(ois); } return retObj; }
java
{ "resource": "" }
q171475
DefaultResultSetMapper.resolveMappedTypesTableNames
test
protected String[][] resolveMappedTypesTableNames(final Class[] types) { if (cachedMappedNames == null) { String[][] names = new String[types.length][]; for (int i = 0; i < types.length; i++) { Class type = types[i]; if (type != null) { DbEntityDescriptor ded = cachedDbEntityDescriptors[i]; if (ded != null) { Class[] mappedTypes = ded.getMappedTypes(); if (mappedTypes != null) { names[i] = createTypesTableNames(mappedTypes); } } } } cachedMappedNames = names; } return cachedMappedNames; }
java
{ "resource": "" }
q171476
DefaultResultSetMapper.createTypesTableNames
test
protected String[] createTypesTableNames(final Class[] types) { String[] names = new String[types.length]; for (int i = 0; i < types.length; i++) { if (types[i] == null) { names[i] = null; continue; } DbEntityDescriptor ded = dbEntityManager.lookupType(types[i]); if (ded != null) { String tableName = ded.getTableName(); tableName = tableName.toUpperCase(); names[i] = tableName; } } return names; }
java
{ "resource": "" }
q171477
DefaultResultSetMapper.readColumnValue
test
@SuppressWarnings({"unchecked"}) protected Object readColumnValue(final int colNdx, final Class destinationType, final Class<? extends SqlType> sqlTypeClass, final int columnDbSqlType) { if (colNdx != cachedColumnNdx) { try { SqlType sqlType; if (sqlTypeClass != null) { sqlType = SqlTypeManager.get().lookupSqlType(sqlTypeClass); } else { sqlType = SqlTypeManager.get().lookup(destinationType); } if (sqlType != null) { cachedColumnValue = sqlType.readValue(resultSet, colNdx + 1, destinationType, columnDbSqlType); } else { cachedColumnValue = resultSet.getObject(colNdx + 1); cachedColumnValue = TypeConverterManager.get().convertType(cachedColumnValue, destinationType); } } catch (SQLException sex) { throw new DbOomException(dbOomQuery, "Invalid value for column #" + (colNdx + 1), sex); } cachedColumnNdx = colNdx; } return cachedColumnValue; }
java
{ "resource": "" }
q171478
DefaultResultSetMapper.cacheResultSetEntities
test
protected void cacheResultSetEntities(final Object[] result) { if (entitiesCache == null) { entitiesCache = new HashMap<>(); } for (int i = 0; i < result.length; i++) { Object object = result[i]; if (object == null) { continue; } DbEntityDescriptor ded = cachedDbEntityDescriptors[i]; if (ded == null) { // not a type, continue continue; } // calculate key Object key; if (ded.hasIdColumn()) { //noinspection unchecked key = ded.getKeyValue(object); } else { key = object; } Object cachedObject = entitiesCache.get(key); if (cachedObject == null) { // object is not in the cache, add it entitiesCache.put(key, object); } else { // object is in the cache, replace it result[i] = cachedObject; } } }
java
{ "resource": "" }
q171479
ProviderResolver.resolve
test
public ProviderDefinition[] resolve(final Class type, final String name) { ClassDescriptor cd = ClassIntrospector.get().lookup(type); MethodDescriptor[] methods = cd.getAllMethodDescriptors(); List<ProviderDefinition> list = new ArrayList<>(); for (MethodDescriptor methodDescriptor : methods) { Method method = methodDescriptor.getMethod(); PetiteProvider petiteProvider = method.getAnnotation(PetiteProvider.class); if (petiteProvider == null) { continue; } String providerName = petiteProvider.value(); if (StringUtil.isBlank(providerName)) { // default provider name providerName = method.getName(); if (providerName.endsWith("Provider")) { providerName = StringUtil.substring(providerName, 0, -8); } } ProviderDefinition providerDefinition; if (Modifier.isStatic(method.getModifiers())) { providerDefinition = new ProviderDefinition(providerName, method); } else { providerDefinition = new ProviderDefinition(providerName, name, method); } list.add(providerDefinition); } ProviderDefinition[] providers; if (list.isEmpty()) { providers = ProviderDefinition.EMPTY; } else { providers = list.toArray(new ProviderDefinition[0]); } return providers; }
java
{ "resource": "" }
q171480
TableNamingStrategy.applyToTableName
test
public String applyToTableName(final String tableName) { String entityName = convertTableNameToEntityName(tableName); return convertEntityNameToTableName(entityName); }
java
{ "resource": "" }
q171481
CoreConnectionPool.isConnectionValid
test
private boolean isConnectionValid(final ConnectionData connectionData, final long now) { if (!validateConnection) { return true; } if (now < connectionData.lastUsed + validationTimeout) { return true; } Connection conn = connectionData.connection; if (validationQuery == null) { try { return !conn.isClosed(); } catch (SQLException sex) { return false; } } boolean valid = true; Statement st = null; try { st = conn.createStatement(); st.execute(validationQuery); } catch (SQLException sex) { valid = false; } finally { if (st != null) { try { st.close(); } catch (SQLException ignore) { } } } return valid; }
java
{ "resource": "" }
q171482
ServletDispatcherActionResult.renderView
test
@Override protected void renderView(final ActionRequest actionRequest, final String target) throws Exception { HttpServletRequest request = actionRequest.getHttpServletRequest(); HttpServletResponse response = actionRequest.getHttpServletResponse(); RequestDispatcher dispatcher = request.getRequestDispatcher(target); if (dispatcher == null) { response.sendError(SC_NOT_FOUND, "Result not found: " + target); // should never happened return; } // If we're included, then include the view, otherwise do forward. // This allow the page to, for example, set content type. if (DispatcherUtil.isPageIncluded(request, response)) { dispatcher.include(request, response); } else { dispatcher.forward(request, response); } }
java
{ "resource": "" }
q171483
ServletDispatcherActionResult.locateTarget
test
@Override protected String locateTarget(final ActionRequest actionRequest, String path) { String target; if (path.endsWith(StringPool.SLASH)) { path = path + defaultViewPageName; } for (final String ext : defaultViewExtensions) { target = path + ext; if (targetExists(actionRequest, target)) { return target; } } return null; }
java
{ "resource": "" }
q171484
BufferResponseWrapper.getWriter
test
@Override public PrintWriter getWriter() throws IOException { preResponseCommit(); if (buffer == null) { return getResponse().getWriter(); } return buffer.getWriter(); }
java
{ "resource": "" }
q171485
BufferResponseWrapper.getOutputStream
test
@Override public ServletOutputStream getOutputStream() throws IOException { preResponseCommit(); if (buffer == null) { return getResponse().getOutputStream(); } return buffer.getOutputStream(); }
java
{ "resource": "" }
q171486
BufferResponseWrapper.writeContentToResponse
test
public void writeContentToResponse(final char[] content) throws IOException { if (buffer == null) { return; } if (buffer.isUsingStream()) { ServletOutputStream outputStream = getResponse().getOutputStream(); String encoding = getContentTypeEncoding(); if (encoding == null) { outputStream.write(CharUtil.toByteArray(content)); } else { outputStream.write(CharUtil.toByteArray(content, encoding)); } outputStream.flush(); } else { Writer out = getResponse().getWriter(); out.write(content); out.flush(); } }
java
{ "resource": "" }
q171487
BufferResponseWrapper.setContentType
test
@Override public void setContentType(final String type) { super.setContentType(type); contentTypeResolver = new ContentTypeHeaderResolver(type); if (bufferContentType(type, contentTypeResolver.getMimeType(), contentTypeResolver.getEncoding())) { enableBuffering(); } else { disableBuffering(); } }
java
{ "resource": "" }
q171488
BufferResponseWrapper.print
test
public void print(final String string) throws IOException { if (isBufferStreamBased()) { String encoding = getContentTypeEncoding(); byte[] bytes; if (encoding == null) { bytes = string.getBytes(); } else { bytes = string.getBytes(encoding); } buffer.getOutputStream().write(bytes); return; } // make sure at least writer is initialized buffer.getWriter().write(string); }
java
{ "resource": "" }
q171489
AuthAction.login
test
protected JsonResult login() { T authToken; authToken = loginViaBasicAuth(servletRequest); if (authToken == null) { authToken = loginViaRequestParams(servletRequest); } if (authToken == null) { log.warn("Login failed."); return JsonResult.of(HttpStatus.error401().unauthorized("Login failed.")); } log.info("login OK!"); final UserSession<T> userSession = new UserSession<>(authToken, userAuth.tokenValue(authToken)); userSession.start(servletRequest, servletResponse); // return token return tokenAsJson(authToken); }
java
{ "resource": "" }
q171490
AuthAction.tokenAsJson
test
protected JsonResult tokenAsJson(final T authToken) { final JsonObject jsonObject = new JsonObject(); jsonObject.put("token", userAuth.tokenValue(authToken)); return JsonResult.of(jsonObject); }
java
{ "resource": "" }
q171491
AuthAction.loginViaBasicAuth
test
protected T loginViaBasicAuth(final HttpServletRequest servletRequest) { final String username = ServletUtil.resolveAuthUsername(servletRequest); if (username == null) { return null; } final String password = ServletUtil.resolveAuthPassword(servletRequest); return userAuth.login(username, password); }
java
{ "resource": "" }
q171492
AuthAction.logout
test
protected JsonResult logout() { log.debug("logout user"); UserSession.stop(servletRequest, servletResponse); return JsonResult.of(HttpStatus.ok()); }
java
{ "resource": "" }
q171493
FileUtil.toContainerFile
test
public static File toContainerFile(final URL url) { String protocol = url.getProtocol(); if (protocol.equals(FILE_PROTOCOL)) { return toFile(url); } String path = url.getPath(); return new File(URI.create( path.substring(ZERO, path.lastIndexOf("!/")))); }
java
{ "resource": "" }
q171494
FileUtil.mkdirs
test
public static File mkdirs(final File dirs) throws IOException { if (dirs.exists()) { checkIsDirectory(dirs); return dirs; } return checkCreateDirectory(dirs); }
java
{ "resource": "" }
q171495
FileUtil.mkdir
test
public static File mkdir(final File dir) throws IOException { if (dir.exists()) { checkIsDirectory(dir); return dir; } return checkCreateDirectory(dir); }
java
{ "resource": "" }
q171496
FileUtil._copyFile
test
private static void _copyFile(final File srcFile, final File destFile) throws IOException { if (destFile.exists()) { if (destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' is a directory"); } } // do copy file FileInputStream input = null; FileOutputStream output = null; try { input = new FileInputStream(srcFile); output = new FileOutputStream(destFile, false); StreamUtil.copy(input, output); } finally { StreamUtil.close(output); StreamUtil.close(input); } // done if (srcFile.length() != destFile.length()) { throw new IOException("Copy file failed of '" + srcFile + "' to '" + destFile + "' due to different sizes"); } destFile.setLastModified(srcFile.lastModified()); }
java
{ "resource": "" }
q171497
FileUtil.copyDir
test
public static void copyDir(final File srcDir, final File destDir) throws IOException { checkDirCopy(srcDir, destDir); _copyDirectory(srcDir, destDir); }
java
{ "resource": "" }
q171498
FileUtil.moveFileToDir
test
public static File moveFileToDir(final File srcFile, final File destDir) throws IOException { checkExistsAndDirectory(destDir); return moveFile(srcFile, file(destDir, srcFile.getName())); }
java
{ "resource": "" }
q171499
FileUtil._moveDirectory
test
private static void _moveDirectory(final File srcDest, File destDir) throws IOException { if (destDir.exists()) { checkIsDirectory(destDir); destDir = file(destDir, destDir.getName()); destDir.mkdir(); } final boolean rename = srcDest.renameTo(destDir); if (!rename) { _copyDirectory(srcDest, destDir); deleteDir(srcDest); } }
java
{ "resource": "" }