language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestGSet.java
{ "start": 12905, "end": 13352 }
class ____ { final IntElement[] integers; IntData(int size, int modulus) { integers = new IntElement[size]; for(int i = 0; i < integers.length; i++) { integers[i] = new IntElement(i, ran.nextInt(modulus)); } } IntElement get(int i) { return integers[i]; } int size() { return integers.length; } } /** Elements of {@link LightWeightGSet} in this test */ private static
IntData
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/MessageDeframer.java
{ "start": 17087, "end": 17456 }
class ____ implements StreamListener.MessageProducer { private InputStream message; private SingleMessageProducer(InputStream message) { this.message = message; } @Nullable @Override public InputStream next() { InputStream messageToReturn = message; message = null; return messageToReturn; } } }
SingleMessageProducer
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/fieldsel/FieldSelectionHelper.java
{ "start": 1083, "end": 2759 }
class ____ can be used to perform * field selections in a manner similar to unix cut. The input data is treated * as fields separated by a user specified separator (the default value is * "\t"). The user can specify a list of fields that form the map output keys, * and a list of fields that form the map output values. If the inputformat is * TextInputFormat, the mapper will ignore the key to the map function. and the * fields are from the value only. Otherwise, the fields are the union of those * from the key and those from the value. * * The field separator is under attribute "mapreduce.fieldsel.data.field.separator" * * The map output field list spec is under attribute * "mapreduce.fieldsel.map.output.key.value.fields.spec". * The value is expected to be like "keyFieldsSpec:valueFieldsSpec" * key/valueFieldsSpec are comma (,) separated field spec: fieldSpec,fieldSpec,fieldSpec ... * Each field spec can be a simple number (e.g. 5) specifying a specific field, or a range * (like 2-5) to specify a range of fields, or an open range (like 3-) specifying all * the fields starting from field 3. The open range field spec applies value fields only. * They have no effect on the key fields. * * Here is an example: "4,3,0,1:6,5,1-3,7-". It specifies to use fields 4,3,0 and 1 for keys, * and use fields 6,5,1,2,3,7 and above for values. * * The reduce output field list spec is under attribute * "mapreduce.fieldsel.reduce.output.key.value.fields.spec". * * The reducer extracts output key/value pairs in a similar manner, except that * the key is never ignored. * */ @InterfaceAudience.Public @InterfaceStability.Stable public
that
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java
{ "start": 13237, "end": 13510 }
class ____ extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } }
PendingSubtaskCheckpointStatistics
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/expressions/parser/ast/literal/NullLiteral.java
{ "start": 1220, "end": 1684 }
class ____ extends ExpressionNode { @Override public ExpressionDef generateExpression(ExpressionCompilationContext ctx) { return ExpressionDef.nullValue(); } @Override protected ClassElement doResolveClassElement(ExpressionVisitorContext ctx) { return ClassElement.of(Object.class); } @Override protected TypeDef doResolveType(@NonNull ExpressionVisitorContext ctx) { return TypeDef.OBJECT; } }
NullLiteral
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/http/impl/CookieJar.java
{ "start": 1002, "end": 4255 }
class ____ extends AbstractSet<ServerCookie> { // keep a shortcut to an empty jar to avoid unnecessary allocations private static final CookieJar EMPTY = new CookieJar(Collections.emptyList()); // the real holder private final List<ServerCookie> list; public CookieJar() { list = new ArrayList<>(4); } public CookieJar(CharSequence cookieHeader) { Objects.requireNonNull(cookieHeader, "cookie header cannot be null"); Set<io.netty.handler.codec.http.cookie.Cookie> nettyCookies = ServerCookieDecoder.STRICT.decode(cookieHeader.toString()); list = new ArrayList<>(nettyCookies.size()); for (io.netty.handler.codec.http.cookie.Cookie cookie : nettyCookies) { list.add(new CookieImpl(cookie)); } } private CookieJar(List<ServerCookie> list) { Objects.requireNonNull(list, "list cannot be null"); this.list = list; } /** * {@inheritDoc} */ @Override public int size() { return list.size(); } /** * {@inheritDoc} * * A Subtle difference here is that matching of cookies is done against the cookie unique identifier, not * the {@link #equals(Object)} method. */ @Override public boolean contains(Object o) { ServerCookie needle = (ServerCookie) o; for (ServerCookie cookie : list) { if (cookieUniqueIdComparator(cookie, needle.getName(), needle.getDomain(), needle.getPath()) == 0) { return true; } } return false; } @Override public Iterator<ServerCookie> iterator() { return list.iterator(); } /** * Adds a non {@code null} cookie to the cookie jar. Adding cookies is only allowed if the cookie jar is not a slice * view of the original cookie jar. In other words if this object was acquired from {@link #getAll(String)} or * {@link #removeOrInvalidateAll(String, boolean)} adding cookies will not be allowed. * * @throws UnsupportedOperationException if cookie jar is a slice view of the http exchange cookies * @throws NullPointerException if cookie is {@code null} * * @param cookie the cookie to add. * @return {@code true} if cookie was added or replaced. */ @Override public boolean add(ServerCookie cookie) { if (cookie == null) { throw new NullPointerException("cookie cannot be null"); } for (int i = 0; i < list.size(); i++) { int cmp = cookieUniqueIdComparator(list.get(i), cookie.getName(), cookie.getDomain(), cookie.getPath()); if (cmp > 0) { // insert list.add(i, cookie); return true; } if (cmp == 0) { // replace list.set(i, cookie); return true; } } // reached the end list.add(cookie); return true; } /** * Clears the cookie jar. Clearing the cookie jar is only allowed if the cookie jar is not a slice * view of the original cookie jar. In other words if this object was acquired from {@link #getAll(String)} or * {@link #removeOrInvalidateAll(String, boolean)} adding cookies will not be allowed. * * @throws UnsupportedOperationException if cookie jar is a slice view of the http exchange cookies */ @Override public void clear() { list.clear(); } /** * Follows the {@link Comparator}
CookieJar
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/Polygon.java
{ "start": 372, "end": 582 }
class ____ testing joined inheritance with a discriminator column. * * @author Etienne Miret */ @Entity @Inheritance( strategy = InheritanceType.JOINED ) @DiscriminatorColumn( name = "kind" ) public abstract
for
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/main/java/org/apache/hadoop/yarn/server/router/webapp/FederationInterceptorREST.java
{ "start": 67033, "end": 110436 }
interface ____ subCluster concurrently and get the returned result. Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); final HttpServletRequest hsrCopy = clone(hsr); Class[] argsClasses = new Class[]{HttpServletRequest.class, String.class, int.class}; Object[] args = new Object[]{hsrCopy, groupBy, activitiesCount}; ClientMethod remoteMethod = new ClientMethod("getBulkActivities", argsClasses, args); Map<SubClusterInfo, BulkActivitiesInfo> appStatisticsMap = invokeConcurrent( subClustersActive, remoteMethod, BulkActivitiesInfo.class); // Step3. Generate Federation objects and set subCluster information. long startTime = clock.getTime(); FederationBulkActivitiesInfo fedBulkActivitiesInfo = new FederationBulkActivitiesInfo(); appStatisticsMap.forEach((subClusterInfo, bulkActivitiesInfo) -> { SubClusterId subClusterId = subClusterInfo.getSubClusterId(); bulkActivitiesInfo.setSubClusterId(subClusterId.getId()); fedBulkActivitiesInfo.getList().add(bulkActivitiesInfo); }); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_BULKACTIVITIES, TARGET_WEB_SERVICE); long stopTime = clock.getTime(); routerMetrics.succeededGetBulkActivitiesRetrieved(stopTime - startTime); return fedBulkActivitiesInfo; } catch (IllegalArgumentException e) { routerMetrics.incrGetBulkActivitiesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_BULKACTIVITIES, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); throw e; } catch (NotFoundException e) { routerMetrics.incrGetBulkActivitiesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_BULKACTIVITIES, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException("get all active sub cluster(s) error.", e); } catch (IOException e) { routerMetrics.incrGetBulkActivitiesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_BULKACTIVITIES, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "getBulkActivities by groupBy = %s, activitiesCount = %s with io error.", groupBy, String.valueOf(activitiesCount)); } catch (YarnException e) { routerMetrics.incrGetBulkActivitiesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_BULKACTIVITIES, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "getBulkActivities by groupBy = %s, activitiesCount = %s with yarn error.", groupBy, String.valueOf(activitiesCount)); } routerMetrics.incrGetBulkActivitiesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_BULKACTIVITIES, UNKNOWN, TARGET_WEB_SERVICE, "getBulkActivities Failed."); throw new RuntimeException("getBulkActivities Failed."); } @Override public AppActivitiesInfo getAppActivities(HttpServletRequest hsr, String appId, String time, Set<String> requestPriorities, Set<String> allocationRequestIds, String groupBy, String limit, Set<String> actions, boolean summarize) { try { long startTime = clock.getTime(); DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId); final HttpServletRequest hsrCopy = clone(hsr); AppActivitiesInfo appActivitiesInfo = interceptor.getAppActivities(hsrCopy, appId, time, requestPriorities, allocationRequestIds, groupBy, limit, actions, summarize); if (appActivitiesInfo != null) { long stopTime = clock.getTime(); routerMetrics.succeededGetAppActivitiesRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_APPACTIVITIES, TARGET_WEB_SERVICE); return appActivitiesInfo; } } catch (IllegalArgumentException e) { routerMetrics.incrGetAppActivitiesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APPACTIVITIES, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "Unable to get subCluster by appId: %s.", appId); } catch (YarnException e) { routerMetrics.incrGetAppActivitiesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APPACTIVITIES, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "getAppActivities by appId = %s error .", appId); } RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APPACTIVITIES, UNKNOWN, TARGET_WEB_SERVICE, "getAppActivities Failed."); routerMetrics.incrGetAppActivitiesFailedRetrieved(); throw new RuntimeException("getAppActivities Failed."); } @Override public ApplicationStatisticsInfo getAppStatistics(HttpServletRequest hsr, Set<String> stateQueries, Set<String> typeQueries) { try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); final HttpServletRequest hsrCopy = clone(hsr); Class[] argsClasses = new Class[]{HttpServletRequest.class, Set.class, Set.class}; Object[] args = new Object[]{hsrCopy, stateQueries, typeQueries}; ClientMethod remoteMethod = new ClientMethod("getAppStatistics", argsClasses, args); Map<SubClusterInfo, ApplicationStatisticsInfo> appStatisticsMap = invokeConcurrent( subClustersActive, remoteMethod, ApplicationStatisticsInfo.class); ApplicationStatisticsInfo applicationStatisticsInfo = RouterWebServiceUtil.mergeApplicationStatisticsInfo(appStatisticsMap.values()); if (applicationStatisticsInfo != null) { long stopTime = clock.getTime(); routerMetrics.succeededGetAppStatisticsRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_APPSTATISTICS, TARGET_WEB_SERVICE); return applicationStatisticsInfo; } } catch (NotFoundException e) { routerMetrics.incrGetAppStatisticsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APPSTATISTICS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException("get all active sub cluster(s) error.", e); } catch (IOException e) { routerMetrics.incrGetAppStatisticsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APPSTATISTICS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "getAppStatistics error by stateQueries = %s, typeQueries = %s with io error.", StringUtils.join(stateQueries, ","), StringUtils.join(typeQueries, ",")); } catch (YarnException e) { routerMetrics.incrGetAppStatisticsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APPSTATISTICS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "getAppStatistics by stateQueries = %s, typeQueries = %s with yarn error.", StringUtils.join(stateQueries, ","), StringUtils.join(typeQueries, ",")); } routerMetrics.incrGetAppStatisticsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APPSTATISTICS, UNKNOWN, TARGET_WEB_SERVICE, "getAppStatistics Failed."); throw RouterServerUtil.logAndReturnRunTimeException( "getAppStatistics by stateQueries = %s, typeQueries = %s Failed.", StringUtils.join(stateQueries, ","), StringUtils.join(typeQueries, ",")); } @Override public NodeToLabelsInfo getNodeToLabels(HttpServletRequest hsr) throws IOException { try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); final HttpServletRequest hsrCopy = clone(hsr); Class[] argsClasses = new Class[]{HttpServletRequest.class}; Object[] args = new Object[]{hsrCopy}; ClientMethod remoteMethod = new ClientMethod("getNodeToLabels", argsClasses, args); Map<SubClusterInfo, NodeToLabelsInfo> nodeToLabelsInfoMap = invokeConcurrent(subClustersActive, remoteMethod, NodeToLabelsInfo.class); NodeToLabelsInfo nodeToLabelsInfo = RouterWebServiceUtil.mergeNodeToLabels(nodeToLabelsInfoMap); if (nodeToLabelsInfo != null) { long stopTime = clock.getTime(); routerMetrics.succeededGetNodeToLabelsRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_NODETOLABELS, TARGET_WEB_SERVICE); return nodeToLabelsInfo; } } catch (NotFoundException e) { routerMetrics.incrNodeToLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_NODETOLABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("get all active sub cluster(s) error.", e); } catch (YarnException e) { routerMetrics.incrNodeToLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_NODETOLABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("getNodeToLabels error.", e); } routerMetrics.incrNodeToLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_NODETOLABELS, UNKNOWN, TARGET_WEB_SERVICE, "getNodeToLabels Failed."); throw new RuntimeException("getNodeToLabels Failed."); } @Override public NodeLabelsInfo getRMNodeLabels(HttpServletRequest hsr) throws IOException { try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); final HttpServletRequest hsrCopy = clone(hsr); Class[] argsClasses = new Class[]{HttpServletRequest.class}; Object[] args = new Object[]{hsrCopy}; ClientMethod remoteMethod = new ClientMethod("getRMNodeLabels", argsClasses, args); Map<SubClusterInfo, NodeLabelsInfo> nodeToLabelsInfoMap = invokeConcurrent(subClustersActive, remoteMethod, NodeLabelsInfo.class); NodeLabelsInfo nodeToLabelsInfo = RouterWebServiceUtil.mergeNodeLabelsInfo(nodeToLabelsInfoMap); if (nodeToLabelsInfo != null) { long stopTime = clock.getTime(); routerMetrics.succeededGetRMNodeLabelsRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_RMNODELABELS, TARGET_WEB_SERVICE); return nodeToLabelsInfo; } } catch (NotFoundException e) { routerMetrics.incrGetRMNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_RMNODELABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("get all active sub cluster(s) error.", e); } catch (YarnException e) { routerMetrics.incrGetRMNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_RMNODELABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("getRMNodeLabels error.", e); } routerMetrics.incrGetRMNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_RMNODELABELS, UNKNOWN, TARGET_WEB_SERVICE, "getRMNodeLabels Failed."); throw new RuntimeException("getRMNodeLabels Failed."); } @Override public LabelsToNodesInfo getLabelsToNodes(Set<String> labels) throws IOException { try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); Class[] argsClasses = new Class[]{Set.class}; Object[] args = new Object[]{labels}; ClientMethod remoteMethod = new ClientMethod("getLabelsToNodes", argsClasses, args); Map<SubClusterInfo, LabelsToNodesInfo> labelsToNodesInfoMap = invokeConcurrent(subClustersActive, remoteMethod, LabelsToNodesInfo.class); Map<NodeLabelInfo, NodeIDsInfo> labelToNodesMap = new HashMap<>(); labelsToNodesInfoMap.values().forEach(labelsToNode -> { Map<NodeLabelInfo, NodeIDsInfo> values = labelsToNode.getLabelsToNodes(); for (Map.Entry<NodeLabelInfo, NodeIDsInfo> item : values.entrySet()) { NodeLabelInfo key = item.getKey(); NodeIDsInfo leftValue = item.getValue(); NodeIDsInfo rightValue = labelToNodesMap.getOrDefault(key, null); NodeIDsInfo newValue = NodeIDsInfo.add(leftValue, rightValue); labelToNodesMap.put(key, newValue); } }); LabelsToNodesInfo labelsToNodesInfo = new LabelsToNodesInfo(labelToNodesMap); if (labelsToNodesInfo != null) { long stopTime = clock.getTime(); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_LABELSTONODES, TARGET_WEB_SERVICE); routerMetrics.succeededGetLabelsToNodesRetrieved(stopTime - startTime); return labelsToNodesInfo; } } catch (NotFoundException e) { routerMetrics.incrLabelsToNodesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_LABELSTONODES, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("get all active sub cluster(s) error.", e); } catch (YarnException e) { routerMetrics.incrLabelsToNodesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_LABELSTONODES, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException( e, "getLabelsToNodes by labels = %s with yarn error.", StringUtils.join(labels, ",")); } routerMetrics.incrLabelsToNodesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_LABELSTONODES, UNKNOWN, TARGET_WEB_SERVICE, "getLabelsToNodes Failed."); throw RouterServerUtil.logAndReturnRunTimeException( "getLabelsToNodes by labels = %s Failed.", StringUtils.join(labels, ",")); } /** * This method replaces all the node labels for specific nodes, and it is * reachable by using {@link RMWSConsts#REPLACE_NODE_TO_LABELS}. * * @see ResourceManagerAdministrationProtocol#replaceLabelsOnNode * @param newNodeToLabels the list of new labels. It is a content param. * @param hsr the servlet request * @return Response containing the status code * @throws IOException if an exception happened */ @Override public Response replaceLabelsOnNodes(NodeToLabelsEntryList newNodeToLabels, HttpServletRequest hsr) throws IOException { // Step1. Check the parameters to ensure that the parameters are not empty. if (newNodeToLabels == null) { routerMetrics.incrReplaceLabelsOnNodesFailedRetrieved(); throw new IllegalArgumentException("Parameter error, newNodeToLabels must not be empty."); } List<NodeToLabelsEntry> nodeToLabelsEntries = newNodeToLabels.getNodeToLabels(); if (CollectionUtils.isEmpty(nodeToLabelsEntries)) { routerMetrics.incrReplaceLabelsOnNodesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), REPLACE_LABELSONNODES, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, " + "nodeToLabelsEntries must not be empty."); throw new IllegalArgumentException("Parameter error, " + "nodeToLabelsEntries must not be empty."); } try { // Step2. We map the NodeId and NodeToLabelsEntry in the request. Map<String, NodeToLabelsEntry> nodeIdToLabels = new HashMap<>(); newNodeToLabels.getNodeToLabels().forEach(nodeIdToLabel -> { String nodeId = nodeIdToLabel.getNodeId(); nodeIdToLabels.put(nodeId, nodeIdToLabel); }); // Step3. We map SubCluster with NodeToLabelsEntryList Map<SubClusterInfo, NodeToLabelsEntryList> subClusterToNodeToLabelsEntryList = new HashMap<>(); nodeIdToLabels.forEach((nodeId, nodeToLabelsEntry) -> { SubClusterInfo subClusterInfo = getNodeSubcluster(nodeId); NodeToLabelsEntryList nodeToLabelsEntryList = subClusterToNodeToLabelsEntryList. getOrDefault(subClusterInfo, new NodeToLabelsEntryList()); nodeToLabelsEntryList.getNodeToLabels().add(nodeToLabelsEntry); subClusterToNodeToLabelsEntryList.put(subClusterInfo, nodeToLabelsEntryList); }); // Step4. Traverse the subCluster and call the replaceLabelsOnNodes interface. long startTime = clock.getTime(); final HttpServletRequest hsrCopy = clone(hsr); StringBuilder builder = new StringBuilder(); subClusterToNodeToLabelsEntryList.forEach((subClusterInfo, nodeToLabelsEntryList) -> { SubClusterId subClusterId = subClusterInfo.getSubClusterId(); try { DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorForSubCluster( subClusterInfo); interceptor.replaceLabelsOnNodes(nodeToLabelsEntryList, hsrCopy); builder.append("subCluster-").append(subClusterId.getId()).append(":Success,"); } catch (Exception e) { LOG.error("replaceLabelsOnNodes Failed. subClusterId = {}.", subClusterId, e); builder.append("subCluster-").append(subClusterId.getId()).append(":Failed,"); } }); long stopTime = clock.getTime(); RouterAuditLogger.logSuccess(getUser().getShortUserName(), REPLACE_LABELSONNODES, TARGET_WEB_SERVICE); routerMetrics.succeededReplaceLabelsOnNodesRetrieved(stopTime - startTime); // Step5. return call result. return Response.status(Status.OK).entity(builder.toString()).build(); } catch (Exception e) { routerMetrics.incrReplaceLabelsOnNodesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), REPLACE_LABELSONNODES, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); throw e; } } /** * This method replaces all the node labels for specific node, and it is * reachable by using {@link RMWSConsts#NODES_NODEID_REPLACE_LABELS}. * * @see ResourceManagerAdministrationProtocol#replaceLabelsOnNode * @param newNodeLabelsName the list of new labels. It is a QueryParam. * @param hsr the servlet request * @param nodeId the node we want to replace the node labels. It is a * PathParam. * @return Response containing the status code * @throws Exception if an exception happened */ @Override public Response replaceLabelsOnNode(Set<String> newNodeLabelsName, HttpServletRequest hsr, String nodeId) throws Exception { // Step1. Check the parameters to ensure that the parameters are not empty. if (StringUtils.isBlank(nodeId)) { routerMetrics.incrReplaceLabelsOnNodeFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), REPLACE_LABELSONNODE, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, nodeId must not be null or empty."); throw new IllegalArgumentException("Parameter error, nodeId must not be null or empty."); } if (CollectionUtils.isEmpty(newNodeLabelsName)) { routerMetrics.incrReplaceLabelsOnNodeFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), REPLACE_LABELSONNODE, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, newNodeLabelsName must not be empty."); throw new IllegalArgumentException("Parameter error, newNodeLabelsName must not be empty."); } try { // Step2. We find the subCluster according to the nodeId, // and then call the replaceLabelsOnNode of the subCluster. long startTime = clock.getTime(); SubClusterInfo subClusterInfo = getNodeSubcluster(nodeId); DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByNodeId(nodeId); final HttpServletRequest hsrCopy = clone(hsr); interceptor.replaceLabelsOnNode(newNodeLabelsName, hsrCopy, nodeId); // Step3. Return the response result. long stopTime = clock.getTime(); RouterAuditLogger.logSuccess(getUser().getShortUserName(), REPLACE_LABELSONNODE, TARGET_WEB_SERVICE); routerMetrics.succeededReplaceLabelsOnNodeRetrieved(stopTime - startTime); String msg = "subCluster#" + subClusterInfo.getSubClusterId().getId() + ":Success;"; return Response.status(Status.OK).entity(msg).build(); } catch (Exception e) { routerMetrics.incrReplaceLabelsOnNodeFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), REPLACE_LABELSONNODE, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); throw e; } } @Override public NodeLabelsInfo getClusterNodeLabels(HttpServletRequest hsr) throws IOException { try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); final HttpServletRequest hsrCopy = clone(hsr); Class[] argsClasses = new Class[]{HttpServletRequest.class}; Object[] args = new Object[]{hsrCopy}; ClientMethod remoteMethod = new ClientMethod("getClusterNodeLabels", argsClasses, args); Map<SubClusterInfo, NodeLabelsInfo> nodeToLabelsInfoMap = invokeConcurrent(subClustersActive, remoteMethod, NodeLabelsInfo.class); Set<NodeLabel> hashSets = Sets.newHashSet(); nodeToLabelsInfoMap.values().forEach(item -> hashSets.addAll(item.getNodeLabels())); NodeLabelsInfo nodeLabelsInfo = new NodeLabelsInfo(hashSets); if (nodeLabelsInfo != null) { long stopTime = clock.getTime(); routerMetrics.succeededGetClusterNodeLabelsRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_CLUSTER_NODELABELS, TARGET_WEB_SERVICE); return nodeLabelsInfo; } } catch (NotFoundException e) { routerMetrics.incrClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_CLUSTER_NODELABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("get all active sub cluster(s) error.", e); } catch (YarnException e) { routerMetrics.incrClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_CLUSTER_NODELABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("getClusterNodeLabels with yarn error.", e); } routerMetrics.incrClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_CLUSTER_NODELABELS, UNKNOWN, TARGET_WEB_SERVICE, "getClusterNodeLabels Failed."); throw new RuntimeException("getClusterNodeLabels Failed."); } /** * This method adds specific node labels for specific nodes, and it is * reachable by using {@link RMWSConsts#ADD_NODE_LABELS}. * * @see ResourceManagerAdministrationProtocol#addToClusterNodeLabels * @param newNodeLabels the node labels to add. It is a content param. * @param hsr the servlet request * @return Response containing the status code * @throws Exception in case of bad request */ @Override public Response addToClusterNodeLabels(NodeLabelsInfo newNodeLabels, HttpServletRequest hsr) throws Exception { if (newNodeLabels == null) { routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), ADD_TO_CLUSTER_NODELABELS, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, the newNodeLabels is null."); throw new IllegalArgumentException("Parameter error, the newNodeLabels is null."); } List<NodeLabelInfo> nodeLabelInfos = newNodeLabels.getNodeLabelsInfo(); if (CollectionUtils.isEmpty(nodeLabelInfos)) { routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), ADD_TO_CLUSTER_NODELABELS, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, the nodeLabelsInfo is null or empty."); throw new IllegalArgumentException("Parameter error, the nodeLabelsInfo is null or empty."); } try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActives = federationFacade.getActiveSubClusters(); final HttpServletRequest hsrCopy = clone(hsr); Class[] argsClasses = new Class[]{NodeLabelsInfo.class, HttpServletRequest.class}; Object[] args = new Object[]{newNodeLabels, hsrCopy}; ClientMethod remoteMethod = new ClientMethod("addToClusterNodeLabels", argsClasses, args); Map<SubClusterInfo, Response> responseInfoMap = invokeConcurrent(subClustersActives, remoteMethod, Response.class); StringBuilder buffer = new StringBuilder(); // SubCluster-0:SUCCESS,SubCluster-1:SUCCESS responseInfoMap.forEach((subClusterInfo, response) -> buildAppendMsg(subClusterInfo, buffer, response)); long stopTime = clock.getTime(); RouterAuditLogger.logSuccess(getUser().getShortUserName(), ADD_TO_CLUSTER_NODELABELS, TARGET_WEB_SERVICE); routerMetrics.succeededAddToClusterNodeLabelsRetrieved((stopTime - startTime)); return Response.status(Status.OK).entity(buffer.toString()).build(); } catch (NotFoundException e) { routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), ADD_TO_CLUSTER_NODELABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("get all active sub cluster(s) error.", e); } catch (YarnException e) { routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), ADD_TO_CLUSTER_NODELABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("addToClusterNodeLabels with yarn error.", e); } routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), ADD_TO_CLUSTER_NODELABELS, UNKNOWN, TARGET_WEB_SERVICE, "addToClusterNodeLabels Failed."); throw new RuntimeException("addToClusterNodeLabels Failed."); } /** * This method removes all the node labels for specific nodes, and it is * reachable by using {@link RMWSConsts#REMOVE_NODE_LABELS}. * * @see ResourceManagerAdministrationProtocol#removeFromClusterNodeLabels * @param oldNodeLabels the node labels to remove. It is a QueryParam. * @param hsr the servlet request * @return Response containing the status code * @throws Exception in case of bad request */ @Override public Response removeFromClusterNodeLabels(Set<String> oldNodeLabels, HttpServletRequest hsr) throws Exception { if (CollectionUtils.isEmpty(oldNodeLabels)) { routerMetrics.incrRemoveFromClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), REMOVE_FROM_CLUSTERNODELABELS, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, the oldNodeLabels is null or empty."); throw new IllegalArgumentException("Parameter error, the oldNodeLabels is null or empty."); } try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActives = federationFacade.getActiveSubClusters(); final HttpServletRequest hsrCopy = clone(hsr); Class[] argsClasses = new Class[]{Set.class, HttpServletRequest.class}; Object[] args = new Object[]{oldNodeLabels, hsrCopy}; ClientMethod remoteMethod = new ClientMethod("removeFromClusterNodeLabels", argsClasses, args); Map<SubClusterInfo, Response> responseInfoMap = invokeConcurrent(subClustersActives, remoteMethod, Response.class); StringBuilder buffer = new StringBuilder(); // SubCluster-0:SUCCESS,SubCluster-1:SUCCESS responseInfoMap.forEach((subClusterInfo, response) -> buildAppendMsg(subClusterInfo, buffer, response)); long stopTime = clock.getTime(); RouterAuditLogger.logSuccess(getUser().getShortUserName(), REMOVE_FROM_CLUSTERNODELABELS, TARGET_WEB_SERVICE); routerMetrics.succeededRemoveFromClusterNodeLabelsRetrieved(stopTime - startTime); return Response.status(Status.OK).entity(buffer.toString()).build(); } catch (NotFoundException e) { routerMetrics.incrRemoveFromClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), REMOVE_FROM_CLUSTERNODELABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("get all active sub cluster(s) error.", e); } catch (YarnException e) { routerMetrics.incrRemoveFromClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), REMOVE_FROM_CLUSTERNODELABELS, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("removeFromClusterNodeLabels with yarn error.", e); } routerMetrics.incrRemoveFromClusterNodeLabelsFailedRetrieved(); throw new RuntimeException("removeFromClusterNodeLabels Failed."); } /** * Build Append information. * * @param subClusterInfo subCluster information. * @param buffer StringBuilder. * @param response response message. */ private void buildAppendMsg(SubClusterInfo subClusterInfo, StringBuilder buffer, Response response) { SubClusterId subClusterId = subClusterInfo.getSubClusterId(); String state = response != null && (response.getStatus() == Status.OK.getStatusCode()) ? "SUCCESS" : "FAILED"; buffer.append("SubCluster-") .append(subClusterId.getId()) .append(":") .append(state) .append(","); } @Override public NodeLabelsInfo getLabelsOnNode(HttpServletRequest hsr, String nodeId) throws IOException { try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); final HttpServletRequest hsrCopy = clone(hsr); Class[] argsClasses = new Class[]{HttpServletRequest.class, String.class}; Object[] args = new Object[]{hsrCopy, nodeId}; ClientMethod remoteMethod = new ClientMethod("getLabelsOnNode", argsClasses, args); Map<SubClusterInfo, NodeLabelsInfo> nodeToLabelsInfoMap = invokeConcurrent(subClustersActive, remoteMethod, NodeLabelsInfo.class); Set<NodeLabel> hashSets = Sets.newHashSet(); nodeToLabelsInfoMap.values().forEach(item -> hashSets.addAll(item.getNodeLabels())); NodeLabelsInfo nodeLabelsInfo = new NodeLabelsInfo(hashSets); if (nodeLabelsInfo != null) { long stopTime = clock.getTime(); routerMetrics.succeededGetLabelsToNodesRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_LABELS_ON_NODE, TARGET_WEB_SERVICE); return nodeLabelsInfo; } } catch (NotFoundException e) { routerMetrics.incrLabelsToNodesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_LABELS_ON_NODE, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException("get all active sub cluster(s) error.", e); } catch (YarnException e) { routerMetrics.incrLabelsToNodesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_LABELS_ON_NODE, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowIOException( e, "getLabelsOnNode nodeId = %s with yarn error.", nodeId); } routerMetrics.incrLabelsToNodesFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_LABELS_ON_NODE, UNKNOWN, TARGET_WEB_SERVICE, "getLabelsOnNode by nodeId = " + nodeId + " Failed."); throw RouterServerUtil.logAndReturnRunTimeException( "getLabelsOnNode by nodeId = %s Failed.", nodeId); } @Override public AppPriority getAppPriority(HttpServletRequest hsr, String appId) throws AuthorizationException { try { long startTime = clock.getTime(); DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId); AppPriority appPriority = interceptor.getAppPriority(hsr, appId); if (appPriority != null) { long stopTime = clock.getTime(); routerMetrics.succeededGetAppPriorityRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_APP_PRIORITY, TARGET_WEB_SERVICE); return appPriority; } } catch (IllegalArgumentException e) { routerMetrics.incrGetAppPriorityFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APP_PRIORITY, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "Unable to get the getAppPriority appId: %s.", appId); } catch (YarnException e) { routerMetrics.incrGetAppPriorityFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APP_PRIORITY, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException("getAppPriority error.", e); } routerMetrics.incrGetAppPriorityFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APP_PRIORITY, UNKNOWN, TARGET_WEB_SERVICE, "getAppPriority Failed."); throw new RuntimeException("getAppPriority Failed."); } @Override public Response updateApplicationPriority(AppPriority targetPriority, HttpServletRequest hsr, String appId) throws AuthorizationException, YarnException, InterruptedException, IOException { if (targetPriority == null) { routerMetrics.incrUpdateAppPriorityFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APPLICATIONPRIORITY, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, the targetPriority is empty or null."); throw new IllegalArgumentException("Parameter error, the targetPriority is empty or null."); } try { long startTime = clock.getTime(); DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId); Response response = interceptor.updateApplicationPriority(targetPriority, hsr, appId); if (response != null) { long stopTime = clock.getTime(); routerMetrics.succeededUpdateAppPriorityRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), UPDATE_APPLICATIONPRIORITY, TARGET_WEB_SERVICE); return response; } } catch (IllegalArgumentException e) { routerMetrics.incrUpdateAppPriorityFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APPLICATIONPRIORITY, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "Unable to get the updateApplicationPriority appId: %s.", appId); } catch (YarnException e) { routerMetrics.incrUpdateAppPriorityFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APPLICATIONPRIORITY, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException("updateApplicationPriority error.", e); } RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APPLICATIONPRIORITY, UNKNOWN, TARGET_WEB_SERVICE, "getAppPriority Failed."); routerMetrics.incrUpdateAppPriorityFailedRetrieved(); throw new RuntimeException("updateApplicationPriority Failed."); } @Override public AppQueue getAppQueue(HttpServletRequest hsr, String appId) throws AuthorizationException { try { long startTime = clock.getTime(); DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId); AppQueue queue = interceptor.getAppQueue(hsr, appId); if (queue != null) { long stopTime = clock.getTime(); routerMetrics.succeededGetAppQueueRetrieved((stopTime - startTime)); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_QUEUEINFO, TARGET_WEB_SERVICE); return queue; } } catch (IllegalArgumentException e) { routerMetrics.incrGetAppQueueFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_QUEUEINFO, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "Unable to get queue by appId: %s.", appId); } catch (YarnException e) { routerMetrics.incrGetAppQueueFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_QUEUEINFO, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException("getAppQueue error.", e); } RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_QUEUEINFO, UNKNOWN, TARGET_WEB_SERVICE, "getAppQueue Failed."); routerMetrics.incrGetAppQueueFailedRetrieved(); throw new RuntimeException("getAppQueue Failed."); } @Override public Response updateAppQueue(AppQueue targetQueue, HttpServletRequest hsr, String appId) throws AuthorizationException, YarnException, InterruptedException, IOException { if (targetQueue == null) { routerMetrics.incrUpdateAppQueueFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APP_QUEUE, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, the targetQueue is null."); throw new IllegalArgumentException("Parameter error, the targetQueue is null."); } try { long startTime = clock.getTime(); DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId); Response response = interceptor.updateAppQueue(targetQueue, hsr, appId); if (response != null) { long stopTime = clock.getTime(); routerMetrics.succeededUpdateAppQueueRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), UPDATE_APP_QUEUE, TARGET_WEB_SERVICE); return response; } } catch (IllegalArgumentException e) { routerMetrics.incrUpdateAppQueueFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APP_QUEUE, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "Unable to update app queue by appId: %s.", appId); } catch (YarnException e) { routerMetrics.incrUpdateAppQueueFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APP_QUEUE, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException("updateAppQueue error.", e); } RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APP_QUEUE, UNKNOWN, TARGET_WEB_SERVICE, "updateAppQueue Failed."); routerMetrics.incrUpdateAppQueueFailedRetrieved(); throw new RuntimeException("updateAppQueue Failed."); } /** * This method posts a delegation token from the client. * * @param tokenData the token to delegate. It is a content param. * @param hsr the servlet request. * @return Response containing the status code. * @throws AuthorizationException if Kerberos auth failed. * @throws IOException if the delegation failed. * @throws InterruptedException if interrupted. * @throws Exception in case of bad request. */ @Override public Response postDelegationToken(DelegationToken tokenData, HttpServletRequest hsr) throws AuthorizationException, IOException, InterruptedException, Exception { if (tokenData == null || hsr == null) { RouterAuditLogger.logFailure(getUser().getShortUserName(), POST_DELEGATION_TOKEN, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, the tokenData or hsr is null."); throw new IllegalArgumentException("Parameter error, the tokenData or hsr is null."); } try { // get Caller UserGroupInformation Configuration conf = federationFacade.getConf(); UserGroupInformation callerUGI = getKerberosUserGroupInformation(conf, hsr); // create a delegation token return createDelegationToken(tokenData, callerUGI); } catch (YarnException e) { LOG.error("Create delegation token request failed.", e); RouterAuditLogger.logFailure(getUser().getShortUserName(), POST_DELEGATION_TOKEN, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); return Response.status(Status.FORBIDDEN).entity(e.getMessage()).build(); } } /** * Create DelegationToken. * * @param dtoken DelegationToken Data. * @param callerUGI UserGroupInformation. * @return Response. * @throws Exception An exception occurred when creating a delegationToken. */ private Response createDelegationToken(DelegationToken dtoken, UserGroupInformation callerUGI) throws IOException, InterruptedException { String renewer = dtoken.getRenewer(); GetDelegationTokenResponse resp = callerUGI.doAs( (PrivilegedExceptionAction<GetDelegationTokenResponse>) () -> { GetDelegationTokenRequest createReq = GetDelegationTokenRequest.newInstance(renewer); return this.getRouterClientRMService().getDelegationToken(createReq); }); DelegationToken respToken = getDelegationToken(renewer, resp); RouterAuditLogger.logSuccess(getUser().getShortUserName(), POST_DELEGATION_TOKEN, TARGET_WEB_SERVICE); return Response.status(Status.OK).entity(respToken).build(); } /** * Get DelegationToken. * * @param renewer renewer. * @param resp GetDelegationTokenResponse. * @return DelegationToken. * @throws IOException if there are I/O errors. */ private DelegationToken getDelegationToken(String renewer, GetDelegationTokenResponse resp) throws IOException { // Step1. Parse token from GetDelegationTokenResponse. Token<RMDelegationTokenIdentifier> tk = getToken(resp); String tokenKind = tk.getKind().toString(); RMDelegationTokenIdentifier tokenIdentifier = tk.decodeIdentifier(); String owner = tokenIdentifier.getOwner().toString(); long maxDate = tokenIdentifier.getMaxDate(); // Step2. Call the
of
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/IncludeExclude.java
{ "start": 18387, "end": 26138 }
class ____ extends Terms { private final SortedSetDocValues values; DocValuesTerms(SortedSetDocValues values) { this.values = values; } @Override public TermsEnum iterator() throws IOException { return values.termsEnum(); } @Override public long size() throws IOException { return -1; } @Override public long getSumTotalTermFreq() throws IOException { return -1; } @Override public long getSumDocFreq() throws IOException { return -1; } @Override public int getDocCount() throws IOException { return -1; } @Override public boolean hasFreqs() { return false; } @Override public boolean hasOffsets() { return false; } @Override public boolean hasPositions() { return false; } @Override public boolean hasPayloads() { return false; } } private static Set<BytesRef> parseArrayToSet(XContentParser parser) throws IOException { final Set<BytesRef> set = new HashSet<>(); if (parser.currentToken() != XContentParser.Token.START_ARRAY) { throw new ElasticsearchParseException("Missing start of array in include/exclude clause"); } while (parser.nextToken() != XContentParser.Token.END_ARRAY) { if (parser.currentToken().isValue() == false) { throw new ElasticsearchParseException("Array elements in include/exclude clauses should be string values"); } set.add(new BytesRef(parser.text())); } return set; } public boolean isRegexBased() { return include != null || exclude != null; } public boolean isPartitionBased() { return incNumPartitions > 0; } private Automaton toAutomaton() { Automaton a = null; if (include == null && exclude == null) { return a; } if (include != null) { a = include.toAutomaton(); } else { a = Automata.makeAnyString(); } if (exclude != null) { a = Operations.minus(a, exclude.toAutomaton(), Operations.DEFAULT_DETERMINIZE_WORK_LIMIT); } return Operations.determinize(a, Operations.DEFAULT_DETERMINIZE_WORK_LIMIT); } public StringFilter convertToStringFilter(DocValueFormat format) { if (isPartitionBased()) { return new PartitionedStringFilter(); } return new SetAndRegexStringFilter(format); } private static SortedSet<BytesRef> parseForDocValues(SortedSet<BytesRef> endUserFormattedValues, DocValueFormat format) { SortedSet<BytesRef> result = endUserFormattedValues; if (endUserFormattedValues != null) { if (format != DocValueFormat.RAW) { result = new TreeSet<>(); for (BytesRef formattedVal : endUserFormattedValues) { result.add(format.parseBytesRef(formattedVal.utf8ToString())); } } } return result; } public OrdinalsFilter convertToOrdinalsFilter(DocValueFormat format) { if (isPartitionBased()) { return new PartitionedOrdinalsFilter(); } return new SetAndRegexOrdinalsFilter(format); } public LongFilter convertToLongFilter(DocValueFormat format) { if (isPartitionBased()) { return new PartitionedLongFilter(); } int numValids = includeValues == null ? 0 : includeValues.size(); int numInvalids = excludeValues == null ? 0 : excludeValues.size(); SetBackedLongFilter result = new SetBackedLongFilter(numValids, numInvalids); if (includeValues != null) { for (BytesRef val : includeValues) { result.addAccept(format.parseLong(val.utf8ToString(), false, null)); } } if (excludeValues != null) { for (BytesRef val : excludeValues) { result.addReject(format.parseLong(val.utf8ToString(), false, null)); } } return result; } public LongFilter convertToDoubleFilter() { if (isPartitionBased()) { return new PartitionedLongFilter(); } int numValids = includeValues == null ? 0 : includeValues.size(); int numInvalids = excludeValues == null ? 0 : excludeValues.size(); SetBackedLongFilter result = new SetBackedLongFilter(numValids, numInvalids); if (includeValues != null) { for (BytesRef val : includeValues) { double dval = Double.parseDouble(val.utf8ToString()); result.addAccept(NumericUtils.doubleToSortableLong(dval)); } } if (excludeValues != null) { for (BytesRef val : excludeValues) { double dval = Double.parseDouble(val.utf8ToString()); result.addReject(NumericUtils.doubleToSortableLong(dval)); } } return result; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (include != null) { builder.field(INCLUDE_FIELD.getPreferredName(), include.getOriginalString()); } else if (includeValues != null) { builder.startArray(INCLUDE_FIELD.getPreferredName()); for (BytesRef value : includeValues) { builder.value(value.utf8ToString()); } builder.endArray(); } else if (isPartitionBased()) { builder.startObject(INCLUDE_FIELD.getPreferredName()); builder.field(PARTITION_FIELD.getPreferredName(), incZeroBasedPartition); builder.field(NUM_PARTITIONS_FIELD.getPreferredName(), incNumPartitions); builder.endObject(); } if (exclude != null) { builder.field(EXCLUDE_FIELD.getPreferredName(), exclude.getOriginalString()); } else if (excludeValues != null) { builder.startArray(EXCLUDE_FIELD.getPreferredName()); for (BytesRef value : excludeValues) { builder.value(value.utf8ToString()); } builder.endArray(); } return builder; } @Override public int hashCode() { return Objects.hash( include == null ? null : include.getOriginalString(), exclude == null ? null : exclude.getOriginalString(), includeValues, excludeValues, incZeroBasedPartition, incNumPartitions ); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } IncludeExclude other = (IncludeExclude) obj; return Objects.equals( include == null ? null : include.getOriginalString(), other.include == null ? null : other.include.getOriginalString() ) && Objects.equals( exclude == null ? null : exclude.getOriginalString(), other.exclude == null ? null : other.exclude.getOriginalString() ) && Objects.equals(includeValues, other.includeValues) && Objects.equals(excludeValues, other.excludeValues) && Objects.equals(incZeroBasedPartition, other.incZeroBasedPartition) && Objects.equals(incNumPartitions, other.incNumPartitions); } }
DocValuesTerms
java
quarkusio__quarkus
extensions/spring-di/deployment/src/main/java/io/quarkus/spring/di/deployment/SpringBeanNameToDotNameBuildItem.java
{ "start": 370, "end": 655 }
class ____ extends SimpleBuildItem { private final Map<String, DotName> map; public SpringBeanNameToDotNameBuildItem(Map<String, DotName> map) { this.map = map; } public Map<String, DotName> getMap() { return map; } }
SpringBeanNameToDotNameBuildItem
java
apache__camel
core/camel-main/src/main/java/org/apache/camel/main/Otel2ConfigurationProperties.java
{ "start": 1077, "end": 2122 }
class ____ implements BootstrapCloseable { private MainConfigurationProperties parent; private boolean enabled; @Metadata(defaultValue = "camel", required = true) private String instrumentationName = "camel"; private boolean encoding; private String excludePatterns; private boolean traceProcessors; public Otel2ConfigurationProperties(MainConfigurationProperties parent) { this.parent = parent; } public MainConfigurationProperties end() { return parent; } @Override public void close() { parent = null; } public boolean isEnabled() { return enabled; } /** * To enable OpenTelemetry 2 */ public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getInstrumentationName() { return instrumentationName; } /** * A name uniquely identifying the instrumentation scope, such as the instrumentation library, package, or fully * qualified
Otel2ConfigurationProperties
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/TinyIntJdbcType.java
{ "start": 897, "end": 3034 }
class ____ implements JdbcType { public static final TinyIntJdbcType INSTANCE = new TinyIntJdbcType(); public TinyIntJdbcType() { } @Override public int getJdbcTypeCode() { return Types.TINYINT; } @Override public String getFriendlyName() { return "TINYINT"; } @Override public String toString() { return "TinyIntTypeDescriptor"; } @Override public <T> JavaType<T> getJdbcRecommendedJavaTypeMapping( Integer length, Integer scale, TypeConfiguration typeConfiguration) { return typeConfiguration.getJavaTypeRegistry().getDescriptor( Byte.class ); } @Override public <T> JdbcLiteralFormatter<T> getJdbcLiteralFormatter(JavaType<T> javaType) { return new JdbcLiteralFormatterNumericData<>( javaType, Byte.class ); } @Override public Class<?> getPreferredJavaTypeClass(WrapperOptions options) { return Byte.class; } @Override public <X> ValueBinder<X> getBinder(final JavaType<X> javaType) { return new BasicBinder<>( javaType, this ) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { st.setByte( index, javaType.unwrap( value, Byte.class, options ) ); } @Override protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException { st.setByte( name, javaType.unwrap( value, Byte.class, options ) ); } }; } @Override public <X> ValueExtractor<X> getExtractor(final JavaType<X> javaType) { return new BasicExtractor<>( javaType, this ) { @Override protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException { return javaType.wrap( rs.getByte( paramIndex ), options ); } @Override protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException { return javaType.wrap( statement.getByte( index ), options ); } @Override protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException { return javaType.wrap( statement.getByte( name ), options ); } }; } }
TinyIntJdbcType
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/jdk/Base64DecodingTest.java
{ "start": 507, "end": 2116 }
class ____ { private final ObjectMapper MAPPER = newJsonMapper(); private final byte[] HELLO_BYTES = "hello".getBytes(StandardCharsets.UTF_8); private final String BASE64_HELLO = "aGVsbG8="; // for [databind#1425] @Test public void testInvalidBase64() throws Exception { byte[] b = MAPPER.readValue(q(BASE64_HELLO), byte[].class); assertArrayEquals(HELLO_BYTES, b); _testInvalidBase64(MAPPER, BASE64_HELLO+"!"); _testInvalidBase64(MAPPER, BASE64_HELLO+"!!"); } private void _testInvalidBase64(ObjectMapper mapper, String value) throws Exception { // First, use data-binding try { MAPPER.readValue(q(value), byte[].class); fail("Should not pass"); } catch (MismatchedInputException e) { // 16-Jan-2021, tatu: Message changed for 3.0 a bit // verifyException(e, "Failed to decode"); verifyException(e, "Cannot deserialize value of type `byte[]` from String"); verifyException(e, "Illegal character '!'"); verifyException(e, "in base64 content"); } // and then tree model JsonNode tree = mapper.readTree(String.format("{\"foo\":\"%s\"}", value)); JsonNode nodeValue = tree.get("foo"); try { /*byte[] b =*/ nodeValue.binaryValue(); fail("Should not pass"); } catch (JsonNodeException e) { verifyException(e, "method `binaryValue()` cannot convert value"); verifyException(e, "Illegal character '!'"); } } }
Base64DecodingTest
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_Test.java
{ "start": 11377, "end": 13370 }
interface ____.apache.dubbo.common.extension.ext2.Ext2 is not adaptive method!")); } } @Test void test_urlHolder_getAdaptiveExtension_ExceptionWhenNameNotProvided() throws Exception { Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1"); UrlHolder holder = new UrlHolder(); holder.setUrl(url); try { ext.echo(holder, "impl1"); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("Failed to get extension")); } url = url.addParameter("key1", "impl1"); holder.setUrl(url); try { ext.echo(holder, "haha"); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Failed to get extension (org.apache.dubbo.common.extension.ext2.Ext2) name from url")); } } @Test void test_getAdaptiveExtension_inject() throws Exception { LogUtil.start(); Ext6 ext = ExtensionLoader.getExtensionLoader(Ext6.class).getAdaptiveExtension(); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1"); url = url.addParameters("ext6", "impl1"); assertEquals("Ext6Impl1-echo-Ext1Impl1-echo", ext.echo(url, "ha")); Assertions.assertTrue(LogUtil.checkNoError(), "can not find error."); LogUtil.stop(); url = url.addParameters("simple.ext", "impl2"); assertEquals("Ext6Impl1-echo-Ext1Impl2-echo", ext.echo(url, "ha")); } @Test void test_getAdaptiveExtension_InjectNotExtFail() throws Exception { Ext6 ext = ExtensionLoader.getExtensionLoader(Ext6.class).getExtension("impl2"); Ext6Impl2 impl = (Ext6Impl2) ext; assertNull(impl.getList()); } }
org
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/dynamic/segment/CommandSegment.java
{ "start": 444, "end": 1912 }
class ____ { /** * Create a constant {@link CommandSegment}. * * @param content must not be empty or {@code null}. * @return the {@link CommandSegment}. */ public static CommandSegment constant(String content) { return new Constant(content); } /** * Create a named parameter reference {@link CommandSegment}. * * @param name must not be empty or {@code null}. * @return */ public static CommandSegment namedParameter(String name) { return new NamedParameter(name); } public static CommandSegment indexedParameter(int index) { return new IndexedParameter(index); } /** * * @return the command segment in its {@link String representation} */ public abstract String asString(); /** * Check whether this segment can consume the {@link Parameter} by applying parameter substitution. * * @param parameter * @return * @since 5.1.3 */ public abstract boolean canConsume(Parameter parameter); /** * @param parametersAccessor * @return */ public abstract ArgumentContribution contribute(MethodParametersAccessor parametersAccessor); @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); sb.append(" ").append(asString()); return sb.toString(); } private static
CommandSegment
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/ai21/Ai21Service.java
{ "start": 10589, "end": 10730 }
class ____ the AI21 inference service. * It provides the settings and configurations required for the service. */ public static
for
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/config/DummyErrorHandlerBuilder.java
{ "start": 2160, "end": 2847 }
class ____ extends ErrorHandlerReifier<DummyErrorHandlerBuilder> { public DummyErrorHandlerReifier(Route route, ErrorHandlerFactory definition) { super(route, (DummyErrorHandlerBuilder) definition); } @Override public Processor createErrorHandler(Processor processor) throws Exception { return new DelegateProcessor(processor) { @Override public void process(Exchange exchange) throws Exception { exchange.setProperty(PROPERTY_NAME, definition.getBeanName()); super.process(exchange); } }; } } }
DummyErrorHandlerReifier
java
apache__camel
components/camel-undertow/src/test/java/org/apache/camel/component/undertow/ws/UndertowWsTwoRoutesToSameEndpointSendToAllHeaderTest.java
{ "start": 1292, "end": 2964 }
class ____ extends BaseUndertowTest { @Test public void testWSHttpCallEcho() throws Exception { WebsocketTestClient testClient = new WebsocketTestClient("ws://localhost:" + getPort() + "/bar", 2); testClient.connect(); testClient.sendTextMessage("Beer"); assertTrue(testClient.await(10, TimeUnit.SECONDS)); assertEquals(2, testClient.getReceived().size()); //Cannot guarantee the order in which messages are received assertTrue(testClient.getReceived().contains("The bar has Beer")); assertTrue(testClient.getReceived().contains("Broadcasting to Bar")); testClient.close(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { final int port = getPort(); from("undertow:ws://localhost:" + port + "/bar") .log(">>> Message received from BAR WebSocket Client : ${body}") .transform().simple("The bar has ${body}") .to("undertow:ws://localhost:" + port + "/bar"); from("timer://foo?fixedRate=true&period=12000") //Use a period which is longer then the latch await time .setBody(constant("Broadcasting to Bar")) .log(">>> Broadcasting message to Bar WebSocket Client") .setHeader(UndertowConstants.SEND_TO_ALL, constant(true)) .to("undertow:ws://localhost:" + port + "/bar"); } }; } }
UndertowWsTwoRoutesToSameEndpointSendToAllHeaderTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SqlEndpointBuilderFactory.java
{ "start": 87569, "end": 89045 }
class ____ a * default constructor to create instance with. d) If the query resulted * in more than one rows, it throws an non-unique result exception. * StreamList streams the result of the query using an Iterator. This * can be used with the Splitter EIP in streaming mode to process the * ResultSet in streaming fashion. * * The option is a: * <code>org.apache.camel.component.sql.SqlOutputType</code> type. * * Default: SelectList * Group: common * * @param outputType the value to set * @return the dsl builder */ default SqlEndpointBuilder outputType(org.apache.camel.component.sql.SqlOutputType outputType) { doSetProperty("outputType", outputType); return this; } /** * Make the output of consumer or producer to SelectList as List of Map, * or SelectOne as single Java object in the following way: a) If the * query has only single column, then that JDBC Column object is * returned. (such as SELECT COUNT( ) FROM PROJECT will return a Long * object. b) If the query has more than one column, then it will return * a Map of that result. c) If the outputClass is set, then it will * convert the query result into an Java bean object by calling all the * setters that match the column names. It will assume your
has
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/operator/topn/KeyExtractorForFloat.java
{ "start": 3248, "end": 3854 }
class ____ extends KeyExtractorForFloat { private final FloatBlock block; MaxFromAscendingBlock(TopNEncoder encoder, byte nul, byte nonNul, FloatBlock block) { super(encoder, nul, nonNul); this.block = block; } @Override public int writeKey(BreakingBytesRefBuilder key, int position) { if (block.isNull(position)) { return nul(key); } return nonNul(key, block.getFloat(block.getFirstValueIndex(position) + block.getValueCount(position) - 1)); } } static
MaxFromAscendingBlock
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/isolation/SynchronizationTest.java
{ "start": 2420, "end": 3736 }
class ____ { public static final Logger log = LoggerFactory.getLogger(SynchronizationTest.class); private String threadPrefix; private Plugins plugins; private ThreadPoolExecutor exec; private Breakpoint<String> dclBreakpoint; private Breakpoint<String> pclBreakpoint; @BeforeEach public void setup(TestInfo testInfo) { Map<String, String> pluginProps = Map.of( WorkerConfig.PLUGIN_PATH_CONFIG, TestPlugins.pluginPathJoined() ); threadPrefix = SynchronizationTest.class.getSimpleName() + "." + testInfo.getDisplayName() + "-"; dclBreakpoint = new Breakpoint<>(); pclBreakpoint = new Breakpoint<>(); plugins = new Plugins(pluginProps, Plugins.class.getClassLoader(), new SynchronizedClassLoaderFactory()); exec = new ThreadPoolExecutor( 2, 2, 1000L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(), threadFactoryWithNamedThreads(threadPrefix) ); } @AfterEach public void tearDown() throws InterruptedException { dclBreakpoint.clear(); pclBreakpoint.clear(); exec.shutdown(); exec.awaitTermination(1L, TimeUnit.SECONDS); } private static
SynchronizationTest
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/scheduling/concurrent/ConcurrentTaskScheduler.java
{ "start": 12375, "end": 12952 }
class ____ implements jakarta.enterprise.concurrent.Trigger { private final Trigger adaptee; public TriggerAdapter(Trigger adaptee) { this.adaptee = adaptee; } @Override public @Nullable Date getNextRunTime(@Nullable LastExecution le, Date taskScheduledTime) { Instant instant = this.adaptee.nextExecution(new LastExecutionAdapter(le)); return (instant != null ? Date.from(instant) : null); } @Override public boolean skipRun(LastExecution lastExecutionInfo, Date scheduledRunTime) { return false; } private static
TriggerAdapter
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/manual/ManualTriggerEvent.java
{ "start": 577, "end": 1830 }
class ____ extends TriggerEvent { private final TriggerEvent triggerEvent; public ManualTriggerEvent(String jobName, TriggerEvent triggerEvent) { super(jobName, triggerEvent.triggeredTime()); this.triggerEvent = triggerEvent; data.putAll(triggerEvent.data()); } @Override public String type() { return ManualTriggerEngine.TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(triggerEvent.type(), triggerEvent, params); return builder.endObject(); } @Override public void recordDataXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(ManualTriggerEngine.TYPE); triggerEvent.recordDataXContent(builder, params); builder.endObject(); } public static ManualTriggerEvent parse(TriggerService triggerService, String watchId, String context, XContentParser parser) throws IOException { TriggerEvent parsedTriggerEvent = triggerService.parseTriggerEvent(watchId, context, parser); return new ManualTriggerEvent(context, parsedTriggerEvent); } }
ManualTriggerEvent
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/duplicate/DuplicateResourceAndClientTest.java
{ "start": 496, "end": 935 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addClasses(Client.class, Resource.class)); @Test public void dummy() { when() .get("/hello") .then() .statusCode(200); } @Path("/hello") public
DuplicateResourceAndClientTest
java
apache__camel
components/camel-aws/camel-aws2-iam/src/test/java/org/apache/camel/component/aws2/iam/integration/IAMListAccessKeyIT.java
{ "start": 1301, "end": 3190 }
class ____ extends Aws2IAMBase { @EndpointInject("mock:result") private MockEndpoint mock; @Test public void iamCreateUserTest() throws Exception { mock.expectedMessageCount(1); Exchange exchange = template.request("direct:createUser", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IAM2Constants.OPERATION, IAM2Operations.createUser); exchange.getIn().setHeader(IAM2Constants.USERNAME, "test"); } }); exchange = template.request("direct:createAccessKey", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IAM2Constants.OPERATION, IAM2Operations.createAccessKey); exchange.getIn().setHeader(IAM2Constants.USERNAME, "test"); } }); exchange = template.request("direct:listKeys", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IAM2Constants.OPERATION, IAM2Operations.listAccessKeys); exchange.getIn().setBody(ListAccessKeysRequest.builder().userName("test").build()); } }); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:createUser").to("aws2-iam://test?operation=createUser"); from("direct:createAccessKey").to("aws2-iam://test?operation=createAccessKey"); from("direct:listKeys").to("aws2-iam://test?operation=listAccessKeys&pojoRequest=true") .to("mock:result"); } }; } }
IAMListAccessKeyIT
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/test/lombok/FooBean.java
{ "start": 278, "end": 335 }
class ____ { private String lombokFieldsTest; }
FooBean
java
spring-projects__spring-boot
module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java
{ "start": 951, "end": 2890 }
class ____ { private final File sourceDirectory; private final File file; private final Type type; /** * Create a new {@link ChangedFile} instance. * @param sourceDirectory the source directory * @param file the file * @param type the type of change */ public ChangedFile(File sourceDirectory, File file, Type type) { Assert.notNull(sourceDirectory, "'sourceDirectory' must not be null"); Assert.notNull(file, "'file' must not be null"); Assert.notNull(type, "'type' must not be null"); this.sourceDirectory = sourceDirectory; this.file = file; this.type = type; } /** * Return the file that was changed. * @return the file */ public File getFile() { return this.file; } /** * Return the type of change. * @return the type of change */ public Type getType() { return this.type; } /** * Return the name of the file relative to the source directory. * @return the relative name */ public String getRelativeName() { File directory = this.sourceDirectory.getAbsoluteFile(); File file = this.file.getAbsoluteFile(); String directoryName = StringUtils.cleanPath(directory.getPath()); String fileName = StringUtils.cleanPath(file.getPath()); Assert.state(fileName.startsWith(directoryName), () -> "The file " + fileName + " is not contained in the source directory " + directoryName); return fileName.substring(directoryName.length() + 1); } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (obj instanceof ChangedFile other) { return this.file.equals(other.file) && this.type.equals(other.type); } return super.equals(obj); } @Override public int hashCode() { return this.file.hashCode() * 31 + this.type.hashCode(); } @Override public String toString() { return this.file + " (" + this.type + ")"; } /** * Change types. */ public
ChangedFile
java
google__guava
android/guava-tests/test/com/google/common/collect/UnmodifiableMultimapAsMapImplementsMapTest.java
{ "start": 1005, "end": 1615 }
class ____ extends AbstractMultimapAsMapImplementsMapTest { public UnmodifiableMultimapAsMapImplementsMapTest() { super(false, true, false); } @Override protected Map<String, Collection<Integer>> makeEmptyMap() { return Multimaps.unmodifiableMultimap(LinkedHashMultimap.<String, Integer>create()).asMap(); } @Override protected Map<String, Collection<Integer>> makePopulatedMap() { Multimap<String, Integer> delegate = LinkedHashMultimap.create(); populate(delegate); return Multimaps.unmodifiableMultimap(delegate).asMap(); } }
UnmodifiableMultimapAsMapImplementsMapTest
java
apache__spark
common/network-common/src/main/java/org/apache/spark/network/protocol/ChunkFetchSuccess.java
{ "start": 1401, "end": 2902 }
class ____ extends AbstractResponseMessage { public final StreamChunkId streamChunkId; public ChunkFetchSuccess(StreamChunkId streamChunkId, ManagedBuffer buffer) { super(buffer, true); this.streamChunkId = streamChunkId; } @Override public Message.Type type() { return Type.ChunkFetchSuccess; } @Override public int encodedLength() { return streamChunkId.encodedLength(); } /** Encoding does NOT include 'buffer' itself. See {@link MessageEncoder}. */ @Override public void encode(ByteBuf buf) { streamChunkId.encode(buf); } @Override public ResponseMessage createFailureResponse(String error) { return new ChunkFetchFailure(streamChunkId, error); } /** Decoding uses the given ByteBuf as our data, and will retain() it. */ public static ChunkFetchSuccess decode(ByteBuf buf) { StreamChunkId streamChunkId = StreamChunkId.decode(buf); buf.retain(); NettyManagedBuffer managedBuf = new NettyManagedBuffer(buf.duplicate()); return new ChunkFetchSuccess(streamChunkId, managedBuf); } @Override public int hashCode() { return Objects.hash(streamChunkId, body()); } @Override public boolean equals(Object other) { if (other instanceof ChunkFetchSuccess o) { return streamChunkId.equals(o.streamChunkId) && super.equals(o); } return false; } @Override public String toString() { return "ChunkFetchSuccess[streamChunkId=" + streamChunkId + ",body=" + body() + "]"; } }
ChunkFetchSuccess
java
google__gson
gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java
{ "start": 4310, "end": 4575 }
enum ____ { SUB_TYPE1(SubType1.class), SUB_TYPE2(SubType2.class); private final Type subClass; private SubTypes(Type subClass) { this.subClass = subClass; } Type getSubclass() { return subClass; } } private static
SubTypes
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/cli/util/CryptoAdminCmdExecutor.java
{ "start": 942, "end": 1390 }
class ____ extends CommandExecutor { protected String namenode = null; protected CryptoAdmin admin = null; public CryptoAdminCmdExecutor(String namenode, CryptoAdmin admin) { this.namenode = namenode; this.admin = admin; } @Override protected int execute(final String cmd) throws Exception { String[] args = getCommandAsArgs(cmd, "NAMENODE", this.namenode); return ToolRunner.run(admin, args); } }
CryptoAdminCmdExecutor
java
elastic__elasticsearch
x-pack/plugin/transform/qa/multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/transform/integration/TransformRestTestCase.java
{ "start": 3154, "end": 23111 }
class ____ extends TransformCommonRestTestCase { private final Set<String> createdTransformIds = new HashSet<>(); protected void cleanUp() throws Exception { logAudits(); cleanUpTransforms(); waitForPendingTasks(); } protected void cleanUpTransforms() throws IOException { for (String id : createdTransformIds) { try { stopTransform(id); deleteTransform(id); } catch (ResponseException ex) { if (ex.getResponse().getStatusLine().getStatusCode() == RestStatus.NOT_FOUND.getStatus()) { logger.info("tried to cleanup already deleted transform [{}]", id); } else { throw ex; } } } createdTransformIds.clear(); } protected Map<String, Object> getIndexMapping(String index, RequestOptions options) throws IOException { var r = new Request("GET", "/" + index + "/_mapping"); r.setOptions(options); return entityAsMap(client().performRequest(r)); } protected void stopTransform(String id) throws IOException { stopTransform(id, true, null, false, false); } protected void stopTransform( String id, boolean waitForCompletion, @Nullable TimeValue timeout, boolean waitForCheckpoint, boolean force ) throws IOException { final Request stopTransformRequest = new Request("POST", TRANSFORM_ENDPOINT + id + "/_stop"); stopTransformRequest.addParameter(TransformField.WAIT_FOR_COMPLETION.getPreferredName(), Boolean.toString(waitForCompletion)); stopTransformRequest.addParameter(TransformField.WAIT_FOR_CHECKPOINT.getPreferredName(), Boolean.toString(waitForCheckpoint)); if (timeout != null) { stopTransformRequest.addParameter(TransformField.TIMEOUT.getPreferredName(), timeout.getStringRep()); } if (force) { stopTransformRequest.addParameter(TransformField.FORCE.getPreferredName(), "true"); } assertAcknowledged(client().performRequest(stopTransformRequest)); } protected void startTransform(String id, RequestOptions options) throws IOException { Request startTransformRequest = new Request("POST", TRANSFORM_ENDPOINT + id + "/_start"); startTransformRequest.setOptions(options); assertAcknowledged(client().performRequest(startTransformRequest)); } // workaround for https://github.com/elastic/elasticsearch/issues/62204 protected void startTransformWithRetryOnConflict(String id, RequestOptions options) throws Exception { final int totalRetries = 10; long totalSleepTime = 0; ResponseException lastConflict = null; for (int retries = totalRetries; retries > 0; --retries) { try { startTransform(id, options); return; } catch (ResponseException e) { logger.warn( "Failed to start transform [{}], remaining retries [{}], error: [{}], status: [{}]", id, retries, e.getMessage(), e.getResponse().getStatusLine().getStatusCode() ); if ((RestStatus.CONFLICT.getStatus() == e.getResponse().getStatusLine().getStatusCode()) == false) { throw e; } lastConflict = e; // wait between some ms max 5s, between a check, // with 10 retries the total retry should not be longer than 10s final long sleepTime = 5 * Math.round((Math.min(Math.pow(2, 1 + totalRetries - retries), 1000))); totalSleepTime += sleepTime; Thread.sleep(sleepTime); } } throw new AssertionError("startTransformWithRetryOnConflict timed out after " + totalSleepTime + "ms", lastConflict); } protected void deleteTransform(String id) throws IOException { deleteTransform(id, false); } protected void deleteTransform(String id, boolean force) throws IOException { Request request = new Request("DELETE", TRANSFORM_ENDPOINT + id); if (force) { request.addParameter(TransformField.FORCE.getPreferredName(), "true"); } assertAcknowledged(adminClient().performRequest(request)); createdTransformIds.remove(id); } protected void putTransform(String id, String config, RequestOptions options) throws IOException { putTransform(id, config, false, options); } protected void putTransform(String id, String config, boolean deferValidation, RequestOptions options) throws IOException { if (createdTransformIds.contains(id)) { throw new IllegalArgumentException("transform [" + id + "] is already registered"); } Request request = new Request("PUT", TRANSFORM_ENDPOINT + id); request.setJsonEntity(config); if (deferValidation) { request.addParameter("defer_validation", "true"); } request.setOptions(options); assertAcknowledged(client().performRequest(request)); createdTransformIds.add(id); } protected Map<String, Object> previewTransform(String transformConfig, RequestOptions options) throws IOException { var request = new Request("POST", TRANSFORM_ENDPOINT + "_preview"); request.setJsonEntity(transformConfig); request.setOptions(options); return entityAsMap(client().performRequest(request)); } @SuppressWarnings("unchecked") protected Map<String, Object> getTransformStats(String id) throws IOException { var request = new Request("GET", TRANSFORM_ENDPOINT + id + "/_stats"); request.setOptions(RequestOptions.DEFAULT); Response response = client().performRequest(request); List<Map<String, Object>> stats = (List<Map<String, Object>>) XContentMapValues.extractValue("transforms", entityAsMap(response)); assertThat(stats, hasSize(1)); return stats.get(0); } @SuppressWarnings("unchecked") protected Map<String, Object> getBasicTransformStats(String id) throws IOException { var request = new Request("GET", TRANSFORM_ENDPOINT + id + "/_stats"); request.addParameter(BASIC_STATS.getPreferredName(), "true"); request.setOptions(RequestOptions.DEFAULT); var stats = (List<Map<String, Object>>) XContentMapValues.extractValue("transforms", entityAsMap(client().performRequest(request))); assertThat(stats, hasSize(1)); return stats.get(0); } protected String getTransformState(String id) throws IOException { return (String) getBasicTransformStats(id).get("state"); } protected String getTransformHealthStatus(String id) throws IOException { return (String) XContentMapValues.extractValue("health.status", getBasicTransformStats(id)); } @SuppressWarnings("unchecked") protected Map<String, Object> getTransform(String id) throws IOException { var request = new Request("GET", TRANSFORM_ENDPOINT + id); var transformConfigs = (List<Map<String, Object>>) XContentMapValues.extractValue( "transforms", entityAsMap(client().performRequest(request)) ); assertThat(transformConfigs, hasSize(1)); return transformConfigs.get(0); } protected Map<String, Object> getTransforms(String id) throws IOException { Request request = new Request("GET", TRANSFORM_ENDPOINT + id); return entityAsMap(client().performRequest(request)); } protected void waitUntilCheckpoint(String id, long checkpoint) throws Exception { waitUntilCheckpoint(id, checkpoint, TimeValue.timeValueSeconds(30)); } protected void waitUntilCheckpoint(String id, long checkpoint, TimeValue waitTime) throws Exception { assertBusy(() -> assertEquals(checkpoint, getCheckpoint(id)), waitTime.getMillis(), TimeUnit.MILLISECONDS); } protected long getCheckpoint(String id) throws IOException { return getCheckpoint(getBasicTransformStats(id)); } protected long getCheckpoint(Map<String, Object> stats) { return ((Integer) XContentMapValues.extractValue("checkpointing.last.checkpoint", stats)).longValue(); } protected DateHistogramGroupSource createDateHistogramGroupSourceWithCalendarInterval( String field, DateHistogramInterval interval, ZoneId zone ) { return new DateHistogramGroupSource(field, null, false, new DateHistogramGroupSource.CalendarInterval(interval), zone, null); } /** * GroupConfig has 2 internal representations - source and a map * of SingleGroupSource, both need to be present. * The fromXContent parser populates both so the trick here is * to JSON serialise {@code groups} and build the * GroupConfig from JSON. * * @param groups Agg factory * @param xContentRegistry registry * @return GroupConfig * @throws IOException on parsing */ public static GroupConfig createGroupConfig(Map<String, SingleGroupSource> groups, NamedXContentRegistry xContentRegistry) throws IOException { try (XContentBuilder builder = XContentFactory.jsonBuilder()) { builder.startObject(); for (Map.Entry<String, SingleGroupSource> entry : groups.entrySet()) { builder.startObject(entry.getKey()); builder.field(entry.getValue().getType().value(), entry.getValue()); builder.endObject(); } builder.endObject(); try ( XContentParser sourceParser = XContentType.JSON.xContent() .createParser( XContentParserConfiguration.EMPTY.withRegistry(xContentRegistry) .withDeprecationHandler(LoggingDeprecationHandler.INSTANCE), BytesReference.bytes(builder).streamInput() ) ) { return GroupConfig.fromXContent(sourceParser, false); } } } protected GroupConfig createGroupConfig(Map<String, SingleGroupSource> groups) throws IOException { return createGroupConfig(groups, xContentRegistry()); } /** * AggregationConfig has 2 internal representations - source and an * Aggregation Factory, both need to be present. * The fromXContent parser populates both so the trick here is * to JSON serialise {@code aggregations} and build the * AggregationConfig from JSON. * * @param aggregations Agg factory * @param xContentRegistry registry * @return AggregationConfig * @throws IOException on parsing */ public static AggregationConfig createAggConfig(AggregatorFactories.Builder aggregations, NamedXContentRegistry xContentRegistry) throws IOException { try (XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()) { aggregations.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); try ( XContentParser sourceParser = XContentType.JSON.xContent() .createParser( XContentParserConfiguration.EMPTY.withRegistry(xContentRegistry) .withDeprecationHandler(LoggingDeprecationHandler.INSTANCE), BytesReference.bytes(xContentBuilder).streamInput() ) ) { return AggregationConfig.fromXContent(sourceParser, false); } } } protected AggregationConfig createAggConfig(AggregatorFactories.Builder aggregations) throws IOException { return createAggConfig(aggregations, xContentRegistry()); } protected PivotConfig createPivotConfig(Map<String, SingleGroupSource> groups, AggregatorFactories.Builder aggregations) throws Exception { return new PivotConfig(createGroupConfig(groups), createAggConfig(aggregations), null); } protected TransformConfig.Builder createTransformConfigBuilder( String id, String destinationIndex, QueryConfig queryConfig, String... sourceIndices ) { return TransformConfig.builder() .setId(id) .setSource(new SourceConfig(sourceIndices, queryConfig, Collections.emptyMap())) .setDest(new DestConfig(destinationIndex, null, null)) .setFrequency(TimeValue.timeValueSeconds(10)) .setDescription("Test transform config id: " + id); } protected void updateConfig(String id, String update, RequestOptions options) throws Exception { updateConfig(id, update, false, options); } protected void updateConfig(String id, String update, boolean deferValidation, RequestOptions options) throws Exception { Request updateRequest = new Request("POST", "_transform/" + id + "/_update"); if (deferValidation) { updateRequest.addParameter("defer_validation", String.valueOf(deferValidation)); } updateRequest.setJsonEntity(update); updateRequest.setOptions(options); assertOKAndConsume(client().performRequest(updateRequest)); } protected void createReviewsIndex( String indexName, int numDocs, int numUsers, Function<Integer, Integer> userIdProvider, Function<Integer, String> dateStringProvider ) throws Exception { createReviewsIndex(indexName, numDocs, numUsers, userIdProvider, dateStringProvider, null); } protected void createReviewsIndex( String indexName, int numDocs, int numUsers, Function<Integer, Integer> userIdProvider, Function<Integer, String> dateStringProvider, String defaultPipeline ) throws Exception { assert numUsers > 0; createReviewsIndexMappings(indexName, defaultPipeline); // create index StringBuilder sourceBuilder = new StringBuilder(); for (int i = 0; i < numDocs; i++) { Integer user = userIdProvider.apply(i); int stars = i % 5; long business = i % 50; String dateString = dateStringProvider.apply(i); sourceBuilder.append(Strings.format(""" {"create":{"_index":"%s"}} """, indexName)); sourceBuilder.append("{"); if (user != null) { sourceBuilder.append("\"user_id\":\"").append("user_").append(user).append("\","); } sourceBuilder.append(Strings.format(""" "count":%s,"business_id":"business_%s","stars":%s,"comment":"Great stuff, deserves %s stars","regular_object":\ {"foo": 42},"nested_object":{"bar": 43},"timestamp":"%s"} """, i, business, stars, stars, dateString)); if (i % 100 == 0) { sourceBuilder.append("\r\n"); doBulk(sourceBuilder.toString(), false); sourceBuilder.setLength(0); } } sourceBuilder.append("\r\n"); doBulk(sourceBuilder.toString(), true); } protected void createReviewsIndexMappings(String indexName, String defaultPipeline) throws IOException { try (XContentBuilder builder = jsonBuilder()) { builder.startObject(); { builder.startObject("mappings") .startObject("properties") .startObject("timestamp") .field("type", "date") .endObject() .startObject("user_id") .field("type", "keyword") .endObject() .startObject("count") .field("type", "integer") .endObject() .startObject("business_id") .field("type", "keyword") .endObject() .startObject("stars") .field("type", "integer") .endObject() .startObject("regular_object") .field("type", "object") .endObject() .startObject("nested_object") .field("type", "nested") .endObject() .startObject("comment") .field("type", "text") .startObject("fields") .startObject("keyword") .field("type", "keyword") .endObject() .endObject() .endObject() .endObject() .endObject(); if (defaultPipeline != null) { builder.startObject("settings").field("index.default_pipeline", defaultPipeline).endObject(); } } builder.endObject(); final StringEntity indexMappings = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON); Request req = new Request("PUT", indexName); req.setEntity(indexMappings); req.setOptions(RequestOptions.DEFAULT); assertOKAndConsume(adminClient().performRequest(req)); } } protected void doBulk(String bulkDocuments, boolean refresh) throws IOException { Request bulkRequest = new Request("POST", "/_bulk"); if (refresh) { bulkRequest.addParameter("refresh", "true"); } bulkRequest.setJsonEntity(bulkDocuments); bulkRequest.setOptions(RequestOptions.DEFAULT); Response bulkResponse = adminClient().performRequest(bulkRequest); try { var bulkMap = entityAsMap(assertOK(bulkResponse)); assertThat((boolean) bulkMap.get("errors"), is(equalTo(false))); } finally { EntityUtils.consumeQuietly(bulkResponse.getEntity()); } } protected Map<String, Object> matchAllSearch(String index, int size, RequestOptions options) throws IOException { Request request = new Request("GET", index + "/_search"); request.addParameter("size", Integer.toString(size)); request.setOptions(options); Response response = client().performRequest(request); try { return entityAsMap(assertOK(response)); } finally { EntityUtils.consumeQuietly(response.getEntity()); } } private void waitForPendingTasks() { Request request = new Request(HttpGet.METHOD_NAME, "/_tasks"); Map<String, String> parameters = Map.of( "wait_for_completion", Boolean.TRUE.toString(), "detailed", Boolean.TRUE.toString(), "timeout", TimeValue.timeValueSeconds(10).getStringRep() ); request.addParameters(parameters); try { EntityUtils.consumeQuietly(adminClient().performRequest(request).getEntity()); } catch (Exception e) { throw new AssertionError("Failed to wait for pending tasks to complete", e); } } @Override protected NamedXContentRegistry xContentRegistry() { SearchModule searchModule = new SearchModule(Settings.EMPTY, Collections.emptyList()); return new NamedXContentRegistry(searchModule.getNamedXContents()); } @Override protected Settings restClientSettings() { final String token = "Basic " + Base64.getEncoder().encodeToString(("x_pack_rest_user:x-pack-test-password").getBytes(StandardCharsets.UTF_8)); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build(); } }
TransformRestTestCase
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/dynamic/DefaultMethodParametersAccessor.java
{ "start": 2986, "end": 4089 }
class ____ implements Iterator<Object> { private final int bindableParameterCount; private final DefaultMethodParametersAccessor accessor; private int currentIndex = 0; /** * Creates a new {@link BindableParameterIterator}. * * @param accessor must not be {@code null}. */ BindableParameterIterator(DefaultMethodParametersAccessor accessor) { LettuceAssert.notNull(accessor, "ParametersParameterAccessor must not be null!"); this.accessor = accessor; this.bindableParameterCount = accessor.getParameters().getBindableParameters().size(); } /** * Return the next bindable parameter. * * @return */ public Object next() { return accessor.getBindableValue(currentIndex++); } public boolean hasNext() { return bindableParameterCount > currentIndex; } public void remove() { throw new UnsupportedOperationException(); } } }
BindableParameterIterator
java
quarkusio__quarkus
extensions/container-image/container-image-jib/deployment/src/main/java/io/quarkus/container/image/jib/deployment/JibBuildEnabled.java
{ "start": 172, "end": 571 }
class ____ implements BooleanSupplier { private final ContainerImageConfig containerImageConfig; JibBuildEnabled(ContainerImageConfig containerImageConfig) { this.containerImageConfig = containerImageConfig; } @Override public boolean getAsBoolean() { return containerImageConfig.builder().map(b -> b.equals(JibProcessor.JIB)).orElse(true); } }
JibBuildEnabled
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/utils/MlTaskState.java
{ "start": 377, "end": 616 }
interface ____ { /** * The time of the last state change. */ @Nullable Instant getLastStateChangeTime(); /** * @return Is the task in the <code>failed</code> state? */ boolean isFailed(); }
MlTaskState
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/metrics/stats/Avg.java
{ "start": 1015, "end": 1556 }
class ____ extends SampledStat { public Avg() { super(0.0); } @Override protected void update(Sample sample, MetricConfig config, double value, long now) { sample.value += value; } @Override public double combine(List<Sample> samples, MetricConfig config, long now) { double total = 0.0; long count = 0; for (Sample s : samples) { total += s.value; count += s.eventCount; } return count == 0 ? Double.NaN : total / count; } }
Avg
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/interceptor/bindings/AdditionalInterceptorBindingsPredicateTest.java
{ "start": 4768, "end": 5226 }
class ____ { public static boolean INTERCEPTOR_TRIGGERED = false; @AroundInvoke public Object invoke(InvocationContext context) throws Exception { INTERCEPTOR_TRIGGERED = true; return context.proceed(); } } @ApplicationScoped @ToBeBinding @ToBeBindingWithNonBindingField("toBeIgnored") @ToBeBindingWithBindingField("notIgnored-mismatched") static
MyInterceptorForNonBindingField
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/util/SimpleStreamWriteContext.java
{ "start": 396, "end": 7342 }
class ____ extends TokenStreamContext { /** * Parent context for this context; null for root context. */ protected final SimpleStreamWriteContext _parent; // // // Optional duplicate detection protected DupDetector _dups; /* /********************************************************************** /* Simple instance reuse slots; speed up things a bit (10-15%) /* for docs with lots of small arrays/objects /********************************************************************** */ protected SimpleStreamWriteContext _childToRecycle; /* /********************************************************************** /* Location/state information (minus source reference) /********************************************************************** */ /** * Name of the property of which value is to be written; only * used for OBJECT contexts. */ protected String _currentName; protected Object _currentValue; /** * Marker used to indicate that we just wrote a property name (or possibly * property id for some backends) and now expect a value to write. */ protected boolean _gotPropertyId; /* /********************************************************************** /* Life-cycle /********************************************************************** */ protected SimpleStreamWriteContext(int type, SimpleStreamWriteContext parent, int nestingDepth, DupDetector dups, Object currentValue) { super(); _type = type; _parent = parent; _nestingDepth = nestingDepth; _dups = dups; _index = -1; _currentValue = currentValue; } // REMOVE as soon as nothing uses this /* @Deprecated protected SimpleStreamWriteContext(int type, SimpleStreamWriteContext parent, DupDetector dups, Object currentValue) { super(); _type = type; _parent = parent; _dups = dups; _index = -1; _currentValue = currentValue; } */ private SimpleStreamWriteContext reset(int type, Object currentValue) { _type = type; // Due to way reuse works, "_parent" and "_nestingDepth" are fine already _index = -1; _currentName = null; _gotPropertyId = false; _currentValue = currentValue; if (_dups != null) { _dups.reset(); } return this; } public SimpleStreamWriteContext withDupDetector(DupDetector dups) { _dups = dups; return this; } @Override public Object currentValue() { return _currentValue; } @Override public void assignCurrentValue(Object v) { _currentValue = v; } /* /********************************************************************** /* Factory methods /********************************************************************** */ public static SimpleStreamWriteContext createRootContext(DupDetector dd) { return new SimpleStreamWriteContext(TYPE_ROOT, null, 0, dd, null); } public SimpleStreamWriteContext createChildArrayContext(Object currentValue) { SimpleStreamWriteContext ctxt = _childToRecycle; if (ctxt == null) { _childToRecycle = ctxt = new SimpleStreamWriteContext(TYPE_ARRAY, this, _nestingDepth + 1, (_dups == null) ? null : _dups.child(), currentValue); return ctxt; } return ctxt.reset(TYPE_ARRAY, currentValue); } public SimpleStreamWriteContext createChildObjectContext(Object currentValue) { SimpleStreamWriteContext ctxt = _childToRecycle; if (ctxt == null) { _childToRecycle = ctxt = new SimpleStreamWriteContext(TYPE_OBJECT, this, _nestingDepth + 1, (_dups == null) ? null : _dups.child(), currentValue); return ctxt; } return ctxt.reset(TYPE_OBJECT, currentValue); } /* /********************************************************************** /* Accessors /********************************************************************** */ @Override public final SimpleStreamWriteContext getParent() { return _parent; } @Override public final String currentName() { // 15-Aug-2019, tatu: Should NOT check this status because otherwise name // in parent context is not accessible after new structured scope started // if (_gotPropertyId) { ... } return _currentName; } @Override public boolean hasCurrentName() { return _gotPropertyId; } /** * Method that can be used to both clear the accumulated references * (specifically value set with {@link #assignCurrentValue(Object)}) * that should not be retained, and returns parent (as would * {@link #getParent()} do). Typically called when closing the active * context when encountering {@link JsonToken#END_ARRAY} or * {@link JsonToken#END_OBJECT}. * * @return Parent context of this context node, if any; {@code null} for root context */ public SimpleStreamWriteContext clearAndGetParent() { _currentValue = null; // could also clear the current name, but seems cheap enough to leave? return _parent; } public DupDetector getDupDetector() { return _dups; } /* /********************************************************************** /* State changing /********************************************************************** */ /** * Method that writer is to call before it writes an Object Property name. * * @param name Name of Object property name being written * * @return {@code True} if name writing should proceed; {@code false} if not * * @throws StreamWriteException If write fails due to duplicate check */ public boolean writeName(String name) throws StreamWriteException { if ((_type != TYPE_OBJECT) || _gotPropertyId) { return false; } _gotPropertyId = true; _currentName = name; if (_dups != null) { _checkDup(_dups, name); } return true; } private final void _checkDup(DupDetector dd, String name) throws StreamWriteException { if (dd.isDup(name)) { Object src = dd.getSource(); throw new StreamWriteException(((src instanceof JsonGenerator) ? ((JsonGenerator) src) : null), "Duplicate Object property \""+name+"\""); } } public boolean writeValue() { // Only limitation is with OBJECTs: if (_type == TYPE_OBJECT) { if (!_gotPropertyId) { return false; } _gotPropertyId = false; } ++_index; return true; } }
SimpleStreamWriteContext
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/OneSizeGenerator.java
{ "start": 1108, "end": 2569 }
class ____<T, E extends @Nullable Object> implements OneSizeTestContainerGenerator<T, E> { private final TestContainerGenerator<T, E> generator; private final CollectionSize collectionSize; public OneSizeGenerator(TestContainerGenerator<T, E> generator, CollectionSize collectionSize) { this.generator = generator; this.collectionSize = collectionSize; } @Override public TestContainerGenerator<T, E> getInnerGenerator() { return generator; } @Override public SampleElements<E> samples() { return generator.samples(); } @Override public T create(Object... elements) { return generator.create(elements); } @Override public E[] createArray(int length) { return generator.createArray(length); } @Override public T createTestSubject() { Collection<E> elements = getSampleElements(getCollectionSize().getNumElements()); return generator.create(elements.toArray()); } @Override public Collection<E> getSampleElements(int howMany) { SampleElements<E> samples = samples(); List<E> allSampleElements = asList(samples.e0(), samples.e1(), samples.e2(), samples.e3(), samples.e4()); return new ArrayList<>(allSampleElements.subList(0, howMany)); } @Override public CollectionSize getCollectionSize() { return collectionSize; } @Override public Iterable<E> order(List<E> insertionOrder) { return generator.order(insertionOrder); } }
OneSizeGenerator
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialEvaluatorFactory.java
{ "start": 5012, "end": 6003 }
class ____ extends SpatialEvaluatorFactory< EvalOperator.ExpressionEvaluator.Factory, EvalOperator.ExpressionEvaluator.Factory> { SpatialEvaluatorFactoryWithFields( TriFunction< Source, EvalOperator.ExpressionEvaluator.Factory, EvalOperator.ExpressionEvaluator.Factory, EvalOperator.ExpressionEvaluator.Factory> factoryCreator ) { super(factoryCreator); } @Override public EvalOperator.ExpressionEvaluator.Factory get(SpatialSourceSupplier s, EvaluatorMapper.ToEvaluator toEvaluator) { return factoryCreator.apply(s.source(), toEvaluator.apply(s.left()), toEvaluator.apply(s.right())); } } /** * This evaluator factory is used when the right hand side is a constant or literal, * and the left is sourced from the index, or from previous evaluators. */ protected static
SpatialEvaluatorFactoryWithFields
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/reflection/TypeParameterResolverTest.java
{ "start": 20878, "end": 20934 }
class ____<T> implements ParentIface<T> { }
BaseHandler
java
elastic__elasticsearch
x-pack/plugin/security/cli/src/main/java/org/elasticsearch/xpack/security/cli/CertificateGenerateTool.java
{ "start": 35126, "end": 37389 }
class ____ { final String originalName; final X500Principal x500Principal; final String filename; final String error; private Name(String name, X500Principal x500Principal, String filename, String error) { this.originalName = name; this.x500Principal = x500Principal; this.filename = filename; this.error = error; } static Name fromUserProvidedName(String name, String filename) { if ("ca".equals(name)) { return new Name(name, null, null, "[ca] may not be used as an instance name"); } final X500Principal principal; try { if (name.contains("=")) { principal = new X500Principal(name); } else { principal = new X500Principal("CN=" + name); } } catch (IllegalArgumentException e) { String error = "[" + name + "] could not be converted to a valid DN\n" + e.getMessage() + "\n" + ExceptionsHelper.stackTrace(e); return new Name(name, null, null, error); } boolean validFilename = isValidFilename(filename); if (validFilename == false) { return new Name(name, principal, null, "[" + filename + "] is not a valid filename"); } return new Name(name, principal, resolvePath(filename).toString(), null); } static boolean isValidFilename(String name) { return ALLOWED_FILENAME_CHAR_PATTERN.matcher(name).matches() && ALLOWED_FILENAME_CHAR_PATTERN.matcher(resolvePath(name).toString()).matches() && name.startsWith(".") == false; } @Override public String toString() { return getClass().getSimpleName() + "{original=[" + originalName + "] principal=[" + x500Principal + "] file=[" + filename + "] err=[" + error + "]}"; } } static
Name
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/resource/MediaTypeFromMessageBodyWriterResource.java
{ "start": 438, "end": 1777 }
class ____ { @GET @Path("{type}") public Object hello(@PathParam("type") final String type, @HeaderParam("Accept") final String accept) throws Exception { return Class.forName(type).getDeclaredConstructor().newInstance(); } @GET @Path("fixed") public Object fixedResponse(@QueryParam("type") @DefaultValue(MediaType.TEXT_PLAIN) final MediaType type) { final List<Integer> body = Arrays.asList(1, 2, 3, 4, 5, 6); return Response.ok(body, type).build(); } @GET @Path("variants") public Response variantsResponse() { final List<Integer> body = Arrays.asList(1, 2, 3, 4, 5, 6); final List<Variant> variants = Variant .mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE, MediaType.TEXT_PLAIN_TYPE).build(); return Response.ok(body).variants(variants).build(); } @GET @Path("variantsObject") public Object variantsObjectResponse() { final List<Integer> body = Arrays.asList(1, 2, 3, 4, 5, 6); final List<Variant> variants = Variant .mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE, MediaType.TEXT_PLAIN_TYPE).build(); return Response.ok(body).variants(variants).build(); } }
MediaTypeFromMessageBodyWriterResource
java
apache__logging-log4j2
log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerContextResolver.java
{ "start": 1901, "end": 5704 }
class ____ extends TypeBasedParameterResolver<LoggerContext> implements BeforeAllCallback, BeforeEachCallback { private static final Object KEY = LoggerContextHolder.class; @Override public void beforeEach(ExtensionContext extensionContext) { final Class<?> testClass = extensionContext.getRequiredTestClass(); if (AnnotationSupport.isAnnotated(testClass, LoggerContextSource.class)) { final LoggerContextHolder holder = ExtensionContextAnchor.getAttribute(KEY, LoggerContextHolder.class, extensionContext); if (holder == null) { throw new IllegalStateException( "Specified @LoggerContextSource but no LoggerContext found for test class " + testClass.getCanonicalName()); } } AnnotationSupport.findAnnotation(extensionContext.getRequiredTestMethod(), LoggerContextSource.class) .ifPresent(source -> { final LoggerContextHolder holder = new LoggerContextHolder(source, extensionContext); ExtensionContextAnchor.setAttribute(KEY, holder, extensionContext); }); final LoggerContextHolder holder = ExtensionContextAnchor.getAttribute(KEY, LoggerContextHolder.class, extensionContext); if (holder != null) { ReflectionSupport.findFields( extensionContext.getRequiredTestClass(), f -> ModifierSupport.isNotStatic(f) && f.getType().equals(LoggerContext.class), HierarchyTraversalMode.TOP_DOWN) .forEach(f -> { try { f.setAccessible(true); f.set(extensionContext.getRequiredTestInstance(), holder.getLoggerContext()); } catch (ReflectiveOperationException e) { throw new ExtensionContextException("Failed to inject field " + f, e); } }); } } @Override public void beforeAll(ExtensionContext extensionContext) { final Class<?> testClass = extensionContext.getRequiredTestClass(); AnnotationSupport.findAnnotation(testClass, LoggerContextSource.class).ifPresent(testSource -> { final LoggerContextHolder holder = new LoggerContextHolder(testSource, extensionContext); ExtensionContextAnchor.setAttribute(KEY, holder, extensionContext); }); final LoggerContextHolder holder = ExtensionContextAnchor.getAttribute(KEY, LoggerContextHolder.class, extensionContext); if (holder != null) { ReflectionSupport.findFields( extensionContext.getRequiredTestClass(), f -> ModifierSupport.isStatic(f) && f.getType().equals(LoggerContext.class), HierarchyTraversalMode.TOP_DOWN) .forEach(f -> { try { f.setAccessible(true); f.set(null, holder.getLoggerContext()); } catch (ReflectiveOperationException e) { throw new ExtensionContextException("Failed to inject field " + f, e); } }); } } @Override public LoggerContext resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return ExtensionContextAnchor.getAttribute(KEY, LoggerContextHolder.class, extensionContext) .getLoggerContext(); } static final
LoggerContextResolver
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/slots/ResourceRequirements.java
{ "start": 1193, "end": 3460 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; private final JobID jobId; private final String targetAddress; private final Collection<ResourceRequirement> resourceRequirements; private ResourceRequirements( JobID jobId, String targetAddress, Collection<ResourceRequirement> resourceRequirements) { this.jobId = Preconditions.checkNotNull(jobId); this.targetAddress = Preconditions.checkNotNull(targetAddress); this.resourceRequirements = Preconditions.checkNotNull(resourceRequirements); } public JobID getJobId() { return jobId; } public String getTargetAddress() { return targetAddress; } public Collection<ResourceRequirement> getResourceRequirements() { return resourceRequirements; } public static ResourceRequirements create( JobID jobId, String targetAddress, Collection<ResourceRequirement> resourceRequirements) { return new ResourceRequirements(jobId, targetAddress, resourceRequirements); } public static ResourceRequirements empty(JobID jobId, String targetAddress) { return new ResourceRequirements(jobId, targetAddress, Collections.emptyList()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ResourceRequirements that = (ResourceRequirements) o; return Objects.equals(jobId, that.jobId) && Objects.equals(targetAddress, that.targetAddress) && Objects.equals(resourceRequirements, that.resourceRequirements); } @Override public int hashCode() { return Objects.hash(jobId, targetAddress, resourceRequirements); } @Override public String toString() { return "ResourceRequirements{" + "jobId=" + jobId + ", targetAddress='" + targetAddress + '\'' + ", resourceRequirements=" + resourceRequirements + '}'; } }
ResourceRequirements
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/BigIntegerMappingTests.java
{ "start": 2574, "end": 2924 }
class ____ { @Id Integer id; //tag::basic-biginteger-example-implicit[] // will be mapped using NUMERIC BigInteger wrapper; //end::basic-biginteger-example-implicit[] public EntityOfBigIntegers() { } public EntityOfBigIntegers(Integer id, BigInteger wrapper) { this.id = id; this.wrapper = wrapper; } } }
EntityOfBigIntegers
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/authentication/ProviderManager.java
{ "start": 4518, "end": 12854 }
class ____ implements AuthenticationManager, MessageSourceAware, InitializingBean { private static final Log logger = LogFactory.getLog(ProviderManager.class); private AuthenticationEventPublisher eventPublisher = new NullEventPublisher(); private List<AuthenticationProvider> providers = Collections.emptyList(); protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private @Nullable AuthenticationManager parent; private boolean eraseCredentialsAfterAuthentication = true; /** * Construct a {@link ProviderManager} using the given {@link AuthenticationProvider}s * @param providers the {@link AuthenticationProvider}s to use */ public ProviderManager(AuthenticationProvider... providers) { this(Arrays.asList(providers), null); } /** * Construct a {@link ProviderManager} using the given {@link AuthenticationProvider}s * @param providers the {@link AuthenticationProvider}s to use */ public ProviderManager(List<AuthenticationProvider> providers) { this(providers, null); } /** * Construct a {@link ProviderManager} using the provided parameters * @param providers the {@link AuthenticationProvider}s to use * @param parent a parent {@link AuthenticationManager} to fall back to */ public ProviderManager(List<AuthenticationProvider> providers, @Nullable AuthenticationManager parent) { Assert.notNull(providers, "providers list cannot be null"); this.providers = providers; this.parent = parent; checkState(); } @Override public void afterPropertiesSet() { checkState(); } private void checkState() { Assert.isTrue(this.parent != null || !this.providers.isEmpty(), "A parent AuthenticationManager or a list of AuthenticationProviders is required"); Assert.isTrue(!CollectionUtils.contains(this.providers.iterator(), null), "providers list cannot contain null values"); } /** * Attempts to authenticate the passed {@link Authentication} object. * <p> * The list of {@link AuthenticationProvider}s will be successively tried until an * <code>AuthenticationProvider</code> indicates it is capable of authenticating the * type of <code>Authentication</code> object passed. Authentication will then be * attempted with that <code>AuthenticationProvider</code>. * <p> * If more than one <code>AuthenticationProvider</code> supports the passed * <code>Authentication</code> object, the first one able to successfully authenticate * the <code>Authentication</code> object determines the <code>result</code>, * overriding any possible <code>AuthenticationException</code> thrown by earlier * supporting <code>AuthenticationProvider</code>s. On successful authentication, no * subsequent <code>AuthenticationProvider</code>s will be tried. If authentication * was not successful by any supporting <code>AuthenticationProvider</code> the last * thrown <code>AuthenticationException</code> will be rethrown. * @param authentication the authentication request object. * @return a fully authenticated object including credentials. * @throws AuthenticationException if authentication fails. */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Class<? extends Authentication> toTest = authentication.getClass(); AuthenticationException lastException = null; AuthenticationException parentException = null; Authentication result = null; Authentication parentResult = null; int currentPosition = 0; int size = this.providers.size(); for (AuthenticationProvider provider : getProviders()) { if (!provider.supports(toTest)) { continue; } if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Authenticating request with %s (%d/%d)", provider.getClass().getSimpleName(), ++currentPosition, size)); } try { result = provider.authenticate(authentication); if (result != null) { copyDetails(authentication, result); break; } } catch (AccountStatusException ex) { prepareException(ex, authentication); logger.debug(LogMessage.format("Authentication failed for user '%s' since their account status is %s", authentication.getName(), ex.getMessage()), ex); // SEC-546: Avoid polling additional providers if auth failure is due to // invalid account status throw ex; } catch (InternalAuthenticationServiceException ex) { prepareException(ex, authentication); logger.debug(LogMessage.format("Authentication service failed internally for user '%s'", authentication.getName()), ex); // SEC-546: Avoid polling additional providers if auth failure is due to // invalid account status throw ex; } catch (AuthenticationException ex) { ex.setAuthenticationRequest(authentication); logger.debug(LogMessage.format("Authentication failed with provider %s since %s", provider.getClass().getSimpleName(), ex.getMessage())); lastException = ex; } } if (result == null && this.parent != null) { // Allow the parent to try. try { parentResult = this.parent.authenticate(authentication); result = parentResult; } catch (ProviderNotFoundException ex) { // ignore as we will throw below if no other exception occurred prior to // calling parent and the parent // may throw ProviderNotFound even though a provider in the child already // handled the request } catch (AuthenticationException ex) { parentException = ex; lastException = ex; } } if (result != null) { if (this.eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) { // Authentication is complete. Remove credentials and other secret data // from authentication ((CredentialsContainer) result).eraseCredentials(); } // If the parent AuthenticationManager was attempted and successful then it // will publish an AuthenticationSuccessEvent // This check prevents a duplicate AuthenticationSuccessEvent if the parent // AuthenticationManager already published it if (parentResult == null) { this.eventPublisher.publishAuthenticationSuccess(result); } return result; } // Parent was null, or didn't authenticate (or throw an exception). if (lastException == null) { lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound", new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}")); } // If the parent AuthenticationManager was attempted and failed then it will // publish an AbstractAuthenticationFailureEvent // This check prevents a duplicate AbstractAuthenticationFailureEvent if the // parent AuthenticationManager already published it if (parentException == null) { prepareException(lastException, authentication); } // Ensure this message is not logged when authentication is attempted by // the parent provider if (this.parent != null) { logger.debug("Denying authentication since all attempted providers failed"); } throw lastException; } @SuppressWarnings("deprecation") private void prepareException(AuthenticationException ex, Authentication auth) { ex.setAuthenticationRequest(auth); this.eventPublisher.publishAuthenticationFailure(ex, auth); } /** * Copies the authentication details from a source Authentication object to a * destination one, provided the latter does not already have one set. * @param source source authentication * @param dest the destination authentication object */ private void copyDetails(Authentication source, Authentication dest) { if ((dest instanceof AbstractAuthenticationToken token) && (dest.getDetails() == null)) { token.setDetails(source.getDetails()); } } public List<AuthenticationProvider> getProviders() { return this.providers; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } public void setAuthenticationEventPublisher(AuthenticationEventPublisher eventPublisher) { Assert.notNull(eventPublisher, "AuthenticationEventPublisher cannot be null"); this.eventPublisher = eventPublisher; } /** * If set to, a resulting {@code Authentication} which implements the * {@code CredentialsContainer}
ProviderManager
java
google__error-prone
check_api/src/main/java/com/google/errorprone/matchers/FieldMatchers.java
{ "start": 1139, "end": 1432 }
interface ____ MethodMatchers. // Ex: [staticField()|instanceField()] // .[onClass(String)|onAnyClass|onClassMatching] // .[named(String)|withAnyName|withNameMatching] /** Static utility methods for creating {@link Matcher}s for detecting references to fields. */ public final
like
java
alibaba__nacos
common/src/main/java/com/alibaba/nacos/common/model/RestResult.java
{ "start": 870, "end": 2166 }
class ____<T> implements Serializable { private static final long serialVersionUID = 6095433538316185017L; private int code; private String message; private T data; public RestResult() { } public RestResult(int code, String message, T data) { this.code = code; this.setMessage(message); this.data = data; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } public boolean ok() { return this.code == 0 || this.code == 200; } public boolean isNoRight() { return this.code == 403 || this.code == 401; } @Override public String toString() { return "RestResult{" + "code=" + code + ", message='" + message + '\'' + ", data=" + data + '}'; } public static <T> ResResultBuilder<T> builder() { return new ResResultBuilder<>(); } public static final
RestResult
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/EnumerationCustomTypeTest.java
{ "start": 537, "end": 920 }
class ____ { @Test public void test(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { Person person = new Person(); person.setId(1L); person.setName("John Doe"); person.setGender(Gender.MALE); entityManager.persist(person); }); } //tag::basic-enums-custom-type-example[] @Entity(name = "Person") public static
EnumerationCustomTypeTest
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/dataframe/analyses/RegressionTests.java
{ "start": 2454, "end": 19181 }
class ____ extends AbstractBWCSerializationTestCase<Regression> { private static final BoostedTreeParams BOOSTED_TREE_PARAMS = BoostedTreeParams.builder().build(); @Override protected Regression doParseInstance(XContentParser parser) throws IOException { return Regression.fromXContent(parser, false); } @Override protected Regression createTestInstance() { return createRandom(); } @Override protected Regression mutateInstance(Regression instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected NamedXContentRegistry xContentRegistry() { List<NamedXContentRegistry.Entry> namedXContent = new ArrayList<>(); namedXContent.addAll(new MlInferenceNamedXContentProvider().getNamedXContentParsers()); namedXContent.addAll(new SearchModule(Settings.EMPTY, Collections.emptyList()).getNamedXContents()); return new NamedXContentRegistry(namedXContent); } @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { List<NamedWriteableRegistry.Entry> entries = new ArrayList<>(); entries.addAll(new MlInferenceNamedXContentProvider().getNamedWriteables()); return new NamedWriteableRegistry(entries); } public static Regression createRandom() { return createRandom(BoostedTreeParamsTests.createRandom()); } private static Regression createRandom(BoostedTreeParams boostedTreeParams) { String dependentVariableName = randomAlphaOfLength(10); String predictionFieldName = randomBoolean() ? null : randomAlphaOfLength(10); Double trainingPercent = randomBoolean() ? null : randomDoubleBetween(0.0, 100.0, false); Long randomizeSeed = randomBoolean() ? null : randomLong(); Regression.LossFunction lossFunction = randomBoolean() ? null : randomFrom(Regression.LossFunction.values()); Double lossFunctionParameter = randomBoolean() ? null : randomDoubleBetween(0.0, Double.MAX_VALUE, false); Boolean earlyStoppingEnabled = randomBoolean() ? null : randomBoolean(); return new Regression( dependentVariableName, boostedTreeParams, predictionFieldName, trainingPercent, randomizeSeed, lossFunction, lossFunctionParameter, randomBoolean() ? null : Stream.generate( () -> randomFrom( FrequencyEncodingTests.createRandom(true), OneHotEncodingTests.createRandom(true), TargetMeanEncodingTests.createRandom(true) ) ).limit(randomIntBetween(0, 5)).collect(Collectors.toList()), earlyStoppingEnabled ); } public static Regression mutateForVersion(Regression instance, TransportVersion version) { return new Regression( instance.getDependentVariable(), BoostedTreeParamsTests.mutateForVersion(instance.getBoostedTreeParams(), version), instance.getPredictionFieldName(), instance.getTrainingPercent(), instance.getRandomizeSeed(), instance.getLossFunction(), instance.getLossFunctionParameter(), instance.getFeatureProcessors(), instance.getEarlyStoppingEnabled() ); } @Override protected Regression mutateInstanceForVersion(Regression instance, TransportVersion version) { return mutateForVersion(instance, version); } @Override protected Writeable.Reader<Regression> instanceReader() { return Regression::new; } public void testDeserialization() throws IOException { String toDeserialize = """ { "dependent_variable": "FlightDelayMin", "feature_processors": [ { "one_hot_encoding": { "field": "OriginWeather", "hot_map": { "sunny_col": "Sunny", "clear_col": "Clear", "rainy_col": "Rain" } } }, { "one_hot_encoding": { "field": "DestWeather", "hot_map": { "dest_sunny_col": "Sunny", "dest_clear_col": "Clear", "dest_rainy_col": "Rain" } } }, { "frequency_encoding": { "field": "OriginWeather", "feature_name": "mean", "frequency_map": { "Sunny": 0.8, "Rain": 0.2 } } } ] }"""; try ( XContentParser parser = XContentHelper.createParser( xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new BytesArray(toDeserialize), XContentType.JSON ) ) { Regression parsed = Regression.fromXContent(parser, false); assertThat(parsed.getDependentVariable(), equalTo("FlightDelayMin")); for (PreProcessor preProcessor : parsed.getFeatureProcessors()) { assertThat(preProcessor.isCustom(), is(true)); } } } public void testConstructor_GivenTrainingPercentIsZero() { ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> new Regression("foo", BOOSTED_TREE_PARAMS, "result", 0.0, randomLong(), Regression.LossFunction.MSE, null, null, null) ); assertThat(e.getMessage(), equalTo("[training_percent] must be a positive double in (0, 100]")); } public void testConstructor_GivenTrainingPercentIsLessThanZero() { ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> new Regression("foo", BOOSTED_TREE_PARAMS, "result", -0.01, randomLong(), Regression.LossFunction.MSE, null, null, null) ); assertThat(e.getMessage(), equalTo("[training_percent] must be a positive double in (0, 100]")); } public void testConstructor_GivenTrainingPercentIsGreaterThan100() { ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> new Regression( "foo", BOOSTED_TREE_PARAMS, "result", 100.0001, randomLong(), Regression.LossFunction.MSE, null, null, null ) ); assertThat(e.getMessage(), equalTo("[training_percent] must be a positive double in (0, 100]")); } public void testConstructor_GivenLossFunctionParameterIsZero() { ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> new Regression("foo", BOOSTED_TREE_PARAMS, "result", 100.0, randomLong(), Regression.LossFunction.MSE, 0.0, null, null) ); assertThat(e.getMessage(), equalTo("[loss_function_parameter] must be a positive double")); } public void testConstructor_GivenLossFunctionParameterIsNegative() { ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> new Regression("foo", BOOSTED_TREE_PARAMS, "result", 100.0, randomLong(), Regression.LossFunction.MSE, -1.0, null, null) ); assertThat(e.getMessage(), equalTo("[loss_function_parameter] must be a positive double")); } public void testGetPredictionFieldName() { Regression regression = new Regression( "foo", BOOSTED_TREE_PARAMS, "result", 50.0, randomLong(), Regression.LossFunction.MSE, 1.0, null, null ); assertThat(regression.getPredictionFieldName(), equalTo("result")); regression = new Regression("foo", BOOSTED_TREE_PARAMS, null, 50.0, randomLong(), Regression.LossFunction.MSE, null, null, null); assertThat(regression.getPredictionFieldName(), equalTo("foo_prediction")); } public void testGetTrainingPercent() { Regression regression = new Regression( "foo", BOOSTED_TREE_PARAMS, "result", 50.0, randomLong(), Regression.LossFunction.MSE, 1.0, null, null ); assertThat(regression.getTrainingPercent(), equalTo(50.0)); // Boundary condition: training_percent == 1.0 regression = new Regression("foo", BOOSTED_TREE_PARAMS, "result", 1.0, randomLong(), Regression.LossFunction.MSE, null, null, null); assertThat(regression.getTrainingPercent(), equalTo(1.0)); // Boundary condition: training_percent == 100.0 regression = new Regression( "foo", BOOSTED_TREE_PARAMS, "result", 100.0, randomLong(), Regression.LossFunction.MSE, null, null, null ); assertThat(regression.getTrainingPercent(), equalTo(100.0)); // training_percent == null, default applied regression = new Regression( "foo", BOOSTED_TREE_PARAMS, "result", null, randomLong(), Regression.LossFunction.MSE, null, null, null ); assertThat(regression.getTrainingPercent(), equalTo(100.0)); } public void testGetParams_ShouldIncludeBoostedTreeParams() { int maxTrees = randomIntBetween(1, 100); Regression regression = new Regression( "foo", BoostedTreeParams.builder().setMaxTrees(maxTrees).build(), null, 100.0, 0L, Regression.LossFunction.MSE, null, null, null ); Map<String, Object> params = regression.getParams(null); assertThat(params.size(), equalTo(7)); assertThat(params.get("dependent_variable"), equalTo("foo")); assertThat(params.get("prediction_field_name"), equalTo("foo_prediction")); assertThat(params.get("max_trees"), equalTo(maxTrees)); assertThat(params.get("training_percent"), equalTo(100.0)); assertThat(params.get("loss_function"), equalTo("mse")); assertThat(params.get("early_stopping_enabled"), equalTo(true)); assertThat(params.get("randomize_seed"), equalTo(0L)); } public void testGetParams_GivenRandomWithoutBoostedTreeParams() { Regression regression = createRandom(BoostedTreeParams.builder().build()); Map<String, Object> params = regression.getParams(null); int expectedParamsCount = 6 + (regression.getLossFunctionParameter() == null ? 0 : 1) + (regression.getFeatureProcessors().isEmpty() ? 0 : 1); assertThat(params.size(), equalTo(expectedParamsCount)); assertThat(params.get("dependent_variable"), equalTo(regression.getDependentVariable())); assertThat(params.get("prediction_field_name"), equalTo(regression.getPredictionFieldName())); assertThat(params.get("training_percent"), equalTo(regression.getTrainingPercent())); assertThat(params.get("loss_function"), equalTo(regression.getLossFunction().toString())); if (regression.getLossFunctionParameter() == null) { assertThat(params.containsKey("loss_function_parameter"), is(false)); } else { assertThat(params.get("loss_function_parameter"), equalTo(regression.getLossFunctionParameter())); } assertThat(params.get("early_stopping_enabled"), equalTo(regression.getEarlyStoppingEnabled())); assertThat(params.get("randomize_seed"), equalTo(regression.getRandomizeSeed())); } public void testRequiredFieldsIsNonEmpty() { assertThat(createTestInstance().getRequiredFields(), is(not(empty()))); } public void testFieldCardinalityLimitsIsEmpty() { assertThat(createTestInstance().getFieldCardinalityConstraints(), is(empty())); } public void testGetResultMappings() { Map<String, Object> resultMappings = new Regression("foo").getResultMappings("results", null); assertThat(resultMappings, hasEntry("results.foo_prediction", Collections.singletonMap("type", "double"))); assertThat(resultMappings, hasEntry("results.feature_importance", Regression.FEATURE_IMPORTANCE_MAPPING)); assertThat(resultMappings, hasEntry("results.is_training", Collections.singletonMap("type", "boolean"))); } public void testGetStateDocId() { Regression regression = createRandom(); assertThat(regression.persistsState(), is(true)); String randomId = randomAlphaOfLength(10); assertThat(regression.getStateDocIdPrefix(randomId), equalTo(randomId + "_regression_state#")); } public void testExtractJobIdFromStateDoc() { assertThat(Regression.extractJobIdFromStateDoc("foo_bar-1_regression_state#1"), equalTo("foo_bar-1")); assertThat(Regression.extractJobIdFromStateDoc("noop"), is(nullValue())); } public void testToXContent_GivenVersionBeforeRandomizeSeedWasIntroduced() throws IOException { Regression regression = createRandom(); assertThat(regression.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { regression.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("version", "7.5.0"))); String json = Strings.toString(builder); assertThat(json, not(containsString("randomize_seed"))); } } public void testToXContent_GivenVersionAfterRandomizeSeedWasIntroduced() throws IOException { Regression regression = createRandom(); assertThat(regression.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { regression.toXContent( builder, new ToXContent.MapParams(Collections.singletonMap("version", MlConfigVersion.CURRENT.toString())) ); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testToXContent_GivenVersionIsNull() throws IOException { Regression regression = createRandom(); assertThat(regression.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { regression.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("version", null))); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testToXContent_GivenEmptyParams() throws IOException { Regression regression = createRandom(); assertThat(regression.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { regression.toXContent(builder, ToXContent.EMPTY_PARAMS); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testInferenceConfig() { Regression regression = createRandom(); InferenceConfig inferenceConfig = regression.inferenceConfig(null); assertThat(inferenceConfig, instanceOf(RegressionConfig.class)); RegressionConfig regressionConfig = (RegressionConfig) inferenceConfig; assertThat(regressionConfig.getResultsField(), equalTo(regression.getPredictionFieldName())); Integer expectedNumTopFeatureImportanceValues = regression.getBoostedTreeParams().getNumTopFeatureImportanceValues() == null ? 0 : regression.getBoostedTreeParams().getNumTopFeatureImportanceValues(); assertThat(regressionConfig.getNumTopFeatureImportanceValues(), equalTo(expectedNumTopFeatureImportanceValues)); } }
RegressionTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitchTest.java
{ "start": 28933, "end": 29304 }
enum ____ { ONE, TWO } void m(Case c) { switch (c) { case ONE -> {} case TWO -> {} default -> {} } } } """) .addOutputLines( "Test.java", """
Case
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/FilterChainMatchingProtocolNegotiators.java
{ "start": 16463, "end": 16969 }
class ____ implements InternalProtocolNegotiator.ServerFactory { private final InternalProtocolNegotiator.ServerFactory delegate; public FilterChainMatchingNegotiatorServerFactory( InternalProtocolNegotiator.ServerFactory delegate) { this.delegate = checkNotNull(delegate, "delegate"); } @Override public ProtocolNegotiator newNegotiator( final ObjectPool<? extends Executor> offloadExecutorPool) {
FilterChainMatchingNegotiatorServerFactory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/scanning/JarVisitorTest.java
{ "start": 3079, "end": 14043 }
class ____ implements ScanEnvironment { private final URL rootUrl; private ScanEnvironmentImpl(URL rootUrl) { this.rootUrl = rootUrl; } @Override public URL getRootUrl() { return rootUrl; } @Override public List<URL> getNonRootUrls() { return Collections.emptyList(); } @Override public List<String> getExplicitlyListedClassNames() { return Collections.emptyList(); } @Override public List<String> getExplicitlyListedMappingFiles() { return Collections.emptyList(); } } @Test public void testInputStreamZippedJar() throws Exception { File defaultPar = buildDefaultPar(); addPackageToClasspath( defaultPar ); ScanResult result = standardScan( defaultPar.toURL() ); validateResults( result, org.hibernate.orm.test.jpa.pack.defaultpar.ApplicationServer.class, Version.class ); } private void validateResults(ScanResult scanResult, Class... expectedClasses) throws IOException { assertEquals( 3, scanResult.getLocatedClasses().size() ); for ( Class expectedClass : expectedClasses ) { assertTrue( scanResult.getLocatedClasses().contains( new ClassDescriptorImpl( expectedClass.getName(), ClassDescriptor.Categorization.MODEL, null ) ) ); } assertEquals( 2, scanResult.getLocatedMappingFiles().size() ); for ( MappingFileDescriptor mappingFileDescriptor : scanResult.getLocatedMappingFiles() ) { assertNotNull( mappingFileDescriptor.getStreamAccess() ); final InputStream stream = mappingFileDescriptor.getStreamAccess().accessInputStream(); assertNotNull( stream ); stream.close(); } } @Test public void testNestedJarProtocol() throws Exception { File defaultPar = buildDefaultPar(); File nestedEar = buildNestedEar( defaultPar ); File nestedEarDir = buildNestedEarDir( defaultPar ); addPackageToClasspath( nestedEar ); String jarFileName = nestedEar.toURL().toExternalForm() + "!/defaultpar.par"; URL rootUrl = new URL( jarFileName ); JarProtocolArchiveDescriptor archiveDescriptor = new JarProtocolArchiveDescriptor( StandardArchiveDescriptorFactory.INSTANCE, rootUrl, "" ); ScanEnvironment environment = new ScanEnvironmentImpl( rootUrl ); ScanResultCollector collector = new ScanResultCollector( environment, new StandardScanOptions(), StandardScanParameters.INSTANCE ); archiveDescriptor.visitArchive( new AbstractScannerImpl.ArchiveContextImpl( true, collector ) ); validateResults( collector.toScanResult(), org.hibernate.orm.test.jpa.pack.defaultpar.ApplicationServer.class, Version.class ); jarFileName = nestedEarDir.toURL().toExternalForm() + "!/defaultpar.par"; rootUrl = new URL( jarFileName ); archiveDescriptor = new JarProtocolArchiveDescriptor( StandardArchiveDescriptorFactory.INSTANCE, rootUrl, "" ); environment = new ScanEnvironmentImpl( rootUrl ); collector = new ScanResultCollector( environment, new StandardScanOptions(), StandardScanParameters.INSTANCE ); archiveDescriptor.visitArchive( new AbstractScannerImpl.ArchiveContextImpl( true, collector ) ); validateResults( collector.toScanResult(), org.hibernate.orm.test.jpa.pack.defaultpar.ApplicationServer.class, Version.class ); } @Test public void testJarProtocol() throws Exception { File war = buildWar(); addPackageToClasspath( war ); String jarFileName = war.toURL().toExternalForm() + "!/WEB-INF/classes"; URL rootUrl = new URL( jarFileName ); JarProtocolArchiveDescriptor archiveDescriptor = new JarProtocolArchiveDescriptor( StandardArchiveDescriptorFactory.INSTANCE, rootUrl, "" ); final ScanEnvironment environment = new ScanEnvironmentImpl( rootUrl ); final ScanResultCollector collector = new ScanResultCollector( environment, new StandardScanOptions(), StandardScanParameters.INSTANCE ); archiveDescriptor.visitArchive( new AbstractScannerImpl.ArchiveContextImpl( true, collector ) ); validateResults( collector.toScanResult(), org.hibernate.orm.test.jpa.pack.war.ApplicationServer.class, org.hibernate.orm.test.jpa.pack.war.Version.class ); } @Test public void testZippedJar() throws Exception { File defaultPar = buildDefaultPar(); addPackageToClasspath( defaultPar ); ScanResult result = standardScan( defaultPar.toURL() ); validateResults( result, org.hibernate.orm.test.jpa.pack.defaultpar.ApplicationServer.class, Version.class ); } @Test public void testExplodedJar() throws Exception { File explodedPar = buildExplodedPar(); addPackageToClasspath( explodedPar ); String dirPath = explodedPar.toURL().toExternalForm(); // TODO - shouldn't ExplodedJarVisitor take care of a trailing slash? if ( dirPath.endsWith( "/" ) ) { dirPath = dirPath.substring( 0, dirPath.length() - 1 ); } ScanResult result = standardScan( ArchiveHelper.getURLFromPath( dirPath ) ); assertEquals( 1, result.getLocatedClasses().size() ); assertEquals( 1, result.getLocatedPackages().size() ); assertEquals( 1, result.getLocatedMappingFiles().size() ); assertTrue( result.getLocatedClasses().contains( new ClassDescriptorImpl( Carpet.class.getName(), ClassDescriptor.Categorization.MODEL, null ) ) ); for ( MappingFileDescriptor mappingFileDescriptor : result.getLocatedMappingFiles() ) { assertNotNull( mappingFileDescriptor.getStreamAccess() ); final InputStream stream = mappingFileDescriptor.getStreamAccess().accessInputStream(); assertNotNull( stream ); stream.close(); } } @Test @JiraKey(value = "HHH-6806") public void testJarVisitorFactory() throws Exception { final File explodedPar = buildExplodedPar(); final File defaultPar = buildDefaultPar(); addPackageToClasspath( explodedPar, defaultPar ); //setting URL to accept vfs based protocol URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { public URLStreamHandler createURLStreamHandler(String protocol) { if("vfszip".equals(protocol) || "vfsfile".equals(protocol) ) return new URLStreamHandler() { protected URLConnection openConnection(URL u) throws IOException { return null; } }; return null; } }); URL jarUrl = defaultPar.toURL(); ArchiveDescriptor descriptor = StandardArchiveDescriptorFactory.INSTANCE.buildArchiveDescriptor( jarUrl ); assertEquals( JarFileBasedArchiveDescriptor.class.getName(), descriptor.getClass().getName() ); jarUrl = explodedPar.toURL(); descriptor = StandardArchiveDescriptorFactory.INSTANCE.buildArchiveDescriptor( jarUrl ); assertEquals( ExplodedArchiveDescriptor.class.getName(), descriptor.getClass().getName() ); jarUrl = new URL( defaultPar.toURL().toExternalForm().replace( "file:", "vfszip:" ) ); descriptor = StandardArchiveDescriptorFactory.INSTANCE.buildArchiveDescriptor( jarUrl ); assertEquals( JarFileBasedArchiveDescriptor.class.getName(), descriptor.getClass().getName()); jarUrl = new URL( explodedPar.toURL().toExternalForm().replace( "file:", "vfsfile:" ) ); descriptor = StandardArchiveDescriptorFactory.INSTANCE.buildArchiveDescriptor( jarUrl ); assertEquals( ExplodedArchiveDescriptor.class.getName(), descriptor.getClass().getName() ); } @Test @JiraKey( value = "EJB-230" ) public void testDuplicateFilterExplodedJarExpected() throws Exception { // File explodedPar = buildExplodedPar(); // addPackageToClasspath( explodedPar ); // // Filter[] filters = getFilters(); // Filter[] dupeFilters = new Filter[filters.length * 2]; // int index = 0; // for ( Filter filter : filters ) { // dupeFilters[index++] = filter; // } // filters = getFilters(); // for ( Filter filter : filters ) { // dupeFilters[index++] = filter; // } // String dirPath = explodedPar.toURL().toExternalForm(); // // TODO - shouldn't ExplodedJarVisitor take care of a trailing slash? // if ( dirPath.endsWith( "/" ) ) { // dirPath = dirPath.substring( 0, dirPath.length() - 1 ); // } // JarVisitor jarVisitor = new ExplodedJarVisitor( dirPath, dupeFilters ); // assertEquals( "explodedpar", jarVisitor.getUnqualifiedJarName() ); // Set[] entries = jarVisitor.getMatchingEntries(); // assertEquals( 1, entries[1].size() ); // assertEquals( 1, entries[0].size() ); // assertEquals( 1, entries[2].size() ); // for ( Entry entry : ( Set<Entry> ) entries[2] ) { // InputStream is = entry.getInputStream(); // if ( is != null ) { // assertTrue( 0 < is.available() ); // is.close(); // } // } // for ( Entry entry : ( Set<Entry> ) entries[5] ) { // InputStream is = entry.getInputStream(); // if ( is != null ) { // assertTrue( 0 < is.available() ); // is.close(); // } // } // // Entry entry = new Entry( Carpet.class.getName(), null ); // assertTrue( entries[1].contains( entry ) ); } @Test @JiraKey(value = "HHH-7835") public void testGetBytesFromInputStream() throws Exception { File file = buildLargeJar(); long start = System.currentTimeMillis(); InputStream stream = new BufferedInputStream( new FileInputStream( file ) ); int oldLength = getBytesFromInputStream( stream ).length; stream.close(); long oldTime = System.currentTimeMillis() - start; start = System.currentTimeMillis(); stream = new BufferedInputStream( new FileInputStream( file ) ); int newLength = ArchiveHelper.getBytesFromInputStream( stream ).length; stream.close(); long newTime = System.currentTimeMillis() - start; assertEquals( oldLength, newLength ); System.out.printf( "InputStream byte[] extraction algorithms; old = `%s`, new = `%s`", oldTime, newTime ); } // This is the old getBytesFromInputStream from JarVisitorFactory before // it was changed by HHH-7835. Use it as a regression test. private byte[] getBytesFromInputStream(InputStream inputStream) throws IOException { int size; byte[] entryBytes = new byte[0]; for ( ;; ) { byte[] tmpByte = new byte[4096]; size = inputStream.read( tmpByte ); if ( size == -1 ) break; byte[] current = new byte[entryBytes.length + size]; System.arraycopy( entryBytes, 0, current, 0, entryBytes.length ); System.arraycopy( tmpByte, 0, current, entryBytes.length, size ); entryBytes = current; } return entryBytes; } @Test @JiraKey(value = "HHH-7835") public void testGetBytesFromZeroInputStream() throws Exception { // Ensure that JarVisitorFactory#getBytesFromInputStream // can handle 0 length streams gracefully. URL emptyTxtUrl = getClass().getResource( "/org/hibernate/jpa/test/packaging/empty.txt" ); if ( emptyTxtUrl == null ) { throw new RuntimeException( "Bah!" ); } InputStream emptyStream = new BufferedInputStream( emptyTxtUrl.openStream() ); int length = ArchiveHelper.getBytesFromInputStream( emptyStream ).length; assertEquals( length, 0 ); emptyStream.close(); } }
ScanEnvironmentImpl
java
google__guice
core/test/com/google/inject/ProvisionListenerTest.java
{ "start": 28779, "end": 28864 }
class ____ { @SuppressWarnings("unused") @Inject F f; } private static
E
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/dynamicmap/CustomEntityNameResolverTest.java
{ "start": 1423, "end": 2451 }
class ____ implements SessionFactoryProducer { @AfterEach void dropTestData(SessionFactoryScope factoryScope) { factoryScope.dropData(); } @Test public void test(SessionFactoryScope factoryScope) { // Persist the dynamic map entity factoryScope.inTransaction( (session) -> { final Map<String, Object> artistEntity = new HashMap<>(); artistEntity.put( "id", 1 ); artistEntity.put( "name", "John Doe" ); session.persist( artistEntity ); } ); factoryScope.inTransaction( (session) -> { //noinspection unchecked final Map<String, Object> loaded = (Map<String, Object>) session.byId( "artist" ).load( 1 ); assertThat( loaded ).isNotNull(); assertThat( loaded.get( "$type$" ) ).isEqualTo( "artist" ); } ); } @Override public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { return (SessionFactoryImplementor) model.getSessionFactoryBuilder() .addEntityNameResolver( new HibernateEntityNameResolver() ) .build(); } static
CustomEntityNameResolverTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/param/MySqlParameterizedOutputVisitorTest_59_multiupdate.java
{ "start": 331, "end": 986 }
class ____ extends TestCase { final DbType dbType = JdbcConstants.MYSQL; public void test_for_parameterize() throws Exception { String sql = "update t_order set salary = 101 where id = 101;update t_order set salary = 102 where id = 102"; List<Object> params = new ArrayList<Object>(); String psql = ParameterizedOutputVisitorUtils.parameterize(sql, dbType, params); assertEquals("UPDATE t_order\n" + "SET salary = ?\n" + "WHERE id = ?;", psql); assertEquals(2, params.size()); assertEquals(101, params.get(0)); } }
MySqlParameterizedOutputVisitorTest_59_multiupdate
java
apache__rocketmq
example/src/main/java/org/apache/rocketmq/example/benchmark/TransactionProducer.java
{ "start": 20469, "end": 20732 }
class ____<K, V> extends LinkedHashMap<K, V> { private int maxSize; public LRUMap(int maxSize) { this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > maxSize; } }
LRUMap
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/TestDockerStopCommand.java
{ "start": 1185, "end": 2166 }
class ____ { private DockerStopCommand dockerStopCommand; private static final int GRACE_PERIOD = 10; private static final String CONTAINER_NAME = "foo"; @BeforeEach public void setup() { dockerStopCommand = new DockerStopCommand(CONTAINER_NAME); } @Test public void testGetCommandOption() { assertEquals("stop", dockerStopCommand.getCommandOption()); } @Test public void testSetGracePeriod() throws Exception { dockerStopCommand.setGracePeriod(GRACE_PERIOD); assertEquals("stop", StringUtils.join(",", dockerStopCommand.getDockerCommandWithArguments() .get("docker-command"))); assertEquals("foo", StringUtils.join(",", dockerStopCommand.getDockerCommandWithArguments().get("name"))); assertEquals("10", StringUtils.join(",", dockerStopCommand.getDockerCommandWithArguments().get("time"))); assertEquals(3, dockerStopCommand.getDockerCommandWithArguments().size()); } }
TestDockerStopCommand
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/repositories/blobstore/ChunkedBlobOutputStreamTests.java
{ "start": 1178, "end": 6136 }
class ____ extends ESTestCase { private BigArrays bigArrays; @Override public void setUp() throws Exception { bigArrays = new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), new NoneCircuitBreakerService()); super.setUp(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testSuccessfulChunkedWrite() throws IOException { final long chunkSize = randomLongBetween(10, 1024); final CRC32 checksumIn = new CRC32(); final CRC32 checksumOut = new CRC32(); final CheckedOutputStream out = new CheckedOutputStream(OutputStream.nullOutputStream(), checksumOut); final AtomicLong writtenBytesCounter = new AtomicLong(0L); final long bytesToWrite = randomLongBetween(chunkSize - 5, 1000 * chunkSize); long written = 0; try (ChunkedBlobOutputStream<Integer> stream = new ChunkedBlobOutputStream<>(bigArrays, chunkSize) { private final AtomicInteger partIdSupplier = new AtomicInteger(); @Override protected void flushBuffer() throws IOException { final BytesReference bytes = buffer.bytes(); bytes.writeTo(out); writtenBytesCounter.addAndGet(bytes.length()); finishPart(partIdSupplier.incrementAndGet()); } @Override protected void onCompletion() throws IOException { if (buffer.size() > 0) { flushBuffer(); } out.flush(); for (int i = 0; i < partIdSupplier.get(); i++) { assertEquals((long) i + 1, (long) parts.get(i)); } } @Override protected void onFailure() { fail("not supposed to fail"); } }) { final byte[] buffer = new byte[randomInt(Math.toIntExact(2 * chunkSize)) + 1]; while (written < bytesToWrite) { if (randomBoolean()) { random().nextBytes(buffer); final int offset = randomInt(buffer.length - 1); final int length = Math.toIntExact(Math.min(bytesToWrite - written, buffer.length - offset)); stream.write(buffer, offset, length); checksumIn.update(buffer, offset, length); written += length; } else { int oneByte = randomByte(); stream.write(oneByte); checksumIn.update(oneByte); written++; } } stream.markSuccess(); } assertEquals(bytesToWrite, written); assertEquals(bytesToWrite, writtenBytesCounter.get()); assertEquals(checksumIn.getValue(), checksumOut.getValue()); } public void testExceptionDuringChunkedWrite() throws IOException { final long chunkSize = randomLongBetween(10, 1024); final AtomicLong writtenBytesCounter = new AtomicLong(0L); final long bytesToWrite = randomLongBetween(chunkSize - 5, 1000 * chunkSize); long written = 0; final AtomicBoolean onFailureCalled = new AtomicBoolean(false); try (ChunkedBlobOutputStream<Integer> stream = new ChunkedBlobOutputStream<>(bigArrays, chunkSize) { private final AtomicInteger partIdSupplier = new AtomicInteger(); @Override protected void flushBuffer() { writtenBytesCounter.addAndGet(buffer.size()); finishPart(partIdSupplier.incrementAndGet()); } @Override protected void onCompletion() { fail("supposed to fail"); } @Override protected void onFailure() { for (int i = 0; i < partIdSupplier.get(); i++) { assertEquals((long) i + 1, (long) parts.get(i)); } assertTrue(onFailureCalled.compareAndSet(false, true)); } }) { final byte[] buffer = new byte[randomInt(Math.toIntExact(2 * chunkSize)) + 1]; while (written < bytesToWrite) { if (rarely()) { break; } else if (randomBoolean()) { random().nextBytes(buffer); final int offset = randomInt(buffer.length - 1); final int length = Math.toIntExact(Math.min(bytesToWrite - written, buffer.length - offset)); stream.write(buffer, offset, length); written += length; } else { int oneByte = randomByte(); stream.write(oneByte); written++; } } } assertTrue(onFailureCalled.get()); } }
ChunkedBlobOutputStreamTests
java
apache__flink
flink-test-utils-parent/flink-connector-test-utils/src/main/java/org/apache/flink/connector/testframe/utils/CollectIteratorAssertions.java
{ "start": 984, "end": 1031 }
class ____ * a static factory. */ public final
is
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/metadata/ShutdownPluginsStatus.java
{ "start": 859, "end": 2289 }
class ____ implements Writeable, ToXContentObject { private final SingleNodeShutdownMetadata.Status status; public ShutdownPluginsStatus(boolean safeToShutdown) { this.status = safeToShutdown ? SingleNodeShutdownMetadata.Status.COMPLETE : SingleNodeShutdownMetadata.Status.IN_PROGRESS; } public ShutdownPluginsStatus(StreamInput in) throws IOException { this.status = in.readEnum(SingleNodeShutdownMetadata.Status.class); } public SingleNodeShutdownMetadata.Status getStatus() { return this.status; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("status", status); builder.endObject(); return builder; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeEnum(this.status); } @Override public int hashCode() { return status.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ShutdownPluginsStatus other = (ShutdownPluginsStatus) obj; return status.equals(other.status); } @Override public String toString() { return Strings.toString(this); } }
ShutdownPluginsStatus
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/ResourceReferenceProvider.java
{ "start": 219, "end": 479 }
interface ____ { /** * A resource reference handle is a dependent object of the object it is injected into. {@link InstanceHandle#destroy()} is * called when the target object is * destroyed. * * <pre> *
ResourceReferenceProvider
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/PostRemoveJpaAnnotation.java
{ "start": 463, "end": 1090 }
class ____ implements PostRemove { /** * Used in creating dynamic annotation instances (e.g. from XML) */ public PostRemoveJpaAnnotation(ModelsContext modelContext) { } /** * Used in creating annotation instances from JDK variant */ public PostRemoveJpaAnnotation(PostRemove annotation, ModelsContext modelContext) { } /** * Used in creating annotation instances from Jandex variant */ public PostRemoveJpaAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) { } @Override public Class<? extends Annotation> annotationType() { return PostRemove.class; } }
PostRemoveJpaAnnotation
java
apache__logging-log4j2
log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/resolver/CounterResolverTest.java
{ "start": 1488, "end": 5356 }
class ____ { @Test void no_arg_setup_should_start_from_zero() { final String eventTemplate = writeJson(asMap("$resolver", "counter")); verify(eventTemplate, 0, 1); } @Test void positive_start_should_work() { final String eventTemplate = writeJson(asMap("$resolver", "counter", "start", 3)); verify(eventTemplate, 3, 4); } @Test void positive_start_should_work_when_stringified() { final String eventTemplate = writeJson(asMap("$resolver", "counter", "start", 3, "stringified", true)); verify(eventTemplate, "3", "4"); } @Test void negative_start_should_work() { final String eventTemplate = writeJson(asMap("$resolver", "counter", "start", -3)); verify(eventTemplate, -3, -2); } @Test void negative_start_should_work_when_stringified() { final String eventTemplate = writeJson(asMap("$resolver", "counter", "start", -3, "stringified", true)); verify(eventTemplate, "-3", "-2"); } @Test void min_long_should_work_when_overflow_enabled() { final String eventTemplate = writeJson(asMap("$resolver", "counter", "start", Long.MIN_VALUE)); verify(eventTemplate, Long.MIN_VALUE, Long.MIN_VALUE + 1L); } @Test void min_long_should_work_when_overflow_enabled_and_stringified() { final String eventTemplate = writeJson(asMap("$resolver", "counter", "start", Long.MIN_VALUE, "stringified", true)); verify(eventTemplate, "" + Long.MIN_VALUE, "" + (Long.MIN_VALUE + 1L)); } @Test void max_long_should_work_when_overflowing() { final String eventTemplate = writeJson(asMap("$resolver", "counter", "start", Long.MAX_VALUE)); verify(eventTemplate, Long.MAX_VALUE, Long.MIN_VALUE); } @Test void max_long_should_work_when_overflowing_and_stringified() { final String eventTemplate = writeJson(asMap("$resolver", "counter", "start", Long.MAX_VALUE, "stringified", true)); verify(eventTemplate, "" + Long.MAX_VALUE, "" + Long.MIN_VALUE); } @Test void max_long_should_work_when_not_overflowing() { final String eventTemplate = writeJson(asMap("$resolver", "counter", "start", Long.MAX_VALUE, "overflowing", false)); verify(eventTemplate, Long.MAX_VALUE, BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE)); } @Test void max_long_should_work_when_not_overflowing_and_stringified() { final String eventTemplate = writeJson( asMap("$resolver", "counter", "start", Long.MAX_VALUE, "overflowing", false, "stringified", true)); verify( eventTemplate, "" + Long.MAX_VALUE, "" + BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE)); } private static void verify(final String eventTemplate, final Object expectedNumber1, final Object expectedNumber2) { // Create the layout. final JsonTemplateLayout layout = JsonTemplateLayout.newBuilder() .setConfiguration(CONFIGURATION) .setEventTemplate(eventTemplate) .build(); // Create the log event. final LogEvent logEvent = Log4jLogEvent.newBuilder().build(); // Check the 1st serialized event. final String serializedLogEvent1 = layout.toSerializable(logEvent); final Object deserializedLogEvent1 = JsonReader.read(serializedLogEvent1); assertThat(deserializedLogEvent1).isEqualTo(expectedNumber1); // Check the 2nd serialized event. final String serializedLogEvent2 = layout.toSerializable(logEvent); final Object deserializedLogEvent2 = JsonReader.read(serializedLogEvent2); assertThat(deserializedLogEvent2).isEqualTo(expectedNumber2); } }
CounterResolverTest
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/connector/syncjob/action/UpdateConnectorSyncJobErrorActionRequestBWCSerializationTests.java
{ "start": 660, "end": 2604 }
class ____ extends AbstractBWCSerializationTestCase< UpdateConnectorSyncJobErrorAction.Request> { private String connectorSyncJobId; @Override protected Writeable.Reader<UpdateConnectorSyncJobErrorAction.Request> instanceReader() { return UpdateConnectorSyncJobErrorAction.Request::new; } @Override protected UpdateConnectorSyncJobErrorAction.Request createTestInstance() { UpdateConnectorSyncJobErrorAction.Request request = ConnectorSyncJobTestUtils.getRandomUpdateConnectorSyncJobErrorActionRequest(); this.connectorSyncJobId = request.getConnectorSyncJobId(); return request; } @Override protected UpdateConnectorSyncJobErrorAction.Request mutateInstance(UpdateConnectorSyncJobErrorAction.Request instance) throws IOException { String jobId = instance.getConnectorSyncJobId(); String error = instance.getError(); switch (randomIntBetween(0, 1)) { case 0 -> jobId = randomValueOtherThan(jobId, () -> randomAlphaOfLength(10)); case 1 -> error = randomValueOtherThan(error, () -> randomAlphaOfLengthBetween(5, 100)); default -> throw new AssertionError("Illegal randomisation branch"); } return new UpdateConnectorSyncJobErrorAction.Request(jobId, error); } @Override protected UpdateConnectorSyncJobErrorAction.Request doParseInstance(XContentParser parser) throws IOException { return UpdateConnectorSyncJobErrorAction.Request.fromXContent(parser, this.connectorSyncJobId); } @Override protected UpdateConnectorSyncJobErrorAction.Request mutateInstanceForVersion( UpdateConnectorSyncJobErrorAction.Request instance, TransportVersion version ) { return new UpdateConnectorSyncJobErrorAction.Request(instance.getConnectorSyncJobId(), instance.getError()); } }
UpdateConnectorSyncJobErrorActionRequestBWCSerializationTests
java
quarkusio__quarkus
extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/export/JsonRecorder.java
{ "start": 247, "end": 684 }
class ____ { JsonHandler handler; public JsonHandler getHandler() { if (handler == null) { handler = new JsonHandler(); } return handler; } public Consumer<Route> route() { return new Consumer<Route>() { @Override public void accept(Route route) { route.order(3).produces("application/json"); } }; } }
JsonRecorder
java
google__guava
android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java
{ "start": 21226, "end": 21371 }
class ____ { public static final @Nullable WithNullConstant NULL = null; private WithNullConstant() {} } public static
WithNullConstant
java
apache__camel
tooling/camel-tooling-maven/src/main/java/org/apache/camel/tooling/maven/MavenDownloaderImpl.java
{ "start": 76337, "end": 76544 }
class ____ implements DependencyFilter { @Override public boolean accept(DependencyNode node, List<DependencyNode> parents) { return true; } } }
AcceptAllDependencyFilter
java
quarkusio__quarkus
independent-projects/tools/codestarts/src/test/java/io/quarkus/devtools/codestarts/core/strategy/SmartConfigMergeCodestartFileStrategyHandlerTest.java
{ "start": 177, "end": 1979 }
class ____ { @Test void testFlatten() { final HashMap<String, Object> cc = new HashMap<>(); cc.put("c-c-a", 1); cc.put("c-c-b", 2); final HashMap<String, Object> c = new HashMap<>(); c.put("c-a", "1"); c.put("c-b", "2"); c.put("c-c", cc); final HashMap<String, Object> config = new HashMap<>(); config.put("a", "1"); config.put("b", "2"); config.put("c", c); final HashMap<String, String> flat = new HashMap<>(); SmartConfigMergeCodestartFileStrategyHandler.flatten("", flat, config); assertThat(flat).containsEntry("a", "1"); assertThat(flat).containsEntry("b", "2"); assertThat(flat).containsEntry("c.c-a", "1"); assertThat(flat).containsEntry("c.c-b", "2"); assertThat(flat).containsEntry("c.c-c.c-c-a", "1"); assertThat(flat).containsEntry("c.c-c.c-c-b", "2"); } @Test void testLogLevel() { final HashMap<String, Object> level = new HashMap<>(); level.put("level", "DEBUG"); final HashMap<String, Object> categoryName = new HashMap<>(); categoryName.put("org.hibernate", level); final HashMap<String, Object> category = new HashMap<>(); category.put("category", categoryName); final HashMap<String, Object> log = new HashMap<>(); log.put("log", category); final HashMap<String, Object> quarkus = new HashMap<>(); quarkus.put("quarkus", log); final HashMap<String, String> flat = new HashMap<>(); SmartConfigMergeCodestartFileStrategyHandler.flatten("", flat, quarkus); assertThat(flat).containsEntry("quarkus.log.category.\"org.hibernate\".level", "DEBUG"); } }
SmartConfigMergeCodestartFileStrategyHandlerTest
java
quarkusio__quarkus
extensions/oidc/runtime/src/test/java/io/quarkus/oidc/runtime/OidcTenantConfigBuilderTest.java
{ "start": 2591, "end": 78285 }
class ____ { @Test public void testDefaultValues() { var config = OidcTenantConfig.builder().tenantId("default-test").build(); // OidcTenantConfig methods assertTrue(config.tenantId().isPresent()); assertTrue(config.tenantEnabled()); assertTrue(config.applicationType().isEmpty()); assertTrue(config.authorizationPath().isEmpty()); assertTrue(config.userInfoPath().isEmpty()); assertTrue(config.introspectionPath().isEmpty()); assertTrue(config.jwksPath().isEmpty()); assertTrue(config.endSessionPath().isEmpty()); assertTrue(config.tenantPaths().isEmpty()); assertTrue(config.publicKey().isEmpty()); assertTrue(config.allowTokenIntrospectionCache()); assertTrue(config.allowUserInfoCache()); assertTrue(config.cacheUserInfoInIdtoken().isEmpty()); assertTrue(config.provider().isEmpty()); var introspectionCredentials = config.introspectionCredentials(); assertNotNull(introspectionCredentials); assertTrue(introspectionCredentials.name().isEmpty()); assertTrue(introspectionCredentials.secret().isEmpty()); assertTrue(introspectionCredentials.includeClientId()); var roles = config.roles(); assertNotNull(roles); assertTrue(roles.roleClaimPath().isEmpty()); assertTrue(roles.roleClaimSeparator().isEmpty()); assertTrue(roles.source().isEmpty()); var token = config.token(); assertNotNull(token); assertTrue(token.issuer().isEmpty()); assertTrue(token.audience().isEmpty()); assertFalse(token.subjectRequired()); assertTrue(token.requiredClaims().isEmpty()); assertTrue(token.tokenType().isEmpty()); assertTrue(token.lifespanGrace().isEmpty()); assertTrue(token.age().isEmpty()); assertTrue(token.issuedAtRequired()); assertTrue(token.principalClaim().isEmpty()); assertFalse(token.refreshExpired()); assertTrue(token.refreshTokenTimeSkew().isEmpty()); assertEquals(10, token.forcedJwkRefreshInterval().toMinutes()); assertTrue(token.header().isEmpty()); assertEquals(OidcConstants.BEARER_SCHEME, token.authorizationScheme()); assertTrue(token.signatureAlgorithm().isEmpty()); assertTrue(token.decryptionKeyLocation().isEmpty()); assertTrue(token.allowJwtIntrospection()); assertFalse(token.requireJwtIntrospectionOnly()); assertTrue(token.allowOpaqueTokenIntrospection()); assertTrue(token.customizerName().isEmpty()); assertTrue(token.verifyAccessTokenWithUserInfo().isEmpty()); var logout = config.logout(); assertNotNull(logout); assertTrue(logout.path().isEmpty()); assertTrue(logout.postLogoutPath().isEmpty()); assertEquals(OidcConstants.POST_LOGOUT_REDIRECT_URI, logout.postLogoutUriParam()); assertTrue(logout.extraParams().isEmpty()); var backchannel = logout.backchannel(); assertNotNull(backchannel); assertTrue(backchannel.path().isEmpty()); assertEquals(10, backchannel.tokenCacheSize()); assertEquals(10, backchannel.tokenCacheTimeToLive().toMinutes()); assertTrue(backchannel.cleanUpTimerInterval().isEmpty()); assertEquals("sub", backchannel.logoutTokenKey()); var frontchannel = logout.frontchannel(); assertNotNull(frontchannel); assertTrue(frontchannel.path().isEmpty()); var certificateChain = config.certificateChain(); assertNotNull(certificateChain); assertTrue(certificateChain.leafCertificateName().isEmpty()); assertTrue(certificateChain.trustStoreFile().isEmpty()); assertTrue(certificateChain.trustStorePassword().isEmpty()); assertTrue(certificateChain.trustStoreCertAlias().isEmpty()); assertTrue(certificateChain.trustStoreFileType().isEmpty()); var authentication = config.authentication(); assertNotNull(authentication); assertTrue(authentication.responseMode().isEmpty()); assertTrue(authentication.redirectPath().isEmpty()); assertFalse(authentication.restorePathAfterRedirect()); assertTrue(authentication.removeRedirectParameters()); assertTrue(authentication.errorPath().isEmpty()); assertTrue(authentication.sessionExpiredPath().isEmpty()); assertFalse(authentication.verifyAccessToken()); assertTrue(authentication.forceRedirectHttpsScheme().isEmpty()); assertTrue(authentication.scopes().isEmpty()); assertTrue(authentication.scopeSeparator().isEmpty()); assertFalse(authentication.nonceRequired()); assertTrue(authentication.addOpenidScope().isEmpty()); assertTrue(authentication.extraParams().isEmpty()); assertTrue(authentication.forwardParams().isEmpty()); assertFalse(authentication.cookieForceSecure()); assertTrue(authentication.cookieSuffix().isEmpty()); assertEquals("/", authentication.cookiePath()); assertTrue(authentication.cookiePathHeader().isEmpty()); assertTrue(authentication.cookieDomain().isEmpty()); assertEquals(CookieSameSite.LAX, authentication.cookieSameSite()); assertTrue(authentication.allowMultipleCodeFlows()); assertFalse(authentication.failOnMissingStateParam()); assertTrue(authentication.userInfoRequired().isEmpty()); assertEquals(5, authentication.sessionAgeExtension().toMinutes()); assertEquals(5, authentication.stateCookieAge().toMinutes()); assertTrue(authentication.javaScriptAutoRedirect()); assertTrue(authentication.idTokenRequired().isEmpty()); assertTrue(authentication.internalIdTokenLifespan().isEmpty()); assertTrue(authentication.pkceRequired().isEmpty()); assertTrue(authentication.pkceSecret().isEmpty()); assertTrue(authentication.stateSecret().isEmpty()); var codeGrant = config.codeGrant(); assertNotNull(codeGrant); assertTrue(codeGrant.extraParams().isEmpty()); assertTrue(codeGrant.headers().isEmpty()); var tokenStateManager = config.tokenStateManager(); assertNotNull(tokenStateManager); assertEquals(Strategy.KEEP_ALL_TOKENS, tokenStateManager.strategy()); assertFalse(tokenStateManager.splitTokens()); assertTrue(tokenStateManager.encryptionRequired()); assertTrue(tokenStateManager.encryptionSecret().isEmpty()); assertEquals(EncryptionAlgorithm.A256GCMKW, tokenStateManager.encryptionAlgorithm()); var jwks = config.jwks(); assertNotNull(jwks); assertTrue(jwks.resolveEarly()); assertEquals(10, jwks.cacheSize()); assertEquals(10, jwks.cacheTimeToLive().toMinutes()); assertTrue(jwks.cleanUpTimerInterval().isEmpty()); assertFalse(jwks.tryAll()); // OidcClientCommonConfig methods assertTrue(config.tokenPath().isEmpty()); assertTrue(config.revokePath().isEmpty()); assertTrue(config.clientId().isEmpty()); assertTrue(config.clientName().isEmpty()); var credentials = config.credentials(); assertNotNull(credentials); assertTrue(credentials.secret().isEmpty()); var clientSecret = credentials.clientSecret(); assertNotNull(clientSecret); assertTrue(clientSecret.value().isEmpty()); assertTrue(clientSecret.method().isEmpty()); var provider = clientSecret.provider(); assertNotNull(provider); assertTrue(provider.key().isEmpty()); assertTrue(provider.keyringName().isEmpty()); assertTrue(provider.name().isEmpty()); var jwt = credentials.jwt(); assertNotNull(jwt); assertEquals(Source.CLIENT, jwt.source()); assertTrue(jwt.secret().isEmpty()); provider = jwt.secretProvider(); assertNotNull(provider); assertTrue(provider.key().isEmpty()); assertTrue(provider.keyringName().isEmpty()); assertTrue(provider.name().isEmpty()); assertTrue(jwt.key().isEmpty()); assertTrue(jwt.keyFile().isEmpty()); assertTrue(jwt.keyStoreFile().isEmpty()); assertTrue(jwt.keyStorePassword().isEmpty()); assertTrue(jwt.keyId().isEmpty()); assertTrue(jwt.keyPassword().isEmpty()); assertTrue(jwt.audience().isEmpty()); assertTrue(jwt.tokenKeyId().isEmpty()); assertTrue(jwt.issuer().isEmpty()); assertTrue(jwt.subject().isEmpty()); assertTrue(jwt.claims().isEmpty()); assertTrue(jwt.signatureAlgorithm().isEmpty()); assertEquals(10, jwt.lifespan()); assertFalse(jwt.assertion()); assertTrue(jwt.tokenPath().isEmpty()); // OidcCommonConfig methods assertTrue(config.authServerUrl().isEmpty()); assertTrue(config.discoveryEnabled().isEmpty()); assertTrue(config.registrationPath().isEmpty()); assertTrue(config.connectionDelay().isEmpty()); assertEquals(3, config.connectionRetryCount()); assertEquals(10, config.connectionTimeout().getSeconds()); assertFalse(config.useBlockingDnsLookup()); assertTrue(config.maxPoolSize().isEmpty()); assertTrue(config.followRedirects()); assertNotNull(config.proxy()); assertTrue(config.proxy().host().isEmpty()); assertEquals(80, config.proxy().port()); assertTrue(config.proxy().username().isEmpty()); assertTrue(config.proxy().password().isEmpty()); assertNotNull(config.tls()); assertTrue(config.tls().tlsConfigurationName().isEmpty()); assertTrue(config.tls().verification().isEmpty()); assertTrue(config.tls().keyStoreFile().isEmpty()); assertTrue(config.tls().keyStoreFileType().isEmpty()); assertTrue(config.tls().keyStoreProvider().isEmpty()); assertTrue(config.tls().keyStorePassword().isEmpty()); assertTrue(config.tls().keyStoreKeyAlias().isEmpty()); assertTrue(config.tls().keyStoreKeyPassword().isEmpty()); assertTrue(config.tls().trustStoreFile().isEmpty()); assertTrue(config.tls().trustStorePassword().isEmpty()); assertTrue(config.tls().trustStoreCertAlias().isEmpty()); assertTrue(config.tls().trustStoreFileType().isEmpty()); assertTrue(config.tls().trustStoreProvider().isEmpty()); } @Test public void testSetEveryProperty() { var config = OidcTenantConfig.builder() // OidcTenantConfig methods .tenantId("set-every-property-test") .disableTenant() .applicationType(ApplicationType.HYBRID) .authorizationPath("authorization-path-test") .userInfoPath("user-info-path-test") .introspectionPath("introspection-path-test") .jwksPath("jwks-path-test") .endSessionPath("end-session-path-test") .tenantPaths("tenant-path-test") .publicKey("public-key-test") .allowTokenIntrospectionCache() .allowUserInfoCache() .cacheUserInfoInIdtoken() .provider(Provider.FACEBOOK) .introspectionCredentials().name("i-name").secret("i-secret").includeClientId(false).end() .roles().roleClaimSeparator("@#$").roleClaimPath("separator-23").source(idtoken).end() .token() .verifyAccessTokenWithUserInfo() .customizerName("customizer-name-8") .allowOpaqueTokenIntrospection(false) .requireJwtIntrospectionOnly() .allowJwtIntrospection(false) .decryptionKeyLocation("decryption-key-location-test") .signatureAlgorithm(PS384) .authorizationScheme("bearer-1234") .header("doloris") .forcedJwkRefreshInterval(Duration.ofMinutes(100)) .refreshTokenTimeSkew(Duration.ofMinutes(99)) .refreshExpired() .principalClaim("potter") .issuedAtRequired(false) .age(Duration.ofMinutes(68)) .lifespanGrace(99) .tokenType("McGonagall") .requiredClaims("req-claim-name", "req-claim-val") .requiredClaims("req-array-claim-name", Set.of("item-1", "item-2")) .subjectRequired() .audience("professor hagrid") .issuer("issuer-3") .end() .logout() .path("logout-path-1") .extraParam("extra-param-key-8", "extra-param-val-8") .frontchannelPath("front-channel-path-7") .postLogoutPath("post-logout-path-4") .postLogoutUriParam("post-logout-uri-param-1") .backchannel() .path("backchannel-path-6") .tokenCacheTimeToLive(Duration.ofMinutes(3)) .cleanUpTimerInterval(Duration.ofMinutes(5)) .logoutTokenKey("logout-token-key-6") .tokenCacheSize(9) .endLogout() .certificateChain() .trustStoreFile(Path.of("here")) .trustStoreCertAlias("trust-store-cert-alias-test-30") .trustStorePassword("trust-store-password-test-64") .trustStoreFileType("trust-store-file-type-test-636") .leafCertificateName("leaf-certificate-name-test-875") .end() .codeGrant() .extraParam("2", "two") .extraParam("4", "three!") .header("1", "123") .header("3", "321") .header("5", "222") .end() .tokenStateManager() .strategy(Strategy.ID_REFRESH_TOKENS) .splitTokens() .encryptionRequired(false) .encryptionSecret("encryption-secret-test-999") .encryptionAlgorithm(EncryptionAlgorithm.DIR) .end() .jwks() .tryAll() .cleanUpTimerInterval(Duration.ofMinutes(1)) .cacheTimeToLive(Duration.ofMinutes(2)) .cacheSize(55) .resolveEarly(false) .end() // OidcClientCommonConfig methods .tokenPath("token-path-yep") .revokePath("revoke-path-yep") .clientId("client-id-yep") .clientName("client-name-yep") .credentials() .secret("secret-yep") .clientSecret() .method(Method.QUERY) .value("value-yep") .provider("key-yep", "name-yep", "keyring-name-yep") .end() .jwt() .source(Source.BEARER) .tokenPath(Path.of("my-super-bearer-path")) .secretProvider() .keyringName("jwt-keyring-name-yep") .key("jwt-key-yep") .name("jwt-name-yep") .end() .secret("jwt-secret-yep") .key("jwt-key-yep") .keyFile("jwt-key-file-yep") .keyStoreFile("jwt-key-store-file-yep") .keyStorePassword("jwt-key-store-password-yep") .keyId("jwt-key-id-yep") .keyPassword("jwt-key-pwd-yep") .audience("jwt-audience-yep") .tokenKeyId("jwt-token-key-id-yep") .issuer("jwt-issuer") .subject("jwt-subject") .claim("claim-one-name", "claim-one-value") .claims(Map.of("claim-two-name", "claim-two-value")) .signatureAlgorithm("ES512") .lifespan(852) .assertion(true) .endCredentials() .authentication() .responseMode(QUERY) .redirectPath("/redirect-path-auth-yep") .restorePathAfterRedirect() .removeRedirectParameters(false) .errorPath("/error-path-auth-yep") .sessionExpiredPath("/session-expired-path-auth-yep") .verifyAccessToken() .forceRedirectHttpsScheme() .scopes(List.of("scope-one", "scope-two", "scope-three")) .scopeSeparator("scope-separator-654456") .nonceRequired() .addOpenidScope(false) .extraParam("ex-auth-param-6-key", "ex-auth-param-6-val") .extraParam("ex-auth-param-7-key", "ex-auth-param-7-val") .forwardParams("forward-param-6-key", "forward-param-6-val") .forwardParams("forward-param-7-key", "forward-param-7-val") .cookieForceSecure() .cookieSuffix("cookie-suffix-auth-whatever") .cookiePath("/cookie-path-auth-whatever") .cookiePathHeader("cookie-path-header-auth-whatever") .cookieDomain("cookie-domain-auth-whatever") .cookieSameSite(CookieSameSite.STRICT) .allowMultipleCodeFlows(false) .failOnMissingStateParam() .userInfoRequired() .sessionAgeExtension(Duration.ofMinutes(77)) .stateCookieAge(Duration.ofMinutes(88)) .javaScriptAutoRedirect(false) .idTokenRequired(false) .internalIdTokenLifespan(Duration.ofMinutes(357)) .pkceRequired() .stateSecret("state-secret-auth-whatever") .end() // OidcCommonConfig methods .authServerUrl("we") .discoveryEnabled(false) .registrationPath("don't") .connectionDelay(Duration.ofSeconds(656)) .connectionRetryCount(565) .connectionTimeout(Duration.ofSeconds(673)) .useBlockingDnsLookup(true) .maxPoolSize(376) .followRedirects(false) .proxy("need", 55, "no", "education") .tlsConfigurationName("Teacher!") .build(); // OidcTenantConfig methods assertEquals("set-every-property-test", config.tenantId().orElse(null)); assertFalse(config.tenantEnabled()); assertEquals(ApplicationType.HYBRID, config.applicationType().orElse(null)); assertEquals("authorization-path-test", config.authorizationPath().orElse(null)); assertEquals("user-info-path-test", config.userInfoPath().orElse(null)); assertEquals("introspection-path-test", config.introspectionPath().orElse(null)); assertEquals("jwks-path-test", config.jwksPath().orElse(null)); assertEquals("end-session-path-test", config.endSessionPath().orElse(null)); assertEquals(1, config.tenantPaths().orElseThrow().size()); assertEquals("tenant-path-test", config.tenantPaths().orElseThrow().get(0)); assertEquals("public-key-test", config.publicKey().orElse(null)); assertTrue(config.allowTokenIntrospectionCache()); assertTrue(config.allowUserInfoCache()); assertTrue(config.cacheUserInfoInIdtoken().orElseThrow()); assertEquals(Provider.FACEBOOK, config.provider().orElse(null)); var introspectionCredentials = config.introspectionCredentials(); assertNotNull(introspectionCredentials); assertEquals("i-name", introspectionCredentials.name().get()); assertEquals("i-secret", introspectionCredentials.secret().get()); assertFalse(introspectionCredentials.includeClientId()); var roles = config.roles(); assertNotNull(roles); var roleClaimPaths = roles.roleClaimPath().orElse(null); assertNotNull(roleClaimPaths); assertEquals(1, roleClaimPaths.size()); assertTrue(roleClaimPaths.contains("separator-23")); assertEquals("@#$", roles.roleClaimSeparator().orElse(null)); assertEquals(idtoken, roles.source().orElse(null)); var token = config.token(); assertNotNull(token); assertTrue(token.issuer().isPresent()); assertEquals("issuer-3", token.issuer().get()); assertTrue(token.audience().isPresent()); assertEquals(1, token.audience().get().size()); assertTrue(token.audience().get().contains("professor hagrid")); assertTrue(token.subjectRequired()); assertEquals(2, token.requiredClaims().size()); assertEquals("req-claim-val", token.requiredClaims().get("req-claim-name").iterator().next()); assertEquals(Set.of("item-1", "item-2"), token.requiredClaims().get("req-array-claim-name")); assertEquals("McGonagall", token.tokenType().get()); assertEquals(99, token.lifespanGrace().getAsInt()); assertEquals(68, token.age().get().toMinutes()); assertFalse(token.issuedAtRequired()); assertEquals("potter", token.principalClaim().orElse(null)); assertTrue(token.refreshExpired()); assertEquals(99, token.refreshTokenTimeSkew().get().toMinutes()); assertEquals(100, token.forcedJwkRefreshInterval().toMinutes()); assertEquals("doloris", token.header().orElse(null)); assertEquals("bearer-1234", token.authorizationScheme()); assertEquals(PS384, token.signatureAlgorithm().orElse(null)); assertEquals("decryption-key-location-test", token.decryptionKeyLocation().orElse(null)); assertFalse(token.allowJwtIntrospection()); assertTrue(token.requireJwtIntrospectionOnly()); assertFalse(token.allowOpaqueTokenIntrospection()); assertEquals("customizer-name-8", token.customizerName().orElse(null)); assertTrue(token.verifyAccessTokenWithUserInfo().orElseThrow()); var logout = config.logout(); assertNotNull(logout); assertEquals("logout-path-1", logout.path().orElse(null)); assertEquals("post-logout-path-4", logout.postLogoutPath().orElse(null)); assertEquals("post-logout-uri-param-1", logout.postLogoutUriParam()); assertEquals(1, logout.extraParams().size()); assertEquals("extra-param-val-8", logout.extraParams().get("extra-param-key-8")); var backchannel = logout.backchannel(); assertNotNull(backchannel); assertEquals("backchannel-path-6", backchannel.path().orElse(null)); assertEquals(9, backchannel.tokenCacheSize()); assertEquals(3, backchannel.tokenCacheTimeToLive().toMinutes()); assertEquals(5, backchannel.cleanUpTimerInterval().orElseThrow().toMinutes()); assertEquals("logout-token-key-6", backchannel.logoutTokenKey()); var frontchannel = logout.frontchannel(); assertNotNull(frontchannel); assertEquals("front-channel-path-7", frontchannel.path().orElse(null)); var certificateChain = config.certificateChain(); assertNotNull(certificateChain); assertTrue(certificateChain.trustStoreFile().toString().contains("here")); assertEquals("trust-store-cert-alias-test-30", certificateChain.trustStoreCertAlias().orElse(null)); assertEquals("trust-store-password-test-64", certificateChain.trustStorePassword().orElse(null)); assertEquals("trust-store-file-type-test-636", certificateChain.trustStoreFileType().orElse(null)); assertEquals("leaf-certificate-name-test-875", certificateChain.leafCertificateName().orElse(null)); var authentication = config.authentication(); assertNotNull(authentication); var forwardParams = authentication.forwardParams().orElseThrow(); assertEquals(4, forwardParams.size()); assertTrue(forwardParams.contains("forward-param-6-key")); assertTrue(forwardParams.contains("forward-param-7-key")); assertTrue(forwardParams.contains("forward-param-6-val")); assertTrue(forwardParams.contains("forward-param-7-val")); var extraParams = authentication.extraParams(); assertEquals(2, extraParams.size()); assertEquals("ex-auth-param-6-val", extraParams.get("ex-auth-param-6-key")); assertEquals("ex-auth-param-7-val", extraParams.get("ex-auth-param-7-key")); var scopes = authentication.scopes().orElseThrow(); assertEquals(3, scopes.size()); assertTrue(scopes.contains("scope-one")); assertTrue(scopes.contains("scope-two")); assertTrue(scopes.contains("scope-three")); assertEquals("scope-separator-654456", authentication.scopeSeparator().orElseThrow()); assertEquals(QUERY, authentication.responseMode().orElseThrow()); assertEquals("/session-expired-path-auth-yep", authentication.sessionExpiredPath().orElseThrow()); assertEquals("/error-path-auth-yep", authentication.errorPath().orElseThrow()); assertEquals("/redirect-path-auth-yep", authentication.redirectPath().orElseThrow()); assertFalse(authentication.removeRedirectParameters()); assertTrue(authentication.restorePathAfterRedirect()); assertTrue(authentication.verifyAccessToken()); assertTrue(authentication.forceRedirectHttpsScheme().orElseThrow()); assertTrue(authentication.nonceRequired()); assertFalse(authentication.addOpenidScope().orElseThrow()); assertTrue(authentication.cookieForceSecure()); assertEquals("cookie-suffix-auth-whatever", authentication.cookieSuffix().orElse(null)); assertEquals("/cookie-path-auth-whatever", authentication.cookiePath()); assertEquals("cookie-path-header-auth-whatever", authentication.cookiePathHeader().orElseThrow()); assertEquals("cookie-domain-auth-whatever", authentication.cookieDomain().orElseThrow()); assertEquals(CookieSameSite.STRICT, authentication.cookieSameSite()); assertFalse(authentication.allowMultipleCodeFlows()); assertTrue(authentication.failOnMissingStateParam()); assertTrue(authentication.userInfoRequired().orElseThrow()); assertEquals(77, authentication.sessionAgeExtension().toMinutes()); assertEquals(88, authentication.stateCookieAge().toMinutes()); assertFalse(authentication.javaScriptAutoRedirect()); assertFalse(authentication.idTokenRequired().orElseThrow()); assertEquals(357, authentication.internalIdTokenLifespan().orElseThrow().toMinutes()); assertTrue(authentication.pkceRequired().orElseThrow()); assertTrue(authentication.pkceSecret().isEmpty()); assertEquals("state-secret-auth-whatever", authentication.stateSecret().orElse(null)); var codeGrant = config.codeGrant(); assertNotNull(codeGrant); assertEquals(2, codeGrant.extraParams().size()); assertEquals("two", codeGrant.extraParams().get("2")); assertEquals("three!", codeGrant.extraParams().get("4")); assertEquals(3, codeGrant.headers().size()); assertEquals("123", codeGrant.headers().get("1")); assertEquals("321", codeGrant.headers().get("3")); assertEquals("222", codeGrant.headers().get("5")); var tokenStateManager = config.tokenStateManager(); assertNotNull(tokenStateManager); assertEquals(Strategy.ID_REFRESH_TOKENS, tokenStateManager.strategy()); assertTrue(tokenStateManager.splitTokens()); assertFalse(tokenStateManager.encryptionRequired()); assertEquals("encryption-secret-test-999", tokenStateManager.encryptionSecret().orElse(null)); assertEquals(EncryptionAlgorithm.DIR, tokenStateManager.encryptionAlgorithm()); var jwks = config.jwks(); assertNotNull(jwks); assertFalse(jwks.resolveEarly()); assertEquals(55, jwks.cacheSize()); assertEquals(2, jwks.cacheTimeToLive().toMinutes()); assertEquals(1, jwks.cleanUpTimerInterval().orElseThrow().toMinutes()); assertTrue(jwks.tryAll()); // OidcClientCommonConfig methods assertEquals("token-path-yep", config.tokenPath().orElse(null)); assertEquals("revoke-path-yep", config.revokePath().orElse(null)); assertEquals("client-id-yep", config.clientId().orElse(null)); assertEquals("client-name-yep", config.clientName().orElse(null)); var credentials = config.credentials(); assertNotNull(credentials); assertEquals("secret-yep", credentials.secret().orElse(null)); var clientSecret = credentials.clientSecret(); assertNotNull(clientSecret); assertEquals(Method.QUERY, clientSecret.method().orElse(null)); assertEquals("value-yep", clientSecret.value().orElse(null)); var provider = clientSecret.provider(); assertNotNull(provider); assertEquals("key-yep", provider.key().orElse(null)); assertEquals("name-yep", provider.name().orElse(null)); assertEquals("keyring-name-yep", provider.keyringName().orElse(null)); var jwt = credentials.jwt(); assertNotNull(jwt); assertEquals(Source.BEARER, jwt.source()); assertEquals("jwt-secret-yep", jwt.secret().orElse(null)); provider = jwt.secretProvider(); assertNotNull(provider); assertEquals("jwt-keyring-name-yep", provider.keyringName().orElse(null)); assertEquals("jwt-name-yep", provider.name().orElse(null)); assertEquals("jwt-key-yep", provider.key().orElse(null)); assertEquals("jwt-key-yep", jwt.key().orElse(null)); assertEquals("jwt-key-file-yep", jwt.keyFile().orElse(null)); assertEquals("jwt-key-store-file-yep", jwt.keyStoreFile().orElse(null)); assertEquals("jwt-key-store-password-yep", jwt.keyStorePassword().orElse(null)); assertEquals("jwt-key-id-yep", jwt.keyId().orElse(null)); assertEquals("jwt-key-pwd-yep", jwt.keyPassword().orElse(null)); assertEquals("jwt-audience-yep", jwt.audience().orElse(null)); assertEquals("jwt-token-key-id-yep", jwt.tokenKeyId().orElse(null)); assertEquals("jwt-issuer", jwt.issuer().orElse(null)); assertEquals("jwt-subject", jwt.subject().orElse(null)); assertEquals("my-super-bearer-path", jwt.tokenPath().orElseThrow().toString()); var claims = jwt.claims(); assertNotNull(claims); assertEquals(2, claims.size()); assertTrue(claims.containsKey("claim-one-name")); assertEquals("claim-one-value", claims.get("claim-one-name")); assertTrue(claims.containsKey("claim-two-name")); assertEquals("claim-two-value", claims.get("claim-two-name")); assertEquals("ES512", jwt.signatureAlgorithm().orElse(null)); assertEquals(852, jwt.lifespan()); assertTrue(jwt.assertion()); // OidcCommonConfig methods assertEquals("we", config.authServerUrl().orElse(null)); assertFalse(config.discoveryEnabled().orElse(false)); assertEquals("don't", config.registrationPath().orElse(null)); assertEquals(656, config.connectionDelay().map(Duration::getSeconds).orElse(null)); assertEquals(565, config.connectionRetryCount()); assertEquals(673, config.connectionTimeout().getSeconds()); assertTrue(config.useBlockingDnsLookup()); assertEquals(376, config.maxPoolSize().orElse(0)); assertFalse(config.followRedirects()); assertNotNull(config.proxy()); assertEquals("need", config.proxy().host().orElse(null)); assertEquals(55, config.proxy().port()); assertEquals("no", config.proxy().username().orElse(null)); assertEquals("education", config.proxy().password().orElse(null)); assertNotNull(config.tls()); assertEquals("Teacher!", config.tls().tlsConfigurationName().orElse(null)); assertTrue(config.tls().verification().isEmpty()); assertTrue(config.tls().keyStoreFile().isEmpty()); assertTrue(config.tls().keyStoreFileType().isEmpty()); assertTrue(config.tls().keyStoreProvider().isEmpty()); assertTrue(config.tls().keyStorePassword().isEmpty()); assertTrue(config.tls().keyStoreKeyAlias().isEmpty()); assertTrue(config.tls().keyStoreKeyPassword().isEmpty()); assertTrue(config.tls().trustStoreFile().isEmpty()); assertTrue(config.tls().trustStorePassword().isEmpty()); assertTrue(config.tls().trustStoreCertAlias().isEmpty()); assertTrue(config.tls().trustStoreFileType().isEmpty()); assertTrue(config.tls().trustStoreProvider().isEmpty()); } @Test public void testCopyProxyProperties() { var previousConfig = OidcTenantConfig.builder() .tenantId("copy-proxy-properties-test") .proxy("need", 55, "no", "education") .build(); var newConfig = OidcTenantConfig.builder(previousConfig) .proxy("fast-car", 22) .build(); assertNotNull(previousConfig.proxy()); assertEquals("copy-proxy-properties-test", newConfig.tenantId().orElse(null)); assertEquals("fast-car", newConfig.proxy().host().orElse(null)); assertEquals(22, newConfig.proxy().port()); assertEquals("no", newConfig.proxy().username().orElse(null)); assertEquals("education", newConfig.proxy().password().orElse(null)); } @Test public void testCopyOidcTenantConfigProperties() { var existingConfig = OidcTenantConfig.builder() // OidcTenantConfig methods .tenantId("test-copy-tenant-props") .tenantEnabled(false) .authorizationPath("authorization-path-test-1") .userInfoPath("user-info-path-test-1") .introspectionPath("introspection-path-test-1") .jwksPath("jwks-path-test-1") .endSessionPath("end-session-path-test-1") .tenantPath("tenant-path-test-1") .tenantPaths("tenant-path-test-2", "tenant-path-test-3") .publicKey("public-key-test-1") .allowTokenIntrospectionCache() .allowUserInfoCache() .cacheUserInfoInIdtoken() .provider(Provider.GOOGLE) // the rest of c&p tests for the OidcTenantConfig are tested in their dedicated builder tests below .build(); // OidcTenantConfig methods assertEquals("test-copy-tenant-props", existingConfig.tenantId().orElse(null)); assertFalse(existingConfig.tenantEnabled()); var tenantPaths = existingConfig.tenantPaths().orElseThrow(); assertEquals(3, tenantPaths.size()); assertTrue(tenantPaths.contains("tenant-path-test-1")); assertTrue(tenantPaths.contains("tenant-path-test-2")); assertTrue(tenantPaths.contains("tenant-path-test-3")); assertTrue(existingConfig.allowTokenIntrospectionCache()); assertTrue(existingConfig.allowUserInfoCache()); assertTrue(existingConfig.cacheUserInfoInIdtoken().orElseThrow()); var newConfig = OidcTenantConfig.builder(existingConfig) // OidcTenantConfig methods .enableTenant() .tenantPaths(List.of("tenant-path-test-4", "tenant-path-test-5")) .allowTokenIntrospectionCache(false) .allowUserInfoCache(false) .cacheUserInfoInIdtoken(false) .build(); // OidcTenantConfig methods assertEquals("test-copy-tenant-props", newConfig.tenantId().orElse(null)); assertTrue(newConfig.tenantEnabled()); assertEquals("authorization-path-test-1", newConfig.authorizationPath().orElse(null)); assertEquals("user-info-path-test-1", newConfig.userInfoPath().orElse(null)); assertEquals("introspection-path-test-1", newConfig.introspectionPath().orElse(null)); assertEquals("jwks-path-test-1", newConfig.jwksPath().orElse(null)); assertEquals("end-session-path-test-1", newConfig.endSessionPath().orElse(null)); tenantPaths = newConfig.tenantPaths().orElseThrow(); assertEquals(5, tenantPaths.size()); assertTrue(tenantPaths.contains("tenant-path-test-1")); assertTrue(tenantPaths.contains("tenant-path-test-2")); assertTrue(tenantPaths.contains("tenant-path-test-3")); assertTrue(tenantPaths.contains("tenant-path-test-4")); assertTrue(tenantPaths.contains("tenant-path-test-5")); assertEquals("public-key-test-1", newConfig.publicKey().orElse(null)); assertFalse(newConfig.allowTokenIntrospectionCache()); assertFalse(newConfig.allowUserInfoCache()); assertFalse(newConfig.cacheUserInfoInIdtoken().orElseThrow()); assertEquals(Provider.GOOGLE, newConfig.provider().orElse(null)); } @Test public void testCopyOidcClientCommonConfigProperties() { var existingConfig = OidcTenantConfig.builder() // OidcTenantConfig methods .tenantId("copy-oidc-client-common-props") // OidcClientCommonConfig methods .tokenPath("token-path-yep") .revokePath("revoke-path-yep") .clientId("client-id-yep") .clientName("client-name-yep") .credentials() .secret("secret-yep") .clientSecret() .method(Method.QUERY) .value("value-yep") .provider("key-yep", "name-yep", "keyring-name-yep") .end() .jwt() .source(Source.BEARER) .tokenPath(Path.of("jwt-bearer-token-path-test-1")) .secretProvider() .keyringName("jwt-keyring-name-yep") .key("jwt-key-yep") .name("jwt-name-yep") .end() .secret("jwt-secret-yep") .key("jwt-key-yep") .keyFile("jwt-key-file-yep") .keyStoreFile("jwt-key-store-file-yep") .keyStorePassword("jwt-key-store-password-yep") .keyId("jwt-key-id-yep") .keyPassword("jwt-key-pwd-yep") .audience("jwt-audience-yep") .tokenKeyId("jwt-token-key-id-yep") .issuer("jwt-issuer") .subject("jwt-subject") .claim("claim-one-name", "claim-one-value") .claims(Map.of("claim-two-name", "claim-two-value")) .signatureAlgorithm("ES512") .lifespan(852) .assertion(true) .endCredentials() .build(); assertEquals("copy-oidc-client-common-props", existingConfig.tenantId().orElse(null)); // OidcClientCommonConfig methods assertEquals("token-path-yep", existingConfig.tokenPath().orElse(null)); assertEquals("revoke-path-yep", existingConfig.revokePath().orElse(null)); assertEquals("client-id-yep", existingConfig.clientId().orElse(null)); assertEquals("client-name-yep", existingConfig.clientName().orElse(null)); var credentials = existingConfig.credentials(); assertNotNull(credentials); assertEquals("secret-yep", credentials.secret().orElse(null)); var clientSecret = credentials.clientSecret(); assertNotNull(clientSecret); assertEquals(Method.QUERY, clientSecret.method().orElse(null)); assertEquals("value-yep", clientSecret.value().orElse(null)); var provider = clientSecret.provider(); assertNotNull(provider); assertEquals("key-yep", provider.key().orElse(null)); assertEquals("name-yep", provider.name().orElse(null)); assertEquals("keyring-name-yep", provider.keyringName().orElse(null)); var jwt = credentials.jwt(); assertNotNull(jwt); assertEquals(Source.BEARER, jwt.source()); assertEquals("jwt-secret-yep", jwt.secret().orElse(null)); provider = jwt.secretProvider(); assertNotNull(provider); assertEquals("jwt-keyring-name-yep", provider.keyringName().orElse(null)); assertEquals("jwt-name-yep", provider.name().orElse(null)); assertEquals("jwt-key-yep", provider.key().orElse(null)); assertEquals("jwt-key-yep", jwt.key().orElse(null)); assertEquals("jwt-key-file-yep", jwt.keyFile().orElse(null)); assertEquals("jwt-key-store-file-yep", jwt.keyStoreFile().orElse(null)); assertEquals("jwt-key-store-password-yep", jwt.keyStorePassword().orElse(null)); assertEquals("jwt-key-id-yep", jwt.keyId().orElse(null)); assertEquals("jwt-key-pwd-yep", jwt.keyPassword().orElse(null)); assertEquals("jwt-audience-yep", jwt.audience().orElse(null)); assertEquals("jwt-token-key-id-yep", jwt.tokenKeyId().orElse(null)); assertEquals("jwt-issuer", jwt.issuer().orElse(null)); assertEquals("jwt-subject", jwt.subject().orElse(null)); var claims = jwt.claims(); assertNotNull(claims); assertEquals(2, claims.size()); assertTrue(claims.containsKey("claim-one-name")); assertEquals("claim-one-value", claims.get("claim-one-name")); assertTrue(claims.containsKey("claim-two-name")); assertEquals("claim-two-value", claims.get("claim-two-name")); assertEquals("ES512", jwt.signatureAlgorithm().orElse(null)); assertEquals(852, jwt.lifespan()); assertTrue(jwt.assertion()); var newConfig = OidcTenantConfig.builder(existingConfig) // OidcClientCommonConfig methods .tokenPath("token-path-yep-CHANGED") .clientId("client-id-yep-CHANGED") .credentials() .secret("secret-yep-CHANGED") .clientSecret("val-1", Method.POST_JWT) .jwt() .secret("different-secret") .secretProvider() .key("jwt-key-yep-CHANGED") .end() .key("jwt-key-yep-CHANGED-2") .keyStoreFile("jwt-key-store-file-yep-CHANGED") .keyPassword("jwt-key-pwd-yep-CHANGED") .issuer("jwt-issuer-CHANGED") .claim("aaa", "bbb") .lifespan(333) .end() .clientSecret("val-1", Method.POST_JWT) .end() .build(); assertEquals("copy-oidc-client-common-props", newConfig.tenantId().orElse(null)); // OidcClientCommonConfig methods assertEquals("token-path-yep-CHANGED", newConfig.tokenPath().orElse(null)); assertEquals("revoke-path-yep", newConfig.revokePath().orElse(null)); assertEquals("client-id-yep-CHANGED", newConfig.clientId().orElse(null)); assertEquals("client-name-yep", newConfig.clientName().orElse(null)); credentials = newConfig.credentials(); assertNotNull(credentials); assertEquals("secret-yep-CHANGED", credentials.secret().orElse(null)); clientSecret = credentials.clientSecret(); assertNotNull(clientSecret); assertEquals(Method.POST_JWT, clientSecret.method().orElse(null)); assertEquals("val-1", clientSecret.value().orElse(null)); provider = clientSecret.provider(); assertNotNull(provider); assertEquals("key-yep", provider.key().orElse(null)); assertEquals("name-yep", provider.name().orElse(null)); assertEquals("keyring-name-yep", provider.keyringName().orElse(null)); jwt = credentials.jwt(); assertNotNull(jwt); assertEquals(Source.BEARER, jwt.source()); assertEquals("different-secret", jwt.secret().orElse(null)); provider = jwt.secretProvider(); assertNotNull(provider); assertEquals("jwt-keyring-name-yep", provider.keyringName().orElse(null)); assertEquals("jwt-name-yep", provider.name().orElse(null)); assertEquals("jwt-key-yep-CHANGED", provider.key().orElse(null)); assertEquals("jwt-key-yep-CHANGED-2", jwt.key().orElse(null)); assertEquals("jwt-key-file-yep", jwt.keyFile().orElse(null)); assertEquals("jwt-key-store-file-yep-CHANGED", jwt.keyStoreFile().orElse(null)); assertEquals("jwt-key-store-password-yep", jwt.keyStorePassword().orElse(null)); assertEquals("jwt-key-id-yep", jwt.keyId().orElse(null)); assertEquals("jwt-key-pwd-yep-CHANGED", jwt.keyPassword().orElse(null)); assertEquals("jwt-audience-yep", jwt.audience().orElse(null)); assertEquals("jwt-token-key-id-yep", jwt.tokenKeyId().orElse(null)); assertEquals("jwt-issuer-CHANGED", jwt.issuer().orElse(null)); assertEquals("jwt-subject", jwt.subject().orElse(null)); assertEquals("jwt-bearer-token-path-test-1", jwt.tokenPath().orElseThrow().toString()); claims = jwt.claims(); assertNotNull(claims); assertEquals(3, claims.size()); assertTrue(claims.containsKey("claim-one-name")); assertEquals("claim-one-value", claims.get("claim-one-name")); assertTrue(claims.containsKey("claim-two-name")); assertEquals("claim-two-value", claims.get("claim-two-name")); assertTrue(claims.containsKey("aaa")); assertEquals("bbb", claims.get("aaa")); assertEquals("ES512", jwt.signatureAlgorithm().orElse(null)); assertEquals(333, jwt.lifespan()); assertTrue(jwt.assertion()); } @Test public void testCopyOidcCommonConfigProperties() { var previousConfig = OidcTenantConfig.builder() .tenantId("common-props-test") .authServerUrl("we") .discoveryEnabled(false) .registrationPath("don't") .connectionDelay(Duration.ofSeconds(656)) .connectionRetryCount(565) .connectionTimeout(Duration.ofSeconds(673)) .useBlockingDnsLookup(true) .maxPoolSize(376) .followRedirects(false) .proxy("need", 55, "no", "education") .tlsConfigurationName("Teacher!") .build(); var newConfig = OidcTenantConfig.builder(previousConfig) .discoveryEnabled(true) .connectionDelay(Duration.ofSeconds(753)) .connectionTimeout(Duration.ofSeconds(357)) .maxPoolSize(1988) .proxy("cross", 44, "the", "boarder") .build(); assertEquals("common-props-test", newConfig.tenantId().orElse(null)); assertEquals("we", newConfig.authServerUrl().orElse(null)); assertTrue(newConfig.discoveryEnabled().orElse(false)); assertEquals("don't", newConfig.registrationPath().orElse(null)); assertEquals(753, newConfig.connectionDelay().map(Duration::getSeconds).orElse(null)); assertEquals(565, newConfig.connectionRetryCount()); assertEquals(357, newConfig.connectionTimeout().getSeconds()); assertTrue(newConfig.useBlockingDnsLookup()); assertEquals(1988, newConfig.maxPoolSize().orElse(0)); assertFalse(newConfig.followRedirects()); assertNotNull(newConfig.proxy()); assertEquals("cross", newConfig.proxy().host().orElse(null)); assertEquals(44, newConfig.proxy().port()); assertEquals("the", newConfig.proxy().username().orElse(null)); assertEquals("boarder", newConfig.proxy().password().orElse(null)); assertNotNull(newConfig.tls()); assertEquals("Teacher!", newConfig.tls().tlsConfigurationName().orElse(null)); assertTrue(newConfig.tls().verification().isEmpty()); assertTrue(newConfig.tls().keyStoreFile().isEmpty()); assertTrue(newConfig.tls().keyStoreFileType().isEmpty()); assertTrue(newConfig.tls().keyStoreProvider().isEmpty()); assertTrue(newConfig.tls().keyStorePassword().isEmpty()); assertTrue(newConfig.tls().keyStoreKeyAlias().isEmpty()); assertTrue(newConfig.tls().keyStoreKeyPassword().isEmpty()); assertTrue(newConfig.tls().trustStoreFile().isEmpty()); assertTrue(newConfig.tls().trustStorePassword().isEmpty()); assertTrue(newConfig.tls().trustStoreCertAlias().isEmpty()); assertTrue(newConfig.tls().trustStoreFileType().isEmpty()); assertTrue(newConfig.tls().trustStoreProvider().isEmpty()); } @Test public void testCreateBuilderShortcuts() { OidcTenantConfig config = OidcTenantConfig.authServerUrl("auth-server-url").tenantId("shortcuts-1").build(); assertEquals("auth-server-url", config.authServerUrl().orElse(null)); assertEquals("shortcuts-1", config.tenantId().orElse(null)); config = OidcTenantConfig.registrationPath("registration-path").tenantId("shortcuts-2").build(); assertEquals("registration-path", config.registrationPath().orElse(null)); assertEquals("shortcuts-2", config.tenantId().orElse(null)); config = OidcTenantConfig.tokenPath("token-path").tenantId("shortcuts-3").build(); assertEquals("token-path", config.tokenPath().orElse(null)); assertEquals("shortcuts-3", config.tenantId().orElse(null)); } @Test public void testCredentialsBuilder() { var jwt = new JwtBuilder<>() .secret("hush-hush") .build(); var clientSecret = new SecretBuilder<>() .value("harry") .build(); var credentials = new CredentialsBuilder<>() .secret("1234") .jwt(jwt) .clientSecret(clientSecret) .build(); var config = OidcTenantConfig.builder().tenantId("1").credentials(credentials).build(); var buildCredentials = config.credentials(); assertEquals("1", config.tenantId().orElse(null)); assertNotNull(buildCredentials); assertEquals("1234", buildCredentials.secret().orElse(null)); assertEquals("hush-hush", buildCredentials.jwt().secret().orElse(null)); assertEquals("harry", buildCredentials.clientSecret().value().orElse(null)); } @Test public void testIntrospectionCredentialsBuilder() { var first = new IntrospectionCredentialsBuilder().includeClientId(false).build(); var config1 = OidcTenantConfig.builder().tenantId("1").introspectionCredentials(first).build(); assertFalse(config1.introspectionCredentials().includeClientId()); assertTrue(config1.introspectionCredentials().name().isEmpty()); assertTrue(config1.introspectionCredentials().secret().isEmpty()); var config2Builder = OidcTenantConfig.builder(config1).introspectionCredentials("name1", "secret1"); var config2 = config2Builder.build(); assertFalse(config2.introspectionCredentials().includeClientId()); assertEquals("name1", config2.introspectionCredentials().name().orElse(null)); assertEquals("secret1", config2.introspectionCredentials().secret().orElse(null)); var config3Builder = new IntrospectionCredentialsBuilder(config2Builder).secret("951357").end(); var config3 = config3Builder.build(); assertFalse(config3.introspectionCredentials().includeClientId()); assertEquals("name1", config3.introspectionCredentials().name().orElse(null)); assertEquals("951357", config3.introspectionCredentials().secret().orElse(null)); assertEquals("1", config3.tenantId().orElse(null)); } @Test public void testRolesBuilder() { var first = new RolesBuilder().source(accesstoken).build(); var config1 = OidcTenantConfig.builder().tenantId("1").roles(first).build(); assertTrue(config1.roles().roleClaimPath().isEmpty()); assertTrue(config1.roles().roleClaimSeparator().isEmpty()); assertEquals(accesstoken, config1.roles().source().orElse(null)); var config2Builder = OidcTenantConfig.builder(config1).roles(userinfo, "role-claim-path-1"); var config2 = config2Builder.build(); assertEquals(userinfo, config2.roles().source().orElse(null)); assertTrue(config2.roles().roleClaimSeparator().isEmpty()); assertTrue(config2.roles().roleClaimPath().isPresent()); var roleClaimPath = config2.roles().roleClaimPath().get(); assertEquals(1, roleClaimPath.size()); assertTrue(roleClaimPath.contains("role-claim-path-1")); var config3Builder = new RolesBuilder(config2Builder).roleClaimSeparator("!!!!").end(); var config3 = config3Builder.build(); assertEquals(userinfo, config3.roles().source().orElse(null)); assertTrue(config3.roles().roleClaimPath().isPresent()); roleClaimPath = config3.roles().roleClaimPath().get(); assertEquals(1, roleClaimPath.size()); assertTrue(roleClaimPath.contains("role-claim-path-1")); assertEquals("!!!!", config3.roles().roleClaimSeparator().orElse(null)); assertEquals("1", config3.tenantId().orElse(null)); } @Test public void testTokenBuilder() { var first = new TokenConfigBuilder() .audience(List.of("one", "two")) .requiredClaims(Map.of("I", "II")) .subjectRequired() .refreshExpired() .allowJwtIntrospection(false) .requireJwtIntrospectionOnly() .allowOpaqueTokenIntrospection(false) .verifyAccessTokenWithUserInfo() .build(); var config1Builder = new OidcTenantConfigBuilder().token(first).tenantId("haha"); var config1 = config1Builder.build(); var builtFirst = config1.token(); assertTrue(builtFirst.verifyAccessTokenWithUserInfo().orElseThrow()); assertFalse(builtFirst.allowOpaqueTokenIntrospection()); assertTrue(builtFirst.requireJwtIntrospectionOnly()); assertFalse(builtFirst.allowJwtIntrospection()); assertTrue(builtFirst.refreshExpired()); assertTrue(builtFirst.subjectRequired()); assertEquals(1, builtFirst.requiredClaims().size()); assertEquals("II", builtFirst.requiredClaims().get("I").iterator().next()); assertEquals(2, builtFirst.audience().orElseThrow().size()); assertTrue(builtFirst.audience().orElseThrow().contains("one")); assertTrue(builtFirst.audience().orElseThrow().contains("two")); var second = new TokenConfigBuilder(config1Builder) .requiredClaims(Map.of("III", "IV")) .audience("extra"); var config2 = second.end() .token().verifyAccessTokenWithUserInfo(false).principalClaim("prince").end() .build(); var builtSecond = config2.token(); assertFalse(builtSecond.verifyAccessTokenWithUserInfo().orElseThrow()); assertFalse(builtSecond.allowOpaqueTokenIntrospection()); assertTrue(builtSecond.requireJwtIntrospectionOnly()); assertFalse(builtSecond.allowJwtIntrospection()); assertTrue(builtSecond.refreshExpired()); assertTrue(builtSecond.subjectRequired()); assertEquals(2, builtSecond.requiredClaims().size()); assertEquals("II", builtSecond.requiredClaims().get("I").iterator().next()); assertEquals("IV", builtSecond.requiredClaims().get("III").iterator().next()); assertEquals(3, builtSecond.audience().orElseThrow().size()); assertTrue(builtSecond.audience().orElseThrow().contains("one")); assertTrue(builtSecond.audience().orElseThrow().contains("two")); assertTrue(builtSecond.audience().orElseThrow().contains("extra")); assertEquals("prince", builtSecond.principalClaim().orElse(null)); var config3 = OidcTenantConfig.builder(config2).token().verifyAccessTokenWithUserInfo().end().build(); assertTrue(config3.token().verifyAccessTokenWithUserInfo().orElseThrow()); assertEquals("haha", config3.tenantId().orElse(null)); } @Test public void testLogoutConfigBuilder() { var first = new LogoutConfigBuilder().postLogoutPath("post-logout-path-AAA").path("path-BBB") .frontchannelPath("front-channel-path-7").extraParams(Map.of("ex-1-k", "ex-1-v")) .postLogoutUriParam("uri-param-44").backchannel().logoutTokenKey("log-me-out").end().build(); var config1 = OidcTenantConfig.builder().tenantId("tenant-357").logout(first).build(); var builtFirst = config1.logout(); assertEquals("post-logout-path-AAA", builtFirst.postLogoutPath().orElse(null)); assertEquals("path-BBB", builtFirst.path().orElse(null)); assertEquals("front-channel-path-7", builtFirst.frontchannel().path().orElse(null)); assertEquals(1, builtFirst.extraParams().size()); assertEquals("ex-1-v", builtFirst.extraParams().get("ex-1-k")); assertEquals("uri-param-44", builtFirst.postLogoutUriParam()); assertEquals("log-me-out", builtFirst.backchannel().logoutTokenKey()); var second = new LogoutConfigBuilder(OidcTenantConfig.builder(config1)).backchannel().path("path-CCC").endLogout(); var config2 = second.build(); var builtSecond = config2.logout(); assertEquals("post-logout-path-AAA", builtSecond.postLogoutPath().orElse(null)); assertEquals("path-BBB", builtSecond.path().orElse(null)); assertEquals("front-channel-path-7", builtSecond.frontchannel().path().orElse(null)); assertEquals(1, builtSecond.extraParams().size()); assertEquals("ex-1-v", builtSecond.extraParams().get("ex-1-k")); assertEquals("uri-param-44", builtSecond.postLogoutUriParam()); assertEquals("log-me-out", builtSecond.backchannel().logoutTokenKey()); assertEquals("path-CCC", builtSecond.backchannel().path().orElse(null)); var newBackchannel = new BackchannelBuilder().tokenCacheSize(555).build(); var third = new LogoutConfigBuilder().backchannel(newBackchannel).build(); var config3 = OidcTenantConfig.builder(config2).logout(third).build(); // expect defaults everywhere except for the backchannel token cache size var builtThird = config3.logout(); assertNotNull(builtThird); assertTrue(builtThird.path().isEmpty()); assertTrue(builtThird.postLogoutPath().isEmpty()); assertEquals(OidcConstants.POST_LOGOUT_REDIRECT_URI, builtThird.postLogoutUriParam()); assertTrue(builtThird.extraParams().isEmpty()); var backchannel = builtThird.backchannel(); assertNotNull(backchannel); assertTrue(backchannel.path().isEmpty()); assertEquals(555, backchannel.tokenCacheSize()); assertEquals(10, backchannel.tokenCacheTimeToLive().toMinutes()); assertTrue(backchannel.cleanUpTimerInterval().isEmpty()); assertEquals("sub", backchannel.logoutTokenKey()); var frontchannel = builtThird.frontchannel(); assertNotNull(frontchannel); assertTrue(frontchannel.path().isEmpty()); assertEquals("tenant-357", config3.tenantId().orElse(null)); } @Test public void testCertificateChainBuilder() { var first = new CertificateChainBuilder() .leafCertificateName("ent") .trustStoreFileType("try") .trustStoreFile(Path.of("march")) .trustStoreCertAlias("to") .trustStorePassword("Isengard") .build(); var config1 = OidcTenantConfig.builder().tenantId("2").certificateChain(first).build(); var builtFirst = config1.certificateChain(); assertEquals("ent", builtFirst.leafCertificateName().orElse(null)); assertEquals("try", builtFirst.trustStoreFileType().orElse(null)); assertTrue(builtFirst.trustStoreFile().toString().contains("march")); assertEquals("to", builtFirst.trustStoreCertAlias().orElse(null)); assertEquals("Isengard", builtFirst.trustStorePassword().orElse(null)); var secondBuilder = new CertificateChainBuilder(new OidcTenantConfigBuilder(config1)) .leafCertificateName("fangorn").end(); var config2 = secondBuilder.build(); var builtSecond = config2.certificateChain(); assertEquals("fangorn", builtSecond.leafCertificateName().orElse(null)); assertEquals("try", builtSecond.trustStoreFileType().orElse(null)); assertTrue(builtSecond.trustStoreFile().toString().contains("march")); assertEquals("to", builtSecond.trustStoreCertAlias().orElse(null)); assertEquals("Isengard", builtSecond.trustStorePassword().orElse(null)); var config3 = OidcTenantConfig.builder(config2).certificateChain().trustStorePassword("home").end().build(); var builtThird = config3.certificateChain(); assertEquals("fangorn", builtThird.leafCertificateName().orElse(null)); assertEquals("try", builtThird.trustStoreFileType().orElse(null)); assertTrue(builtThird.trustStoreFile().toString().contains("march")); assertEquals("to", builtThird.trustStoreCertAlias().orElse(null)); assertEquals("home", builtThird.trustStorePassword().orElse(null)); assertEquals("2", config3.tenantId().orElse(null)); } @Test public void testCopyOfAuthenticationConfigBuilder() { var first = new AuthenticationConfigBuilder() .responseMode(QUERY) .redirectPath("/redirect-path-auth-yep") .restorePathAfterRedirect() .removeRedirectParameters(false) .errorPath("/error-path-auth-yep") .sessionExpiredPath("/session-expired-path-auth-yep") .verifyAccessToken() .forceRedirectHttpsScheme() .scopes(List.of("scope-one", "scope-two", "scope-three")) .scopeSeparator("scope-separator-654456") .nonceRequired() .addOpenidScope(false) .extraParam("ex-auth-param-6-key", "ex-auth-param-6-val") .extraParam("ex-auth-param-7-key", "ex-auth-param-7-val") .forwardParams("forward-param-6-key", "forward-param-6-val") .forwardParams("forward-param-7-key", "forward-param-7-val") .cookieForceSecure() .cookieSuffix("cookie-suffix-auth-whatever") .cookiePath("/cookie-path-auth-whatever") .cookiePathHeader("cookie-path-header-auth-whatever") .cookieDomain("cookie-domain-auth-whatever") .cookieSameSite(CookieSameSite.NONE) .allowMultipleCodeFlows(false) .failOnMissingStateParam() .userInfoRequired() .sessionAgeExtension(Duration.ofMinutes(77)) .stateCookieAge(Duration.ofMinutes(88)) .javaScriptAutoRedirect(false) .idTokenRequired(false) .internalIdTokenLifespan(Duration.ofMinutes(357)) .pkceRequired() .stateSecret("state-secret-auth-whatever") .build(); var config1Builder = OidcTenantConfig.builder().tenantId("3").authentication(first); var config1 = config1Builder.build(); var builtFirst = config1.authentication(); var forwardParams = builtFirst.forwardParams().orElseThrow(); assertEquals(4, forwardParams.size()); assertTrue(forwardParams.contains("forward-param-6-key")); assertTrue(forwardParams.contains("forward-param-7-key")); assertTrue(forwardParams.contains("forward-param-6-val")); assertTrue(forwardParams.contains("forward-param-7-val")); var extraParams = builtFirst.extraParams(); assertEquals(2, extraParams.size()); assertEquals("ex-auth-param-6-val", extraParams.get("ex-auth-param-6-key")); assertEquals("ex-auth-param-7-val", extraParams.get("ex-auth-param-7-key")); var scopes = builtFirst.scopes().orElseThrow(); assertEquals(3, scopes.size()); assertTrue(scopes.contains("scope-one")); assertTrue(scopes.contains("scope-two")); assertTrue(scopes.contains("scope-three")); assertEquals("scope-separator-654456", builtFirst.scopeSeparator().orElseThrow()); assertEquals(QUERY, builtFirst.responseMode().orElseThrow()); assertEquals("/session-expired-path-auth-yep", builtFirst.sessionExpiredPath().orElseThrow()); assertEquals("/error-path-auth-yep", builtFirst.errorPath().orElseThrow()); assertEquals("/redirect-path-auth-yep", builtFirst.redirectPath().orElseThrow()); assertFalse(builtFirst.removeRedirectParameters()); assertTrue(builtFirst.restorePathAfterRedirect()); assertTrue(builtFirst.verifyAccessToken()); assertTrue(builtFirst.forceRedirectHttpsScheme().orElseThrow()); assertTrue(builtFirst.nonceRequired()); assertFalse(builtFirst.addOpenidScope().orElseThrow()); assertTrue(builtFirst.cookieForceSecure()); assertEquals("cookie-suffix-auth-whatever", builtFirst.cookieSuffix().orElse(null)); assertEquals("/cookie-path-auth-whatever", builtFirst.cookiePath()); assertEquals("cookie-path-header-auth-whatever", builtFirst.cookiePathHeader().orElseThrow()); assertEquals("cookie-domain-auth-whatever", builtFirst.cookieDomain().orElseThrow()); assertEquals(CookieSameSite.NONE, builtFirst.cookieSameSite()); assertFalse(builtFirst.allowMultipleCodeFlows()); assertTrue(builtFirst.failOnMissingStateParam()); assertTrue(builtFirst.userInfoRequired().orElseThrow()); assertEquals(77, builtFirst.sessionAgeExtension().toMinutes()); assertEquals(88, builtFirst.stateCookieAge().toMinutes()); assertFalse(builtFirst.javaScriptAutoRedirect()); assertFalse(builtFirst.idTokenRequired().orElseThrow()); assertEquals(357, builtFirst.internalIdTokenLifespan().orElseThrow().toMinutes()); assertTrue(builtFirst.pkceRequired().orElseThrow()); assertEquals("state-secret-auth-whatever", builtFirst.stateSecret().orElse(null)); var second = new AuthenticationConfigBuilder(config1Builder).scopes("scope-four").responseMode(FORM_POST) .extraParams(Map.of("ho", "hey")).stateSecret("my-state-secret"); var config2 = second.end().build(); var builtSecond = config2.authentication(); forwardParams = builtSecond.forwardParams().orElseThrow(); assertEquals(4, forwardParams.size()); assertTrue(forwardParams.contains("forward-param-6-key")); assertTrue(forwardParams.contains("forward-param-7-key")); assertTrue(forwardParams.contains("forward-param-6-val")); assertTrue(forwardParams.contains("forward-param-7-val")); extraParams = builtSecond.extraParams(); assertEquals(3, extraParams.size()); assertEquals("ex-auth-param-6-val", extraParams.get("ex-auth-param-6-key")); assertEquals("ex-auth-param-7-val", extraParams.get("ex-auth-param-7-key")); assertEquals("hey", extraParams.get("ho")); scopes = builtSecond.scopes().orElseThrow(); assertEquals(4, scopes.size()); assertTrue(scopes.contains("scope-one")); assertTrue(scopes.contains("scope-two")); assertTrue(scopes.contains("scope-three")); assertTrue(scopes.contains("scope-four")); assertEquals("scope-separator-654456", builtSecond.scopeSeparator().orElseThrow()); assertEquals(FORM_POST, builtSecond.responseMode().orElseThrow()); assertEquals("/session-expired-path-auth-yep", builtSecond.sessionExpiredPath().orElseThrow()); assertEquals("/error-path-auth-yep", builtSecond.errorPath().orElseThrow()); assertEquals("/redirect-path-auth-yep", builtSecond.redirectPath().orElseThrow()); assertFalse(builtSecond.removeRedirectParameters()); assertTrue(builtSecond.restorePathAfterRedirect()); assertTrue(builtSecond.verifyAccessToken()); assertTrue(builtSecond.forceRedirectHttpsScheme().orElseThrow()); assertTrue(builtSecond.nonceRequired()); assertFalse(builtSecond.addOpenidScope().orElseThrow()); assertTrue(builtSecond.cookieForceSecure()); assertEquals("cookie-suffix-auth-whatever", builtSecond.cookieSuffix().orElse(null)); assertEquals("/cookie-path-auth-whatever", builtSecond.cookiePath()); assertEquals("cookie-path-header-auth-whatever", builtSecond.cookiePathHeader().orElseThrow()); assertEquals("cookie-domain-auth-whatever", builtSecond.cookieDomain().orElseThrow()); assertEquals(CookieSameSite.NONE, builtSecond.cookieSameSite()); assertFalse(builtSecond.allowMultipleCodeFlows()); assertTrue(builtSecond.failOnMissingStateParam()); assertTrue(builtSecond.userInfoRequired().orElseThrow()); assertEquals(77, builtSecond.sessionAgeExtension().toMinutes()); assertEquals(88, builtSecond.stateCookieAge().toMinutes()); assertFalse(builtSecond.javaScriptAutoRedirect()); assertFalse(builtSecond.idTokenRequired().orElseThrow()); assertEquals(357, builtSecond.internalIdTokenLifespan().orElseThrow().toMinutes()); assertTrue(builtSecond.pkceRequired().orElseThrow()); assertEquals("my-state-secret", builtSecond.stateSecret().orElse(null)); } @Test public void testCodeGrantBuilder() { var first = new CodeGrantBuilder() .extraParams(Map.of("code-grant-param", "code-grant-param-val")) .headers(Map.of("code-grant-header", "code-grant-header-val")) .build(); var config1 = new OidcTenantConfigBuilder().tenantId("7").codeGrant(first).build(); var builtFirst = config1.codeGrant(); assertEquals(1, builtFirst.extraParams().size()); assertEquals("code-grant-param-val", builtFirst.extraParams().get("code-grant-param")); assertEquals(1, builtFirst.headers().size()); assertEquals("code-grant-header-val", builtFirst.headers().get("code-grant-header")); var config2 = new CodeGrantBuilder(OidcTenantConfig.builder(config1)) .extraParam("1", "one") .header("2", "two") .end() .build(); var builtSecond = config2.codeGrant(); assertEquals(2, builtSecond.extraParams().size()); assertEquals("code-grant-param-val", builtSecond.extraParams().get("code-grant-param")); assertEquals("one", builtSecond.extraParams().get("1")); assertEquals(2, builtSecond.headers().size()); assertEquals("code-grant-header-val", builtSecond.headers().get("code-grant-header")); assertEquals("two", builtSecond.headers().get("2")); var config3 = OidcTenantConfig.builder(config2).codeGrant(Map.of("new", "header")).build(); var builtThird = config3.codeGrant(); assertEquals(2, builtThird.extraParams().size()); assertEquals("code-grant-param-val", builtThird.extraParams().get("code-grant-param")); assertEquals("one", builtThird.extraParams().get("1")); assertEquals(3, builtThird.headers().size()); assertEquals("code-grant-header-val", builtThird.headers().get("code-grant-header")); assertEquals("two", builtThird.headers().get("2")); assertEquals("header", builtThird.headers().get("new")); var config4 = OidcTenantConfig.builder(config3).codeGrant(Map.of("old", "header"), Map.of("new", "extra")).build(); var builtFourth = config4.codeGrant(); assertEquals(3, builtFourth.extraParams().size()); assertEquals("code-grant-param-val", builtFourth.extraParams().get("code-grant-param")); assertEquals("one", builtFourth.extraParams().get("1")); assertEquals("extra", builtFourth.extraParams().get("new")); assertEquals(4, builtFourth.headers().size()); assertEquals("code-grant-header-val", builtFourth.headers().get("code-grant-header")); assertEquals("two", builtFourth.headers().get("2")); assertEquals("header", builtFourth.headers().get("new")); assertEquals("header", builtFourth.headers().get("old")); assertEquals("7", config4.tenantId().orElse(null)); } @Test public void testTokenStateManagerBuilder() { var first = new TokenStateManagerBuilder() .strategy(Strategy.ID_REFRESH_TOKENS) .splitTokens() .encryptionRequired(false) .encryptionSecret("1-enc-secret") .encryptionAlgorithm(EncryptionAlgorithm.DIR) .build(); var config1 = new OidcTenantConfigBuilder().tenantId("6").tokenStateManager(first).build(); var builtFirst = config1.tokenStateManager(); assertEquals(Strategy.ID_REFRESH_TOKENS, builtFirst.strategy()); assertTrue(builtFirst.splitTokens()); assertFalse(builtFirst.encryptionRequired()); assertEquals("1-enc-secret", builtFirst.encryptionSecret().orElse(null)); assertEquals(EncryptionAlgorithm.DIR, builtFirst.encryptionAlgorithm()); var second = new TokenStateManagerBuilder(new OidcTenantConfigBuilder(config1)) .encryptionRequired() .splitTokens(false); var config2 = second.end().build(); var builtSecond = config2.tokenStateManager(); assertEquals(Strategy.ID_REFRESH_TOKENS, builtSecond.strategy()); assertFalse(builtSecond.splitTokens()); assertTrue(builtSecond.encryptionRequired()); assertEquals("1-enc-secret", builtSecond.encryptionSecret().orElse(null)); assertEquals(EncryptionAlgorithm.DIR, builtSecond.encryptionAlgorithm()); assertEquals("6", config2.tenantId().orElse(null)); } @Test public void testJwksBuilder() { var first = new JwksBuilder() .resolveEarly(false) .cacheSize(67) .cacheTimeToLive(Duration.ofMinutes(5784)) .cleanUpTimerInterval(Duration.ofMinutes(47568)) .tryAll() .build(); var config1 = new OidcTenantConfigBuilder().tenantId("87").jwks(first).build(); var builtFirst = config1.jwks(); assertTrue(builtFirst.tryAll()); assertFalse(builtFirst.resolveEarly()); assertEquals(67, builtFirst.cacheSize()); assertEquals(5784, builtFirst.cacheTimeToLive().toMinutes()); assertEquals(47568, builtFirst.cleanUpTimerInterval().orElseThrow().toMinutes()); var config2 = new JwksBuilder(new OidcTenantConfigBuilder(config1)) .resolveEarly() .tryAll(false) .end().build(); var builtSecond = config2.jwks(); assertFalse(builtSecond.tryAll()); assertTrue(builtSecond.resolveEarly()); assertEquals(67, builtSecond.cacheSize()); assertEquals(5784, builtSecond.cacheTimeToLive().toMinutes()); assertEquals(47568, builtSecond.cleanUpTimerInterval().orElseThrow().toMinutes()); assertEquals("87", config2.tenantId().orElse(null)); } }
OidcTenantConfigBuilderTest
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/codec/AbstractDataBufferDecoder.java
{ "start": 1871, "end": 4035 }
class ____<T> extends AbstractDecoder<T> { private int maxInMemorySize = 256 * 1024; protected AbstractDataBufferDecoder(MimeType... supportedMimeTypes) { super(supportedMimeTypes); } /** * Configure a limit on the number of bytes that can be buffered whenever * the input stream needs to be aggregated. This can be a result of * decoding to a single {@code DataBuffer}, * {@link java.nio.ByteBuffer ByteBuffer}, {@code byte[]}, * {@link org.springframework.core.io.Resource Resource}, {@code String}, etc. * It can also occur when splitting the input stream, for example, delimited text, * in which case the limit applies to data buffered between delimiters. * <p>By default this is set to 256K. * @param byteCount the max number of bytes to buffer, or -1 for unlimited * @since 5.1.11 */ public void setMaxInMemorySize(int byteCount) { this.maxInMemorySize = byteCount; } /** * Return the {@link #setMaxInMemorySize configured} byte count limit. * @since 5.1.11 */ public int getMaxInMemorySize() { return this.maxInMemorySize; } @Override public Flux<T> decode(Publisher<DataBuffer> input, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { return Flux.from(input).map(buffer -> Objects.requireNonNull(decodeDataBuffer(buffer, elementType, mimeType, hints))); } @Override public Mono<T> decodeToMono(Publisher<DataBuffer> input, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { return DataBufferUtils.join(input, this.maxInMemorySize).map(buffer -> Objects.requireNonNull(decodeDataBuffer(buffer, elementType, mimeType, hints))); } /** * How to decode a {@code DataBuffer} to the target element type. * @deprecated in favor of implementing * {@link #decode(DataBuffer, ResolvableType, MimeType, Map)} instead */ @Deprecated(since = "5.2") protected @Nullable T decodeDataBuffer(DataBuffer buffer, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { return decode(buffer, elementType, mimeType, hints); } }
AbstractDataBufferDecoder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LoadANonExistingNotFoundLazyBatchEntityTest.java
{ "start": 2219, "end": 5576 }
class ____ { private static final int NUMBER_OF_ENTITIES = 20; @Test @JiraKey("HHH-11147") public void loadEntityWithNotFoundAssociation(SessionFactoryScope scope) { final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( (session) -> { List<Employee> employees = new ArrayList<>( NUMBER_OF_ENTITIES ); for ( int i = 0 ; i < NUMBER_OF_ENTITIES ; i++ ) { employees.add( session.getReference( Employee.class, i + 1 ) ); } for ( int i = 0 ; i < NUMBER_OF_ENTITIES ; i++ ) { Hibernate.initialize( employees.get( i ) ); assertNull( employees.get( i ).employer ); } } ); // A "not found" association cannot be batch fetched because // Employee#employer must be initialized immediately. // Enhanced proxies (and HibernateProxy objects) should never be created // for a "not found" association. assertEquals( 2 * NUMBER_OF_ENTITIES, statistics.getPrepareStatementCount() ); } @Test @JiraKey("HHH-11147") public void getEntityWithNotFoundAssociation(SessionFactoryScope scope) { final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( (session) -> { for ( int i = 0 ; i < NUMBER_OF_ENTITIES ; i++ ) { Employee employee = session.get( Employee.class, i + 1 ); assertNull( employee.employer ); } } ); // A "not found" association cannot be batch fetched because // Employee#employer must be initialized immediately. // Enhanced proxies (and HibernateProxy objects) should never be created // for a "not found" association. assertEquals( 2 * NUMBER_OF_ENTITIES, statistics.getPrepareStatementCount() ); } @Test @JiraKey("HHH-11147") public void updateNotFoundAssociationWithNew(SessionFactoryScope scope) { final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( (session) -> { for ( int i = 0; i < NUMBER_OF_ENTITIES; i++ ) { Employee employee = session.get( Employee.class, i + 1 ); Employer employer = new Employer(); employer.id = 2 * employee.id; employer.name = "Employer #" + employer.id; employee.employer = employer; } } ); scope.inTransaction( (session) -> { for ( int i = 0; i < NUMBER_OF_ENTITIES; i++ ) { Employee employee = session.get( Employee.class, i + 1 ); assertTrue( Hibernate.isInitialized( employee.employer ) ); assertEquals( employee.id * 2, employee.employer.id ); assertEquals( "Employer #" + employee.employer.id, employee.employer.name ); } } ); } @BeforeEach public void setUpData(SessionFactoryScope scope) { scope.inTransaction( session -> { for ( int i = 0; i < NUMBER_OF_ENTITIES; i++ ) { final Employee employee = new Employee(); employee.id = i + 1; employee.name = "Employee #" + employee.id; session.persist( employee ); } } ); scope.inTransaction( session -> { // Add "not found" associations session.createNativeQuery( "update Employee set employer_id = id" ).executeUpdate(); } ); } @AfterEach public void cleanupDate(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Entity(name = "Employee") public static
LoadANonExistingNotFoundLazyBatchEntityTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/log/LogThrottlingHelper.java
{ "start": 14802, "end": 15130 }
class ____ implements LogAction { public int getCount() { throw new IllegalStateException("Cannot be logged yet!"); } public SummaryStatistics getStats(int idx) { throw new IllegalStateException("Cannot be logged yet!"); } public boolean shouldLog() { return false; } } }
NoLogAction
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-data-mongodb/src/dockerTest/java/smoketest/data/mongodb/SampleDataMongoApplicationReactiveSslTests.java
{ "start": 1614, "end": 2517 }
class ____ { @Container @ServiceConnection @PemKeyStore(certificate = "classpath:ssl/test-client.crt", privateKey = "classpath:ssl/test-client.key") @PemTrustStore("classpath:ssl/test-ca.crt") static final MongoDBContainer mongoDb = TestImage.container(SecureMongoContainer.class); @Autowired private ReactiveMongoTemplate mongoTemplate; @Autowired private SampleReactiveRepository exampleRepository; @Test void testRepository() { SampleDocument exampleDocument = new SampleDocument(); exampleDocument.setText("Look, new @DataMongoTest!"); exampleDocument = this.exampleRepository.save(exampleDocument).block(Duration.ofSeconds(30)); assertThat(exampleDocument).isNotNull(); assertThat(exampleDocument.getId()).isNotNull(); assertThat(this.mongoTemplate.collectionExists("exampleDocuments").block(Duration.ofSeconds(30))).isTrue(); } }
SampleDataMongoApplicationReactiveSslTests
java
netty__netty
transport-classes-io_uring/src/main/java/io/netty/channel/uring/IoUringBufferRingConfig.java
{ "start": 7122, "end": 10233 }
class ____ { private short bgId = -1; private short bufferRingSize = -1; private int batchSize = -1; private boolean incremental = IoUring.isRegisterBufferRingIncSupported(); private IoUringBufferRingAllocator allocator; private boolean batchAllocation; /** * Set the buffer group id to use. * * @param bgId The buffer group id to use. * @return This builder. */ public Builder bufferGroupId(short bgId) { this.bgId = bgId; return this; } /** * Set the size of the ring. * * @param bufferRingSize The size of the ring. * @return This builder. */ public Builder bufferRingSize(short bufferRingSize) { this.bufferRingSize = bufferRingSize; return this; } /** * Set the size of the batch on how many buffers are added everytime we need to expand the buffer ring. * * @param batchSize The batch size. * @return This builder. */ public Builder batchSize(int batchSize) { this.batchSize = batchSize; return this; } /** * Set the {@link IoUringBufferRingAllocator} to use to allocate {@link ByteBuf}s. * * @param allocator The allocator. */ public Builder allocator(IoUringBufferRingAllocator allocator) { this.allocator = allocator; return this; } /** * Set allocation strategy that is used to allocate {@link ByteBuf}s. * * @param batchAllocation {@code true} if the ring should always be filled via a batch allocation or * {@code false} if we will try to allocate a new {@link ByteBuf} as soon * as we used a buffer from the ring. * @return This builder. */ public Builder batchAllocation(boolean batchAllocation) { this.batchAllocation = batchAllocation; return this; } /** * Set if <a href="https://github.com/axboe/liburing/wiki/ * What's-new-with-io_uring-in-6.11-and-6.12#incremental-provided-buffer-consumption">incremental mode</a> * should be used for the buffer ring. * * @param incremental {@code true} if incremental mode is used, {@code false} otherwise. * @return This builder. */ public Builder incremental(boolean incremental) { this.incremental = incremental; return this; } /** * Create a new {@link IoUringBufferRingConfig}. * * @return a new config. */ public IoUringBufferRingConfig build() { return new IoUringBufferRingConfig( bgId, bufferRingSize, batchSize, Integer.MAX_VALUE, incremental, allocator, batchAllocation); } } }
Builder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/shipping/OutputEmitter.java
{ "start": 1516, "end": 9860 }
class ____<T> implements ChannelSelector<SerializationDelegate<T>> { /** the shipping strategy used by this output emitter */ private final ShipStrategyType strategy; /** counter to go over channels round robin */ private int nextChannelToSendTo; /** the total number of output channels */ private int numberOfChannels; /** the comparator for hashing / sorting */ private final TypeComparator<T> comparator; private Object[][] partitionBoundaries; // the partition boundaries for range partitioning private DataDistribution distribution; // the data distribution to create the partition boundaries for range // partitioning private final Partitioner<Object> partitioner; private TypeComparator[] flatComparators; private Object[] keys; private Object[] extractedKeys; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Creates a new channel selector that uses the given strategy (broadcasting, partitioning, ...) * and uses the supplied task index perform a round robin distribution. * * @param strategy The distribution strategy to be used. */ public OutputEmitter(ShipStrategyType strategy, int indexInSubtaskGroup) { this(strategy, indexInSubtaskGroup, null, null, null); } /** * Creates a new channel selector that uses the given strategy (broadcasting, partitioning, ...) * and uses the supplied comparator to hash / compare records for partitioning them * deterministically. * * @param strategy The distribution strategy to be used. * @param comparator The comparator used to hash / compare the records. */ public OutputEmitter(ShipStrategyType strategy, TypeComparator<T> comparator) { this(strategy, 0, comparator, null, null); } @SuppressWarnings("unchecked") public OutputEmitter( ShipStrategyType strategy, int indexInSubtaskGroup, TypeComparator<T> comparator, Partitioner<?> partitioner, DataDistribution distribution) { if (strategy == null) { throw new NullPointerException(); } this.strategy = strategy; this.nextChannelToSendTo = indexInSubtaskGroup; this.comparator = comparator; this.partitioner = (Partitioner<Object>) partitioner; this.distribution = distribution; switch (strategy) { case PARTITION_CUSTOM: extractedKeys = new Object[1]; case FORWARD: case PARTITION_HASH: case PARTITION_RANDOM: case PARTITION_FORCED_REBALANCE: break; case PARTITION_RANGE: if (comparator != null) { this.flatComparators = comparator.getFlatComparators(); this.keys = new Object[flatComparators.length]; } break; case BROADCAST: break; default: throw new IllegalArgumentException( "Invalid shipping strategy for OutputEmitter: " + strategy.name()); } if (strategy == ShipStrategyType.PARTITION_CUSTOM && partitioner == null) { throw new NullPointerException( "Partitioner must not be null when the ship strategy is set to custom partitioning."); } } // ------------------------------------------------------------------------ // Channel Selection // ------------------------------------------------------------------------ @Override public void setup(int numberOfChannels) { this.numberOfChannels = numberOfChannels; } @Override public final int selectChannel(SerializationDelegate<T> record) { switch (strategy) { case FORWARD: return forward(); case PARTITION_RANDOM: case PARTITION_FORCED_REBALANCE: return robin(numberOfChannels); case PARTITION_HASH: return hashPartitionDefault(record.getInstance(), numberOfChannels); case PARTITION_CUSTOM: return customPartition(record.getInstance(), numberOfChannels); case PARTITION_RANGE: return rangePartition(record.getInstance(), numberOfChannels); default: throw new UnsupportedOperationException( "Unsupported distribution strategy: " + strategy.name()); } } @Override public boolean isBroadcast() { if (strategy == ShipStrategyType.BROADCAST) { return true; } else { return false; } } // -------------------------------------------------------------------------------------------- private int forward() { return 0; } private int robin(int numberOfChannels) { int nextChannel = nextChannelToSendTo; if (nextChannel >= numberOfChannels) { if (nextChannel == numberOfChannels) { nextChannel = 0; } else { nextChannel %= numberOfChannels; } } nextChannelToSendTo = nextChannel + 1; return nextChannel; } private int hashPartitionDefault(T record, int numberOfChannels) { int hash = this.comparator.hash(record); return MathUtils.murmurHash(hash) % numberOfChannels; } private int rangePartition(final T record, int numberOfChannels) { if (this.partitionBoundaries == null) { this.partitionBoundaries = new Object[numberOfChannels - 1][]; for (int i = 0; i < numberOfChannels - 1; i++) { this.partitionBoundaries[i] = this.distribution.getBucketBoundary(i, numberOfChannels); } } if (numberOfChannels == this.partitionBoundaries.length + 1) { final Object[][] boundaries = this.partitionBoundaries; // bin search the bucket int low = 0; int high = this.partitionBoundaries.length - 1; while (low <= high) { final int mid = (low + high) >>> 1; final int result = compareRecordAndBoundary(record, boundaries[mid]); if (result > 0) { low = mid + 1; } else if (result < 0) { high = mid - 1; } else { return mid; } } // key not found, but the low index is the target bucket, since the boundaries are the // upper bound return low; } else { throw new IllegalStateException( "The number of channels to partition among is inconsistent with the partitioners state."); } } private int customPartition(T record, int numberOfChannels) { if (extractedKeys == null) { extractedKeys = new Object[1]; } try { if (comparator.extractKeys(record, extractedKeys, 0) == 1) { final Object key = extractedKeys[0]; return partitioner.partition(key, numberOfChannels); } else { throw new RuntimeException( "Inconsistency in the key comparator - comparator extracted more than one field."); } } catch (Throwable t) { throw new RuntimeException("Error while calling custom partitioner.", t); } } private final int compareRecordAndBoundary(T record, Object[] boundary) { this.comparator.extractKeys(record, keys, 0); if (flatComparators.length != keys.length || flatComparators.length > boundary.length) { throw new RuntimeException( "Can not compare keys with boundary due to mismatched length."); } for (int i = 0; i < flatComparators.length; i++) { int result = flatComparators[i].compare(keys[i], boundary[i]); if (result != 0) { return result; } } return 0; } }
OutputEmitter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cdi/general/hibernatesearch/delayed/HibernateSearchDelayedCdiSupportTest.java
{ "start": 3153, "end": 11304 }
class ____ { @Test @CdiContainer(beanClasses = { TheApplicationScopedBean.class, TheNamedApplicationScopedBean.class, TheMainNamedApplicationScopedBeanImpl.class, TheAlternativeNamedApplicationScopedBeanImpl.class, TheSharedApplicationScopedBean.class, TheDependentBean.class, TheNamedDependentBean.class, TheMainNamedDependentBeanImpl.class, TheAlternativeNamedDependentBeanImpl.class, TheNestedDependentBean.class, TheNonHibernateBeanConsumer.class }) public void testIt(CdiContainerScope cdiContainerScope) { final TheFallbackBeanInstanceProducer fallbackBeanInstanceProducer = new TheFallbackBeanInstanceProducer(); final HibernateSearchSimulatedIntegrator beanConsumingIntegrator = new HibernateSearchSimulatedIntegrator( fallbackBeanInstanceProducer ); try (SeContainer cdiContainer = cdiContainerScope.getContainer()) { // Simulate CDI bean consumers outside of Hibernate ORM Instance<TheNonHibernateBeanConsumer> nonHibernateBeanConsumerInstance = cdiContainer.getBeanManager().createInstance().select( TheNonHibernateBeanConsumer.class ); nonHibernateBeanConsumerInstance.get(); // Expect the shared bean to have been instantiated already, but only that one assertEquals( 0, Monitor.theApplicationScopedBean().currentInstantiationCount() ); assertEquals( 0, Monitor.theMainNamedApplicationScopedBean().currentInstantiationCount() ); assertEquals( 0, Monitor.theAlternativeNamedApplicationScopedBean().currentInstantiationCount() ); assertEquals( 1, Monitor.theSharedApplicationScopedBean().currentInstantiationCount() ); assertEquals( 0, Monitor.theDependentBean().currentInstantiationCount() ); assertEquals( 0, Monitor.theMainNamedDependentBean().currentInstantiationCount() ); assertEquals( 0, Monitor.theAlternativeNamedDependentBean().currentInstantiationCount() ); assertEquals( 0, fallbackBeanInstanceProducer.currentInstantiationCount() ); assertEquals( 0, fallbackBeanInstanceProducer.currentNamedInstantiationCount() ); // Nested dependent bean: 1 instance per bean that depends on it assertEquals( 1, Monitor.theNestedDependentBean().currentInstantiationCount() ); try (BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder() .applyIntegrator( beanConsumingIntegrator ) .build()) { try (StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr ) .applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP ) .applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() ) .applySetting( AvailableSettings.DELAY_CDI_ACCESS, "true" ) .build()) { try (SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( ssr ) .addAnnotatedClass( TheEntity.class ) .buildMetadata() .getSessionFactoryBuilder() .build()) { // Here, the HibernateSearchSimulatedIntegrator has just been integrated and has requested beans // See HibernateSearchSimulatedIntegrator for a detailed list of requested beans beanConsumingIntegrator.ensureInstancesInitialized(); // Application scope: maximum 1 instance as soon as at least one was requested assertEquals( 1, Monitor.theApplicationScopedBean().currentInstantiationCount() ); assertEquals( 1, Monitor.theMainNamedApplicationScopedBean().currentInstantiationCount() ); assertEquals( 0, Monitor.theAlternativeNamedApplicationScopedBean().currentInstantiationCount() ); assertEquals( 1, Monitor.theSharedApplicationScopedBean().currentInstantiationCount() ); // Dependent scope: 1 instance per bean we requested explicitly assertEquals( 2, Monitor.theDependentBean().currentInstantiationCount() ); assertEquals( 2, Monitor.theMainNamedDependentBean().currentInstantiationCount() ); assertEquals( 0, Monitor.theAlternativeNamedDependentBean().currentInstantiationCount() ); // Reflection-instantiated: 1 instance per bean we requested explicitly assertEquals( 2, fallbackBeanInstanceProducer.currentInstantiationCount() ); assertEquals( 2, fallbackBeanInstanceProducer.currentNamedInstantiationCount() ); // Nested dependent bean: 1 instance per bean that depends on it assertEquals( 7, Monitor.theNestedDependentBean().currentInstantiationCount() ); // Expect one PostConstruct call per CDI bean instance assertEquals( 1, Monitor.theApplicationScopedBean().currentPostConstructCount() ); assertEquals( 1, Monitor.theMainNamedApplicationScopedBean().currentPostConstructCount() ); assertEquals( 0, Monitor.theAlternativeNamedApplicationScopedBean().currentPostConstructCount() ); assertEquals( 1, Monitor.theSharedApplicationScopedBean().currentPostConstructCount() ); assertEquals( 2, Monitor.theDependentBean().currentPostConstructCount() ); assertEquals( 2, Monitor.theMainNamedDependentBean().currentPostConstructCount() ); assertEquals( 0, Monitor.theAlternativeNamedDependentBean().currentPostConstructCount() ); assertEquals( 7, Monitor.theNestedDependentBean().currentPostConstructCount() ); // Expect no PreDestroy call yet assertEquals( 0, Monitor.theApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theMainNamedApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theAlternativeNamedApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theSharedApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theDependentBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theMainNamedDependentBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theAlternativeNamedDependentBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theNestedDependentBean().currentPreDestroyCount() ); } } } // Here, the NonRegistryManagedBeanConsumingIntegrator has just been disintegrated and has released beans // release() should have an effect on exclusively used application-scoped beans assertEquals( 1, Monitor.theApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 1, Monitor.theMainNamedApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theAlternativeNamedApplicationScopedBean().currentPreDestroyCount() ); // release() should have no effect on shared application-scoped beans (they will be released when they are no longer used) assertEquals( 0, Monitor.theSharedApplicationScopedBean().currentPreDestroyCount() ); // release() should have an effect on dependent-scoped beans assertEquals( 2, Monitor.theDependentBean().currentPreDestroyCount() ); assertEquals( 2, Monitor.theMainNamedDependentBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theAlternativeNamedDependentBean().currentPreDestroyCount() ); // The nested dependent bean instances should have been destroyed along with the beans that depend on them // (the instances used in application-scoped beans should not have been destroyed) assertEquals( 6, Monitor.theNestedDependentBean().currentPreDestroyCount() ); } // After the CDI context has ended, PreDestroy should have been called on every created bean // (see the assertions about instantiations above for an explanation of the expected counts) assertEquals( 1, Monitor.theApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 1, Monitor.theMainNamedApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theAlternativeNamedApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 1, Monitor.theSharedApplicationScopedBean().currentPreDestroyCount() ); assertEquals( 2, Monitor.theDependentBean().currentPreDestroyCount() ); assertEquals( 2, Monitor.theMainNamedDependentBean().currentPreDestroyCount() ); assertEquals( 0, Monitor.theAlternativeNamedDependentBean().currentPreDestroyCount() ); assertEquals( 7, Monitor.theNestedDependentBean().currentPreDestroyCount() ); } }
HibernateSearchDelayedCdiSupportTest
java
google__auto
value/src/test/java/com/google/auto/value/processor/GeneratedDoesNotExistTest.java
{ "start": 1886, "end": 4285 }
class ____ { private static final ImmutableList<String> STANDARD_OPTIONS = ImmutableList.of("-A" + Nullables.NULLABLE_OPTION + "="); @Parameters(name = "{0}") public static ImmutableList<Object[]> data() { ImmutableList.Builder<Object[]> params = ImmutableList.builder(); int release = SourceVersion.latestSupported().ordinal(); // 8 for Java 8, etc. if (release == 8) { params.add(new Object[] {STANDARD_OPTIONS, "javax.annotation.Generated"}); } else { params.add( new Object[] { STANDARD_OPTIONS, "javax.annotation.processing.Generated", }); if (release < 20) { // starting with 20 we get a warning about --release 8 going away soon params.add( new Object[] { ImmutableList.<String>builder() .addAll(STANDARD_OPTIONS) .add("--release", "8") .build(), "javax.annotation.Generated", }); } } return params.build(); } private final ImmutableList<String> javacOptions; private final String expectedAnnotation; public GeneratedDoesNotExistTest(ImmutableList<String> javacOptions, String expectedAnnotation) { this.javacOptions = javacOptions; this.expectedAnnotation = expectedAnnotation; } // The classes here are basically just rigmarole to ensure that // Types.getTypeElement("javax.annotation.Generated") returns null, and to check that something // called that. We want a Processor that forwards everything to AutoValueProcessor, except that // the init(ProcessingEnvironment) method should forward a ProcessingEnvironment that filters // out the Generated class. So that ProcessingEnvironment forwards everything to the real // ProcessingEnvironment, except the ProcessingEnvironment.getElementUtils() method. That method // returns an Elements object that forwards everything to the real Elements except // getTypeElement("javax.annotation.Generated") and // getTypeElement("javax.annotation.processing.Generated"). private static final ImmutableSet<String> GENERATED_ANNOTATIONS = ImmutableSet.of("javax.annotation.Generated", "javax.annotation.processing.Generated"); /** * InvocationHandler that forwards every method to an original object, except methods where there * is an implementation in this
GeneratedDoesNotExistTest
java
google__guice
extensions/assistedinject/test/com/google/inject/assistedinject/FactoryProviderTest.java
{ "start": 17304, "end": 18122 }
interface ____ { WildcardCollection create(Collection<?> items); } @AssistedInject public WildcardCollection(@SuppressWarnings("unused") @Assisted Collection<?> items) {} } public void testWildcardGenerics() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(WildcardCollection.Factory.class) .toProvider( FactoryProvider.newFactory( WildcardCollection.Factory.class, WildcardCollection.class)); } }); WildcardCollection.Factory factory = injector.getInstance(WildcardCollection.Factory.class); factory.create(Collections.emptyList()); } public static
Factory
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AutoValueSubclassLeakedTest.java
{ "start": 2340, "end": 2868 }
class ____ { abstract Builder setFoo(int i); abstract Foo build(); } public static Builder builder() { return new AutoValue_Test_Foo.Builder(); } } } """) .doTest(); } @Test public void negative() { helper .addSourceLines( "Test.java", """ package test; import com.google.auto.value.AutoValue;
Builder
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/MinBytesRefAggregator.java
{ "start": 1192, "end": 2582 }
class ____ { private static boolean isBetter(BytesRef value, BytesRef otherValue) { return value.compareTo(otherValue) < 0; } public static SingleState initSingle(DriverContext driverContext) { return new SingleState(driverContext.breaker()); } public static void combine(SingleState state, BytesRef value) { state.add(value); } public static void combineIntermediate(SingleState state, BytesRef value, boolean seen) { if (seen) { combine(state, value); } } public static Block evaluateFinal(SingleState state, DriverContext driverContext) { return state.toBlock(driverContext); } public static GroupingState initGrouping(DriverContext driverContext) { return new GroupingState(driverContext.bigArrays(), driverContext.breaker()); } public static void combine(GroupingState state, int groupId, BytesRef value) { state.add(groupId, value); } public static void combineIntermediate(GroupingState state, int groupId, BytesRef value, boolean seen) { if (seen) { state.add(groupId, value); } } public static Block evaluateFinal(GroupingState state, IntVector selected, GroupingAggregatorEvaluationContext ctx) { return state.toBlock(selected, ctx.driverContext()); } public static
MinBytesRefAggregator
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/PhysicalSlotProvider.java
{ "start": 1076, "end": 2223 }
interface ____ { /** * Submit requests to allocate physical slots. * * <p>The physical slot can be either allocated from the slots, which are already available for * the job, or a new one can be requested from the resource manager. * * @param physicalSlotRequests physicalSlotRequest slot requirements * @return futures of the allocated slots */ Map<SlotRequestId, CompletableFuture<PhysicalSlotRequest.Result>> allocatePhysicalSlots( Collection<PhysicalSlotRequest> physicalSlotRequests); /** * Cancels the slot request with the given {@link SlotRequestId}. * * <p>If the request is already fulfilled with a physical slot, the slot will be released. * * @param slotRequestId identifying the slot request to cancel * @param cause of the cancellation */ void cancelSlotRequest(SlotRequestId slotRequestId, Throwable cause); /** * Disables batch slot request timeout check. Invoked when someone else wants to take over the * timeout check responsibility. */ void disableBatchSlotRequestTimeoutCheck(); }
PhysicalSlotProvider
java
junit-team__junit5
junit-platform-testkit/src/main/java/org/junit/platform/testkit/engine/TerminationInfo.java
{ "start": 1020, "end": 4839 }
class ____ { // --- Factories ----------------------------------------------------------- /** * Create a <em>skipped</em> {@code TerminationInfo} instance for the * supplied reason. * * @param reason the reason the execution was skipped; may be {@code null} * @return the created {@code TerminationInfo}; never {@code null} * @see #executed(TestExecutionResult) */ public static TerminationInfo skipped(@Nullable String reason) { return new TerminationInfo(true, reason, null); } /** * Create an <em>executed</em> {@code TerminationInfo} instance for the * supplied {@link TestExecutionResult}. * * @param testExecutionResult the result of the execution; never {@code null} * @return the created {@code TerminationInfo}; never {@code null} * @see #skipped(String) */ public static TerminationInfo executed(TestExecutionResult testExecutionResult) { Preconditions.notNull(testExecutionResult, "TestExecutionResult must not be null"); return new TerminationInfo(false, null, testExecutionResult); } // ------------------------------------------------------------------------- private final boolean skipped; private final @Nullable String skipReason; private final @Nullable TestExecutionResult testExecutionResult; private TerminationInfo(boolean skipped, @Nullable String skipReason, @Nullable TestExecutionResult testExecutionResult) { boolean executed = (testExecutionResult != null); Preconditions.condition((skipped ^ executed), "TerminationInfo must represent either a skipped execution or a TestExecutionResult but not both"); this.skipped = skipped; this.skipReason = skipReason; this.testExecutionResult = testExecutionResult; } /** * Determine if this {@code TerminationInfo} represents a skipped execution. * * @return {@code true} if this this {@code TerminationInfo} represents a * skipped execution */ public boolean skipped() { return this.skipped; } /** * Determine if this {@code TerminationInfo} does not represent a skipped * execution. * * @return {@code true} if this this {@code TerminationInfo} does not * represent a skipped execution */ public boolean notSkipped() { return !skipped(); } /** * Determine if this {@code TerminationInfo} represents a completed execution. * * @return {@code true} if this this {@code TerminationInfo} represents a * completed execution */ public boolean executed() { return (this.testExecutionResult != null); } /** * Get the reason the execution was skipped. * * @return the reason the execution was skipped * @throws UnsupportedOperationException if this {@code TerminationInfo} * does not represent a skipped execution */ public @Nullable String getSkipReason() throws UnsupportedOperationException { if (skipped()) { return this.skipReason; } // else throw new UnsupportedOperationException("No skip reason contained in this TerminationInfo"); } /** * Get the {@link TestExecutionResult} for the completed execution. * * @return the result of the completed execution * @throws UnsupportedOperationException if this {@code TerminationInfo} * does not represent a completed execution */ public TestExecutionResult getExecutionResult() throws UnsupportedOperationException { if (this.testExecutionResult != null) { return this.testExecutionResult; } // else throw new UnsupportedOperationException("No TestExecutionResult contained in this TerminationInfo"); } @Override public String toString() { ToStringBuilder builder = new ToStringBuilder(this); if (skipped()) { builder.append("skipped", true).append("reason", this.skipReason); } else { builder.append("executed", true).append("result", this.testExecutionResult); } return builder.toString(); } }
TerminationInfo
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java
{ "start": 526, "end": 715 }
class ____ { private final Class<?> clazz; /** * Create a new InjectMocksScanner for the given clazz on the given instance * * @param clazz Current
InjectMocksScanner
java
google__dagger
javatests/dagger/spi/SpiPluginTest.java
{ "start": 18432, "end": 18579 }
class ____ it easier to compile all of the files in the test // multiple times with different options to single out each error private static
makes
java
google__error-prone
check_api/src/main/java/com/google/errorprone/VisitorState.java
{ "start": 14565, "end": 16051 }
class ____ for a given Name. * * @param name the name to look up, which must be in binary form (i.e. with $ for nested classes). */ public @Nullable ClassSymbol getSymbolFromName(Name name) { boolean modular = sharedState.modules.getDefaultModule() != getSymtab().noModule; if (!modular) { return getSymbolFromString(getSymtab().noModule, name); } for (ModuleSymbol msym : sharedState.modules.allModules()) { ClassSymbol result = getSymbolFromString(msym, name); if (result != null) { // TODO(cushon): the path where we iterate over all modules is probably slow. // Try to learn some lessons from JDK-8189747, and consider disallowing this case and // requiring users to call the getSymbolFromString(ModuleSymbol, Name) overload instead. return result; } } return null; } public @Nullable ClassSymbol getSymbolFromString(ModuleSymbol msym, Name name) { ClassSymbol result = getSymtab().getClass(msym, name); if (result == null || result.kind == Kind.ERR || !result.exists()) { return null; } try { result.complete(); } catch (CompletionFailure failure) { // Ignoring completion error is problematic in general, but in this case we're ignoring a // completion error for a type that was directly requested, not one that was discovered // during the compilation. return null; } return result; } /** * Given a canonical
symbol
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/qualifiers/multiple/MultipleQualifierSpec.java
{ "start": 456, "end": 1428 }
class ____ { @Test void testQualifiers() { try (ApplicationContext context = ApplicationContext.run()) { final MyBean bean = context.getBean(MyBean.class); assertTrue(bean.asyncCreditCartProcessor instanceof AsyncCreditCardProcessor); assertSame(bean.asyncCreditCartProcessor, bean.fromCtorAsyncCreditCartProcessor); assertTrue(bean.syncCreditCartProcessor instanceof CreditCardProcessor); assertSame(bean.syncCreditCartProcessor, bean.fromCtorSyncCreditCartProcessor); assertTrue(bean.asyncBankTransferProcessor instanceof AsyncBankTransferProcessor); assertSame(bean.asyncBankTransferProcessor, bean.fromCtorAsyncBankTransferProcessor); assertTrue(bean.syncBankTransferProcessor instanceof BankTransferProcessor); assertSame(bean.syncBankTransferProcessor, bean.fromCtorSyncBankTransferProcessor); } } } @Singleton
MultipleQualifierSpec
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/ShardLimitValidator.java
{ "start": 1520, "end": 1974 }
class ____ the logic used to check the cluster-wide shard limit before shards are created and ensuring that the limit is * updated correctly on setting updates, etc. * * NOTE: This is the limit applied at *shard creation time*. If you are looking for the limit applied at *allocation* time, which is * controlled by a different setting, * see {@link org.elasticsearch.cluster.routing.allocation.decider.ShardsLimitAllocationDecider}. */ public
contains
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java
{ "start": 21574, "end": 21982 }
class ____ { void f(Method m) { // BUG: Diagnostic contains: getDeclaringClass m.getClass(); } } """) .doTest(); } @Test public void positive_beanDescriptorGetClass() { testHelper .addSourceLines( "Test.java", """ import java.beans.BeanDescriptor;
Test
java
apache__flink
flink-state-backends/flink-statebackend-forst/src/main/java/org/apache/flink/state/forst/ForStDBMultiRawMergePutRequest.java
{ "start": 1261, "end": 1996 }
class ____<K, N, V> extends ForStDBPutRequest<K, N, V> { final Collection<byte[]> rawValue; ForStDBMultiRawMergePutRequest( ContextKey<K, N> key, Collection<byte[]> value, ForStInnerTable<K, N, V> table, InternalAsyncFuture<Void> future) { super(key, null, true, table, future); this.rawValue = value; } @Override public void process(ForStDBWriteBatchWrapper writeBatchWrapper, RocksDB db) throws IOException, RocksDBException { byte[] key = buildSerializedKey(); for (byte[] value : rawValue) { writeBatchWrapper.merge(table.getColumnFamilyHandle(), key, value); } } }
ForStDBMultiRawMergePutRequest
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/bind/annotation/ControllerMappingReflectiveProcessor.java
{ "start": 1977, "end": 4882 }
class ____ implements ReflectiveProcessor { private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar(); @Override public void registerReflectionHints(ReflectionHints hints, AnnotatedElement element) { if (element instanceof Class<?> type) { registerTypeHints(hints, type); } else if (element instanceof Method method) { registerMethodHints(hints, method); } } protected final BindingReflectionHintsRegistrar getBindingRegistrar() { return this.bindingRegistrar; } protected void registerTypeHints(ReflectionHints hints, Class<?> type) { hints.registerType(type); } protected void registerMethodHints(ReflectionHints hints, Method method) { hints.registerMethod(method, ExecutableMode.INVOKE); Class<?> declaringClass = method.getDeclaringClass(); if (KotlinDetector.isKotlinType(declaringClass)) { ReflectionUtils.doWithMethods(declaringClass, m -> hints.registerMethod(m, ExecutableMode.INVOKE), m -> m.getName().equals(method.getName() + "$default")); } for (Parameter parameter : method.getParameters()) { registerParameterTypeHints(hints, MethodParameter.forParameter(parameter)); } registerReturnTypeHints(hints, MethodParameter.forExecutable(method, -1)); } protected void registerParameterTypeHints(ReflectionHints hints, MethodParameter methodParameter) { if (methodParameter.hasParameterAnnotation(RequestBody.class) || methodParameter.hasParameterAnnotation(ModelAttribute.class) || methodParameter.hasParameterAnnotation(RequestPart.class)) { this.bindingRegistrar.registerReflectionHints(hints, methodParameter.getGenericParameterType()); } else if (HttpEntity.class.isAssignableFrom(methodParameter.getParameterType())) { Type httpEntityType = getHttpEntityType(methodParameter); if (httpEntityType != null) { this.bindingRegistrar.registerReflectionHints(hints, httpEntityType); } } } protected void registerReturnTypeHints(ReflectionHints hints, MethodParameter returnTypeParameter) { if (AnnotatedElementUtils.hasAnnotation(returnTypeParameter.getContainingClass(), ResponseBody.class) || returnTypeParameter.hasMethodAnnotation(ResponseBody.class)) { this.bindingRegistrar.registerReflectionHints(hints, returnTypeParameter.getGenericParameterType()); } else if (HttpEntity.class.isAssignableFrom(returnTypeParameter.getParameterType())) { Type httpEntityType = getHttpEntityType(returnTypeParameter); if (httpEntityType != null) { this.bindingRegistrar.registerReflectionHints(hints, httpEntityType); } } } private @Nullable Type getHttpEntityType(MethodParameter parameter) { MethodParameter nestedParameter = parameter.nested(); return (nestedParameter.getNestedParameterType() == nestedParameter.getParameterType() ? null : nestedParameter.getNestedParameterType()); } }
ControllerMappingReflectiveProcessor
java
google__guava
android/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java
{ "start": 6109, "end": 7136 }
class ____ implements TestMapGenerator<Class, Impl> { @Override public Class<?>[] createKeyArray(int length) { return new Class<?>[length]; } @Override public Impl[] createValueArray(int length) { return new Impl[length]; } @Override public SampleElements<Entry<Class, Impl>> samples() { return new SampleElements<>( immutableEntry((Class) One.class, new Impl(1)), immutableEntry((Class) Two.class, new Impl(2)), immutableEntry((Class) Three.class, new Impl(3)), immutableEntry((Class) Four.class, new Impl(4)), immutableEntry((Class) Five.class, new Impl(5))); } @Override @SuppressWarnings("unchecked") public Entry<Class, Impl>[] createArray(int length) { return (Entry<Class, Impl>[]) new Entry<?, ?>[length]; } @Override public Iterable<Entry<Class, Impl>> order(List<Entry<Class, Impl>> insertionOrder) { return insertionOrder; } } private
TestClassToInstanceMapGenerator
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/config/AbstractConfig.java
{ "start": 1672, "end": 4796 }
class ____ { private static final Logger log = LoggerFactory.getLogger(AbstractConfig.class); /** * Configs for which values have been requested, used to detect unused configs. * This set must be concurrent modifiable and iterable. It will be modified * when directly accessed or as a result of RecordingMap access. */ private final Set<String> used = ConcurrentHashMap.newKeySet(); /* the original values passed in by the user */ private final Map<String, ?> originals; /* the parsed values */ private final Map<String, Object> values; private final ConfigDef definition; public static final String AUTOMATIC_CONFIG_PROVIDERS_PROPERTY = "org.apache.kafka.automatic.config.providers"; public static final String CONFIG_PROVIDERS_CONFIG = "config.providers"; public static final String CONFIG_PROVIDERS_DOC = "Comma-separated alias names for classes implementing the <code>ConfigProvider</code> interface. " + "This enables loading configuration data (such as passwords, API keys, and other credentials) from external " + "sources. For example, see <a href=\"https://kafka.apache.org/documentation/#config_providers\">Configuration Providers</a>."; private static final String CONFIG_PROVIDERS_PARAM = ".param."; /** * Construct a configuration with a ConfigDef and the configuration properties, which can include properties * for zero or more {@link ConfigProvider} that will be used to resolve variables in configuration property * values. * <p> * The originals is a name-value pair configuration properties and optional config provider configs. The * value of the configuration can be a variable as defined below or the actual value. This constructor will * first instantiate the ConfigProviders using the config provider configs, then it will find all the * variables in the values of the originals configurations, attempt to resolve the variables using the named * ConfigProviders, and then parse and validate the configurations. * <p> * ConfigProvider configs can be passed either as configs in the originals map or in the separate * configProviderProps map. If config providers properties are passed in the configProviderProps any config * provider properties in originals map will be ignored. If ConfigProvider properties are not provided, the * constructor will skip the variable substitution step and will simply validate and parse the supplied * configuration. * <p> * The "{@code config.providers}" configuration property and all configuration properties that begin with the * "{@code config.providers.}" prefix are reserved. The "{@code config.providers}" configuration property * specifies the names of the config providers, and properties that begin with the "{@code config.providers..}" * prefix correspond to the properties for that named provider. For example, the "{@code config.providers..class}" * property specifies the name of the {@link ConfigProvider} implementation
AbstractConfig
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/builder/parentchild/ImmutableChild.java
{ "start": 207, "end": 501 }
class ____ { private final String name; private ImmutableChild(Builder builder) { this.name = builder.name; } public static Builder builder() { return new Builder(); } public String getName() { return name; } public static
ImmutableChild
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelHelper.java
{ "start": 555, "end": 5737 }
class ____ { private MappingModelHelper() { // disallow direct instantiation } // // public static Expression buildColumnReferenceExpression( // ModelPart modelPart, // SqlExpressionResolver sqlExpressionResolver) { // return buildColumnReferenceExpression( null, modelPart, sqlExpressionResolver ); // } // // public static Expression buildColumnReferenceExpression( // TableGroup tableGroup, // ModelPart modelPart, // SqlExpressionResolver sqlExpressionResolver) { // final int jdbcTypeCount = modelPart.getJdbcTypeCount(); // // if ( modelPart instanceof EmbeddableValuedModelPart ) { // final List<ColumnReference> columnReferences = new ArrayList<>( jdbcTypeCount ); // modelPart.forEachSelectable( // (columnIndex, selection) -> { // final ColumnReference colRef; // final String qualifier; // if ( tableGroup == null ) { // qualifier = selection.getContainingTableExpression(); // } // else { // qualifier = tableGroup.resolveTableReference( selection.getContainingTableExpression() ).getIdentificationVariable(); // } // if ( sqlExpressionResolver == null ) { // colRef = new ColumnReference( // qualifier, // selection // ); // } // else { // colRef = (ColumnReference) sqlExpressionResolver.resolveSqlExpression( // createColumnReferenceKey( qualifier, selection ), // sqlAstProcessingState -> new ColumnReference( // qualifier, // selection // ) // ); // } // columnReferences.add( colRef ); // } // ); // return new SqlTuple( columnReferences, modelPart ); // } // else { // assert modelPart instanceof BasicValuedModelPart; // final BasicValuedModelPart basicPart = (BasicValuedModelPart) modelPart; // final String qualifier; // if ( tableGroup == null ) { // qualifier = basicPart.getContainingTableExpression(); // } // else { // qualifier = tableGroup.resolveTableReference( basicPart.getContainingTableExpression() ).getIdentificationVariable(); // } // if ( sqlExpressionResolver == null ) { // return new ColumnReference( // qualifier, // basicPart // ); // } // else { // return sqlExpressionResolver.resolveSqlExpression( // createColumnReferenceKey( qualifier, basicPart ), // sqlAstProcessingState -> new ColumnReference( // qualifier, // basicPart // ) // ); // } // } // } // public static boolean isCompatibleModelPart(ModelPart attribute1, ModelPart attribute2) { if ( attribute1 == attribute2 ) { return true; } if ( attribute1.getClass() != attribute2.getClass() || attribute1.getJavaType() != attribute2.getJavaType() ) { return false; } if ( attribute1 instanceof Association association1 ) { final var association2 = (Association) attribute2; return association1.getForeignKeyDescriptor().getAssociationKey().equals( association2.getForeignKeyDescriptor().getAssociationKey() ); } else if ( attribute1 instanceof PluralAttributeMapping plural1 ) { final var plural2 = (PluralAttributeMapping) attribute2; final var element1 = plural1.getElementDescriptor(); final var element2 = plural2.getElementDescriptor(); final var index1 = plural1.getIndexDescriptor(); final var index2 = plural2.getIndexDescriptor(); return plural1.getKeyDescriptor().getAssociationKey() .equals( plural2.getKeyDescriptor().getAssociationKey() ) && ( index1 == null && index2 == null || isCompatibleModelPart( index1, index2 ) ) && isCompatibleModelPart( element1, element2 ); } else if ( attribute1 instanceof EmbeddableValuedModelPart embedded1 ) { final var embedded2 = (EmbeddableValuedModelPart) attribute2; final var embeddableTypeDescriptor1 = embedded1.getEmbeddableTypeDescriptor(); final var embeddableTypeDescriptor2 = embedded2.getEmbeddableTypeDescriptor(); final int numberOfAttributeMappings = embeddableTypeDescriptor1.getNumberOfAttributeMappings(); if ( numberOfAttributeMappings != embeddableTypeDescriptor2.getNumberOfAttributeMappings() ) { return false; } for ( int i = 0; i < numberOfAttributeMappings; i++ ) { if ( !isCompatibleModelPart( embeddableTypeDescriptor1.getAttributeMapping( i ), embeddableTypeDescriptor2.getAttributeMapping( i ) ) ) { return false; } } return true; } else { final var basic1 = attribute1.asBasicValuedModelPart(); if ( basic1 != null ) { final var basic2 = castNonNull( attribute2.asBasicValuedModelPart() ); if ( !basic1.getSelectionExpression().equals( basic2.getSelectionExpression() ) ) { return false; } if ( basic1.getContainingTableExpression().equals( basic2.getContainingTableExpression() ) ) { return true; } // For union subclass mappings we also consider mappings compatible that just match the selection expression, // because we match up columns of disjoint union subclass types by column name return attribute1.findContainingEntityMapping() .getEntityPersister() instanceof UnionSubclassEntityPersister; } } return false; } }
MappingModelHelper
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionContainsTest.java
{ "start": 3463, "end": 4067 }
class ____.getExchangeExtension().addOnCompletion(new SynchronizationAdapter() { @Override public void onDone(Exchange exchange) { template.sendBody("mock:sync", "C"); } @Override public String toString() { return "C"; } }); } }).to("mock:result"); } }; } }
exchange
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/internal/AttributeFactory.java
{ "start": 3647, "end": 12726 }
class ____ { private final MetadataContext context; public AttributeFactory(MetadataContext context) { this.context = context; } /** * Build a normal attribute. * * @param ownerType The descriptor of the attribute owner (aka declarer). * @param property The Hibernate property descriptor for the attribute * @param <X> The type of the owner * * @return The built attribute descriptor or null if the attribute is not part of the JPA 2 model (eg backrefs) */ public <X> PersistentAttribute<X, ?> buildAttribute(ManagedDomainType<X> ownerType, Property property) { return buildAttribute( ownerType, property, context ); } public static <X> PersistentAttribute<X, ?> buildAttribute( ManagedDomainType<X> ownerType, Property property, MetadataContext metadataContext) { if ( property.isSynthetic() ) { // hide synthetic/virtual properties (fabricated by Hibernate) from the JPA metamodel. CORE_LOGGER.tracef( "Skipping synthetic property %s(%s)", ownerType.getTypeName(), property.getName() ); return null; } CORE_LOGGER.tracef( "Building attribute [%s.%s]", ownerType.getTypeName(), property.getName() ); final var attributeMetadata = determineAttributeMetadata( wrap( ownerType, property ), normalMemberResolver, metadataContext ); if ( attributeMetadata instanceof PluralAttributeMetadata ) { return PluralAttributeBuilder.build( (PluralAttributeMetadata<X,?,?>) attributeMetadata, property.isGeneric(), metadataContext ); } final var singularAttributeMetadata = (SingularAttributeMetadata<X, ?>) attributeMetadata; final var valueContext = singularAttributeMetadata.getValueContext(); final var domainType = (SqmDomainType<?>) determineSimpleType( valueContext, metadataContext ); final var relationalJavaType = determineRelationalJavaType( valueContext, domainType, metadataContext ); return new SingularAttributeImpl<>( ownerType, attributeMetadata.getName(), attributeMetadata.getAttributeClassification(), domainType, relationalJavaType, attributeMetadata.getMember(), false, false, property.isOptional(), property.isGeneric() ); } private static <X> AttributeContext<X> wrap(final ManagedDomainType<X> ownerType, final Property property) { return new AttributeContext<>() { public ManagedDomainType<X> getOwnerType() { return ownerType; } public Property getPropertyMapping() { return property; } }; } /** * Build the identifier attribute descriptor * * @param ownerType The descriptor of the attribute owner (aka declarer). * @param property The Hibernate property descriptor for the identifier attribute * @param <X> The type of the owner * * @return The built attribute descriptor */ public <X> SingularPersistentAttribute<X, ?> buildIdAttribute( IdentifiableDomainType<X> ownerType, Property property) { CORE_LOGGER.tracef( "Building identifier attribute [%s.%s]", ownerType.getTypeName(), property.getName() ); final var attributeMetadata = determineAttributeMetadata( wrap( ownerType, property ), identifierMemberResolver ); final var singularAttributeMetadata = (SingularAttributeMetadata<X, ?>) attributeMetadata; final var domainType = (SqmDomainType<?>) determineSimpleType( singularAttributeMetadata.getValueContext() ); return new SingularAttributeImpl.Identifier<>( ownerType, property.getName(), domainType, attributeMetadata.getMember(), attributeMetadata.getAttributeClassification(), property.isGeneric() ); } /** * Build the version attribute descriptor * * @param ownerType The descriptor of the attribute owner (aka declarer). * @param property The Hibernate property descriptor for the version attribute * @param <X> The type of the owner * * @return The built attribute descriptor */ public <X> SingularAttributeImpl<X, ?> buildVersionAttribute( IdentifiableDomainType<X> ownerType, Property property) { CORE_LOGGER.tracef( "Building version attribute [%s.%s]", ownerType.getTypeName(), property.getName() ); final var attributeMetadata = determineAttributeMetadata( wrap( ownerType, property ), versionMemberResolver ); final var singularAttributeMetadata = (SingularAttributeMetadata<X, ?>) attributeMetadata; final var domainType = (SqmDomainType<?>) determineSimpleType( singularAttributeMetadata.getValueContext() ); return new SingularAttributeImpl.Version<>( ownerType, property.getName(), attributeMetadata.getAttributeClassification(), domainType, attributeMetadata.getMember() ); } private DomainType<?> determineSimpleType(ValueContext typeContext) { return determineSimpleType( typeContext, context ); } public static DomainType<?> determineSimpleType(ValueContext typeContext, MetadataContext context) { return switch ( typeContext.getValueClassification() ) { case BASIC -> basicDomainType( typeContext, context ); case ENTITY -> entityDomainType (typeContext, context ); case EMBEDDABLE -> embeddableDomainType( typeContext, context ); default -> throw new AssertionFailure( "Unknown type : " + typeContext.getValueClassification() ); }; } private static EmbeddableDomainType<?> embeddableDomainType(ValueContext typeContext, MetadataContext context) { final var component = (Component) typeContext.getHibernateValue(); return component.isDynamic() ? dynamicEmbeddableType( context, component ) : classEmbeddableType( context, component ); // we should have a non-dynamic embeddable } private static EmbeddableDomainType<?> classEmbeddableType(MetadataContext context, Component component) { assert component.getComponentClassName() != null; final var embeddableClass = component.getComponentClass(); if ( !component.isGeneric() ) { final var cached = context.locateEmbeddable( embeddableClass, component ); if ( cached != null ) { return cached; } } final var mappedSuperclass = component.getMappedSuperclass(); final var superType = mappedSuperclass == null ? null : context.locateMappedSuperclassType( mappedSuperclass ); final var discriminatorType = component.isPolymorphic() ? component.getDiscriminatorType() : null; final var embeddableType = embeddableType( context, embeddableClass, superType, discriminatorType ); context.registerEmbeddableType( embeddableType, component ); if ( component.isPolymorphic() ) { final var embeddableSubclasses = component.getDiscriminatorValues().values(); final java.util.Map<String, EmbeddableTypeImpl<?>> domainTypes = new HashMap<>(); domainTypes.put( embeddableType.getTypeName(), embeddableType ); final var classLoaderService = context.getRuntimeModelCreationContext().getBootstrapContext().getClassLoaderService(); for ( final String subclassName : embeddableSubclasses ) { if ( domainTypes.containsKey( subclassName ) ) { assert subclassName.equals( embeddableType.getTypeName() ); } else { final Class<?> subclass = classLoaderService.classForName( subclassName ); final var superTypeEmbeddable = domainTypes.get( component.getSuperclass( subclassName ) ); final var subType = embeddableType( context, subclass, superTypeEmbeddable, discriminatorType ); domainTypes.put( subclassName, subType ); context.registerEmbeddableType( subType, component ); } } } return embeddableType; } private static <J> EmbeddableTypeImpl<J> embeddableType( MetadataContext context, Class<J> subclass, ManagedDomainType<?> superType, DiscriminatorType<?> discriminatorType) { @SuppressWarnings("unchecked") final var castSuperType = (ManagedDomainType<? super J>) superType; return new EmbeddableTypeImpl<>( context.getJavaTypeRegistry().resolveManagedTypeDescriptor( subclass ), castSuperType, discriminatorType, false, context.getJpaMetamodel() ); } private static EmbeddableTypeImpl<?> dynamicEmbeddableType(MetadataContext context, Component component) { final var embeddableType = new EmbeddableTypeImpl<>( context.getJavaTypeRegistry().resolveDescriptor( java.util.Map.class ), null, null, true, context.getJpaMetamodel() ); context.registerComponentByEmbeddable( embeddableType, component); final var inFlightAccess = embeddableType.getInFlightAccess(); for ( Property property : component.getProperties() ) { final var attribute = buildAttribute( embeddableType, property, context); if ( attribute != null ) { inFlightAccess.addAttribute( attribute ); } } inFlightAccess.finishUp(); return embeddableType; } private static DomainType<?> entityDomainType(ValueContext typeContext, MetadataContext context) { final var type = typeContext.getHibernateValue().getType(); if ( type instanceof EntityType entityType ) { final var domainType = context.locateIdentifiableType( entityType.getAssociatedEntityName() ); if ( domainType == null ) { // Due to the use of generics, it can happen that a mapped super
AttributeFactory
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/inheritance/classdenyall/ClassDenyAllInterfaceWithoutPath_PathOnParent_SecurityOnInterface.java
{ "start": 908, "end": 2234 }
interface ____ { @POST @Path(CLASS_PATH_ON_PARENT_RESOURCE + IMPL_ON_INTERFACE + IMPL_METHOD_WITH_PATH + CLASS_DENY_ALL_PATH) default String classPathOnParentResource_ImplOnInterface_ImplMethodWithPath_ClassDenyAll(JsonObject array) { return CLASS_PATH_ON_PARENT_RESOURCE + IMPL_ON_INTERFACE + IMPL_METHOD_WITH_PATH + CLASS_DENY_ALL_PATH; } @PermitAll @POST @Path(CLASS_PATH_ON_PARENT_RESOURCE + IMPL_ON_INTERFACE + IMPL_METHOD_WITH_PATH + CLASS_DENY_ALL_METHOD_PERMIT_ALL_PATH) default String classPathOnParentResource_ImplOnInterface_ImplMethodWithPath_ClassDenyAllMethodPermitAll(JsonObject array) { return CLASS_PATH_ON_PARENT_RESOURCE + IMPL_ON_INTERFACE + IMPL_METHOD_WITH_PATH + CLASS_DENY_ALL_METHOD_PERMIT_ALL_PATH; } @RolesAllowed("admin") @POST @Path(CLASS_PATH_ON_PARENT_RESOURCE + IMPL_ON_INTERFACE + IMPL_METHOD_WITH_PATH + CLASS_DENY_ALL_METHOD_ROLES_ALLOWED_PATH) default String classPathOnParentResource_ImplOnInterface_ImplMethodWithPath_ClassDenyAllMethodRolesAllowed( JsonObject array) { return CLASS_PATH_ON_PARENT_RESOURCE + IMPL_ON_INTERFACE + IMPL_METHOD_WITH_PATH + CLASS_DENY_ALL_METHOD_ROLES_ALLOWED_PATH; } }
ClassDenyAllInterfaceWithoutPath_PathOnParent_SecurityOnInterface
java
netty__netty
handler/src/main/java/io/netty/handler/ssl/OpenSslPrivateKey.java
{ "start": 973, "end": 3482 }
class ____ extends AbstractReferenceCounted implements PrivateKey { private long privateKeyAddress; OpenSslPrivateKey(long privateKeyAddress) { this.privateKeyAddress = privateKeyAddress; } @Override public String getAlgorithm() { return "unknown"; } @Override public String getFormat() { // As we do not support encoding we should return null as stated in the javadocs of PrivateKey. return null; } @Override public byte[] getEncoded() { return null; } private long privateKeyAddress() { if (refCnt() <= 0) { throw new IllegalReferenceCountException(); } return privateKeyAddress; } @Override protected void deallocate() { SSL.freePrivateKey(privateKeyAddress); privateKeyAddress = 0; } @Override public OpenSslPrivateKey retain() { super.retain(); return this; } @Override public OpenSslPrivateKey retain(int increment) { super.retain(increment); return this; } @Override public OpenSslPrivateKey touch() { super.touch(); return this; } @Override public OpenSslPrivateKey touch(Object hint) { return this; } /** * NOTE: This is a JDK8 interface/method. Due to backwards compatibility * reasons it's not possible to slap the {@code @Override} annotation onto * this method. * * @see Destroyable#destroy() */ @Override public void destroy() { release(refCnt()); } /** * NOTE: This is a JDK8 interface/method. Due to backwards compatibility * reasons it's not possible to slap the {@code @Override} annotation onto * this method. * * @see Destroyable#isDestroyed() */ @Override public boolean isDestroyed() { return refCnt() == 0; } /** * Create a new {@link OpenSslKeyMaterial} which uses the private key that is held by {@link OpenSslPrivateKey}. * * When the material is created we increment the reference count of the enclosing {@link OpenSslPrivateKey} and * decrement it again when the reference count of the {@link OpenSslKeyMaterial} reaches {@code 0}. */ OpenSslKeyMaterial newKeyMaterial(long certificateChain, X509Certificate[] chain) { return new OpenSslPrivateKeyMaterial(certificateChain, chain); } // Package-private for unit-test only final
OpenSslPrivateKey