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__camel
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/InvalidReplayIdException.java
{ "start": 858, "end": 1157 }
class ____ extends RuntimeException { private final String replayId; public InvalidReplayIdException(String message, String replayId) { super(message); this.replayId = replayId; } public String getReplayId() { return replayId; } }
InvalidReplayIdException
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/strategy/PartialFinishedInputConsumableDecider.java
{ "start": 1321, "end": 2810 }
class ____ implements InputConsumableDecider { public static final int NUM_FINISHED_PARTITIONS_AS_CONSUMABLE = 1; @Override public boolean isInputConsumable( SchedulingExecutionVertex executionVertex, Set<ExecutionVertexID> verticesToDeploy, Map<ConsumedPartitionGroup, Boolean> consumableStatusCache) { for (ConsumedPartitionGroup consumedPartitionGroup : executionVertex.getConsumedPartitionGroups()) { if (!consumableStatusCache.computeIfAbsent( consumedPartitionGroup, this::isConsumableBasedOnFinishedProducers)) { return false; } } return true; } @Override public boolean isConsumableBasedOnFinishedProducers( final ConsumedPartitionGroup consumedPartitionGroup) { if (consumedPartitionGroup .getResultPartitionType() .isBlockingOrBlockingPersistentResultPartition()) { return consumedPartitionGroup.getNumberOfUnfinishedPartitions() == 0; } else { int numFinishedPartitions = consumedPartitionGroup.size() - consumedPartitionGroup.getNumberOfUnfinishedPartitions(); return numFinishedPartitions >= NUM_FINISHED_PARTITIONS_AS_CONSUMABLE; } } /** Factory for {@link PartialFinishedInputConsumableDecider}. */ public static
PartialFinishedInputConsumableDecider
java
apache__camel
components/camel-olingo2/camel-olingo2-api/src/main/java/org/apache/camel/component/olingo2/api/impl/Olingo2AppImpl.java
{ "start": 4951, "end": 59618 }
class ____ implements Olingo2App { public static final String METADATA = "$metadata"; private static final String SEPARATOR = "/"; private static final String BOUNDARY_PREFIX = "batch_"; private static final String BOUNDARY_PARAMETER = "; boundary="; private static final ContentType METADATA_CONTENT_TYPE = ContentType.create("application/xml", Consts.UTF_8); private static final ContentType SERVICE_DOCUMENT_CONTENT_TYPE = ContentType.create("application/atomsvc+xml", Consts.UTF_8); private static final String BATCH_CONTENT_TYPE = ContentType.create("multipart/mixed").toString(); private static final String BATCH = "$batch"; private static final String MAX_DATA_SERVICE_VERSION = "Max" + ODataHttpHeaders.DATASERVICEVERSION; private static final String MULTIPART_MIME_TYPE = "multipart/"; private static final ContentType TEXT_PLAIN_WITH_CS_UTF_8 = ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8); /** * Reference to CloseableHttpAsyncClient (default) or CloseableHttpClient */ private final Closeable client; private String serviceUri; private ContentType contentType; private Map<String, String> httpHeaders; private EntityProviderReadProperties entityProviderReadProperties; private EntityProviderWriteProperties entityProviderWriteProperties; /** * Create Olingo2 Application with default HTTP configuration. */ public Olingo2AppImpl(String serviceUri) { // By default create HTTP Asynchronous client this(serviceUri, (HttpAsyncClientBuilder) null); } /** * Create Olingo2 Application with custom HTTP Asynchronous client builder. * * @param serviceUri Service Application base URI. * @param builder custom HTTP client builder. */ public Olingo2AppImpl(String serviceUri, HttpAsyncClientBuilder builder) { setServiceUri(serviceUri); CloseableHttpAsyncClient asyncClient; if (builder == null) { asyncClient = HttpAsyncClients.createDefault(); } else { asyncClient = builder.build(); } asyncClient.start(); this.client = asyncClient; this.contentType = ContentType.create("application/json", Consts.UTF_8); } /** * Create Olingo2 Application with custom HTTP Synchronous client builder. * * @param serviceUri Service Application base URI. * @param builder Custom HTTP Synchronous client builder. */ public Olingo2AppImpl(String serviceUri, HttpClientBuilder builder) { setServiceUri(serviceUri); if (builder == null) { this.client = HttpClients.createDefault(); } else { this.client = builder.build(); } this.contentType = ContentType.create("application/json", Consts.UTF_8); } @Override public void setServiceUri(String serviceUri) { if (serviceUri == null || serviceUri.isEmpty()) { throw new IllegalArgumentException("serviceUri is not set"); } this.serviceUri = serviceUri.endsWith(SEPARATOR) ? serviceUri.substring(0, serviceUri.length() - 1) : serviceUri; } @Override public String getServiceUri() { return serviceUri; } @Override public Map<String, String> getHttpHeaders() { return httpHeaders; } @Override public void setHttpHeaders(Map<String, String> httpHeaders) { this.httpHeaders = httpHeaders; } @Override public void setEntityProviderReadProperties(EntityProviderReadProperties entityProviderReadProperties) { this.entityProviderReadProperties = entityProviderReadProperties; } @Override public EntityProviderReadProperties getEntityProviderReadProperties() { if (entityProviderReadProperties == null) { entityProviderReadProperties = EntityProviderReadProperties.init().build(); } return entityProviderReadProperties; } @Override public void setEntityProviderWriteProperties(EntityProviderWriteProperties entityProviderWriteProperties) { this.entityProviderWriteProperties = entityProviderWriteProperties; } @Override public EntityProviderWriteProperties getEntityProviderWriteProperties() { if (entityProviderWriteProperties == null) { entityProviderWriteProperties = EntityProviderWriteProperties.serviceRoot(null).build(); } return entityProviderWriteProperties; } @Override public String getContentType() { return contentType.toString(); } @Override public void setContentType(String contentType) { this.contentType = ContentType.parse(contentType); } @Override public void close() { if (client != null) { try { client.close(); } catch (final IOException ignore) { } } } @Override public <T> void read( final Edm edm, final String resourcePath, final Map<String, String> queryParams, final Map<String, String> endpointHttpHeaders, final Olingo2ResponseHandler<T> responseHandler) { final UriInfoWithType uriInfo = parseUri(edm, resourcePath, queryParams); execute(new HttpGet(createUri(resourcePath, encodeQueryParams(queryParams))), getResourceContentType(uriInfo), endpointHttpHeaders, new AbstractFutureCallback<T>(responseHandler) { @Override public void onCompleted(HttpResponse result) throws IOException { readContent(uriInfo, headersToMap(result.getAllHeaders()), result.getEntity() != null ? result.getEntity().getContent() : null, responseHandler); } }); } @Override public void uread( final Edm edm, final String resourcePath, final Map<String, String> queryParams, final Map<String, String> endpointHttpHeaders, final Olingo2ResponseHandler<InputStream> responseHandler) { final UriInfoWithType uriInfo = parseUri(edm, resourcePath, queryParams); execute(new HttpGet(createUri(resourcePath, encodeQueryParams(queryParams))), getResourceContentType(uriInfo), endpointHttpHeaders, new AbstractFutureCallback<InputStream>(responseHandler) { @Override public void onCompleted(HttpResponse result) throws IOException { responseHandler.onResponse((result.getEntity() != null) ? result.getEntity().getContent() : null, headersToMap(result.getAllHeaders())); } }); } private Map<String, String> encodeQueryParams(Map<String, String> queryParams) { Map<String, String> encodedQueryParams = queryParams; if (queryParams != null) { encodedQueryParams = new HashMap<>(queryParams.size()); for (Map.Entry<String, String> entry : queryParams.entrySet()) { encodedQueryParams.put(entry.getKey(), URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)); } } return encodedQueryParams; } private ContentType getResourceContentType(UriInfoWithType uriInfo) { ContentType resourceContentType; switch (uriInfo.getUriType()) { case URI0: // service document resourceContentType = SERVICE_DOCUMENT_CONTENT_TYPE; break; case URI8: // metadata resourceContentType = METADATA_CONTENT_TYPE; break; case URI4: case URI5: // is it a $value URI?? if (uriInfo.isValue()) { // property value and $count resourceContentType = TEXT_PLAIN_WITH_CS_UTF_8; } else { resourceContentType = contentType; } break; case URI15: case URI16: case URI50A: case URI50B: // $count resourceContentType = TEXT_PLAIN_WITH_CS_UTF_8; break; default: resourceContentType = contentType; } return resourceContentType; } @Override public <T> void create( final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo2ResponseHandler<T> responseHandler) { final UriInfoWithType uriInfo = parseUri(edm, resourcePath, null); writeContent(edm, new HttpPost(createUri(resourcePath, null)), uriInfo, endpointHttpHeaders, data, responseHandler, getEntityProviderWriteProperties()); } @Override public <T> void update( final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo2ResponseHandler<T> responseHandler) { final UriInfoWithType uriInfo = parseUri(edm, resourcePath, null); augmentWithETag(edm, resourcePath, endpointHttpHeaders, new HttpPut(createUri(resourcePath, null)), request -> writeContent(edm, (HttpPut) request, uriInfo, endpointHttpHeaders, data, responseHandler, getEntityProviderWriteProperties()), responseHandler); } @Override public <T> void patch( final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo2ResponseHandler<T> responseHandler) { final UriInfoWithType uriInfo = parseUri(edm, resourcePath, null); augmentWithETag(edm, resourcePath, endpointHttpHeaders, new HttpPatch(createUri(resourcePath, null)), request -> writeContent(edm, (HttpPatch) request, uriInfo, endpointHttpHeaders, data, responseHandler, getEntityProviderWriteProperties()), responseHandler); } @Override public <T> void merge( final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo2ResponseHandler<T> responseHandler) { final UriInfoWithType uriInfo = parseUri(edm, resourcePath, null); // merge operation must use data based property serialization in order to not overwrite // unspecified properties with null values EntityProviderWriteProperties entityProviderWriteProperties = EntityProviderWriteProperties.fromProperties(getEntityProviderWriteProperties()) .isDataBasedPropertySerialization(true).build(); augmentWithETag(edm, resourcePath, endpointHttpHeaders, new HttpMerge(createUri(resourcePath, null)), request -> writeContent(edm, (HttpMerge) request, uriInfo, endpointHttpHeaders, data, responseHandler, entityProviderWriteProperties), responseHandler); } @Override public void batch( final Edm edm, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo2ResponseHandler<List<Olingo2BatchResponse>> responseHandler) { final UriInfoWithType uriInfo = parseUri(edm, BATCH, null); writeContent(edm, new HttpPost(createUri(BATCH, null)), uriInfo, endpointHttpHeaders, data, responseHandler, getEntityProviderWriteProperties()); } @Override public void delete( final String resourcePath, final Map<String, String> endpointHttpHeaders, final Olingo2ResponseHandler<HttpStatusCodes> responseHandler) { HttpDelete deleteRequest = new HttpDelete(createUri(resourcePath)); Consumer<HttpRequestBase> deleteFunction = request -> { execute(request, contentType, endpointHttpHeaders, new AbstractFutureCallback<HttpStatusCodes>(responseHandler) { @Override public void onCompleted(HttpResponse result) { final StatusLine statusLine = result.getStatusLine(); responseHandler.onResponse(HttpStatusCodes.fromStatusCode(statusLine.getStatusCode()), headersToMap(result.getAllHeaders())); } }); }; augmentWithETag(null, resourcePath, endpointHttpHeaders, deleteRequest, deleteFunction, responseHandler); } /** * On occasion, some resources are protected with Optimistic Concurrency via the use of eTags. This will first * conduct a read on the given entity resource, find its eTag then perform the given delegate request function, * augmenting the request with the eTag, if appropriate. Since read operations may be asynchronous, it is necessary * to chain together the methods via the use of a {@link Consumer} function. Only when the response from the read * returns will this delegate function be executed. * * @param edm the Edm object to be interrogated * @param resourcePath the resource path of the entity to be operated on * @param endpointHttpHeaders the headers provided from the endpoint which may be required for the read * operation * @param httpRequest the request to be updated, if appropriate, with the eTag and provided to the * delegate request function * @param delegateRequestFn the function to be invoked in response to the read operation * @param delegateResponseHandler the response handler to respond if any errors occur during the read operation */ private <T> void augmentWithETag( final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final HttpRequestBase httpRequest, final Consumer<HttpRequestBase> delegateRequestFn, final Olingo2ResponseHandler<T> delegateResponseHandler) { if (edm == null) { // Can be the case if calling a delete then need to do a metadata // call first final Olingo2ResponseHandler<Edm> edmResponseHandler = new Olingo2ResponseHandler<Edm>() { @Override public void onResponse(Edm response, Map<String, String> responseHeaders) { // // Call this method again with an intact edm object // augmentWithETag(response, resourcePath, endpointHttpHeaders, httpRequest, delegateRequestFn, delegateResponseHandler); } @Override public void onException(Exception ex) { delegateResponseHandler.onException(ex); } @Override public void onCanceled() { delegateResponseHandler.onCanceled(); } }; // // Reads the metadata to establish an Edm object // then the response handler invokes this method again with the new // edm object // read(null, "$metadata", null, null, edmResponseHandler); } else { // // The handler that responds to the read operation and supplies an // ETag if necessary // and invokes the delegate request function // Olingo2ResponseHandler<T> eTagReadHandler = new Olingo2ResponseHandler<T>() { @Override public void onResponse(T response, Map<String, String> responseHeaders) { if (response instanceof ODataEntry) { ODataEntry e = (ODataEntry) response; Optional.ofNullable(e.getMetadata()).map(EntryMetadata::getEtag) .ifPresent(v -> httpRequest.addHeader("If-Match", v)); } // Invoke the delegate request function providing the // modified request delegateRequestFn.accept(httpRequest); } @Override public void onException(Exception ex) { delegateResponseHandler.onException(ex); } @Override public void onCanceled() { delegateResponseHandler.onCanceled(); } }; read(edm, resourcePath, null, endpointHttpHeaders, eTagReadHandler); } } private <T> void readContent( UriInfoWithType uriInfo, Map<String, String> responseHeaders, InputStream content, Olingo2ResponseHandler<T> responseHandler) { try { responseHandler.onResponse(this.<T> readContent(uriInfo, content), responseHeaders); } catch (Exception e) { responseHandler.onException(e); } catch (Error e) { responseHandler.onException(new ODataApplicationException("Runtime Error Occurred", Locale.ENGLISH, e)); } } @SuppressWarnings("unchecked") private <T> T readContent(UriInfoWithType uriInfo, InputStream content) throws EntityProviderException, ODataApplicationException { T response; switch (uriInfo.getUriType()) { case URI0: // service document response = (T) EntityProvider.readServiceDocument(content, SERVICE_DOCUMENT_CONTENT_TYPE.toString()); break; case URI8: // $metadata response = (T) EntityProvider.readMetadata(content, false); break; case URI7A: // link response = (T) EntityProvider.readLink(getContentType(), uriInfo.getTargetEntitySet(), content); break; case URI7B: // links response = (T) EntityProvider.readLinks(getContentType(), uriInfo.getTargetEntitySet(), content); break; case URI3: // complex property final List<EdmProperty> complexPropertyPath = uriInfo.getPropertyPath(); final EdmProperty complexProperty = complexPropertyPath.get(complexPropertyPath.size() - 1); response = (T) EntityProvider.readProperty(getContentType(), complexProperty, content, getEntityProviderReadProperties()); break; case URI4: case URI5: // simple property final List<EdmProperty> simplePropertyPath = uriInfo.getPropertyPath(); final EdmProperty simpleProperty = simplePropertyPath.get(simplePropertyPath.size() - 1); if (uriInfo.isValue()) { response = (T) EntityProvider.readPropertyValue(simpleProperty, content); } else { response = (T) EntityProvider.readProperty(getContentType(), simpleProperty, content, getEntityProviderReadProperties()); } break; case URI15: case URI16: case URI50A: case URI50B: // $count final String stringCount = new String(EntityProvider.readBinary(content), Consts.UTF_8); response = (T) Long.valueOf(stringCount); break; case URI1: case URI6B: if (uriInfo.getCustomQueryOptions().containsKey("!deltatoken")) { // ODataDeltaFeed response = (T) EntityProvider.readDeltaFeed(getContentType(), uriInfo.getTargetEntitySet(), content, getEntityProviderReadProperties()); } else { // ODataFeed response = (T) EntityProvider.readFeed(getContentType(), uriInfo.getTargetEntitySet(), content, getEntityProviderReadProperties()); } break; case URI2: case URI6A: response = (T) EntityProvider.readEntry(getContentType(), uriInfo.getTargetEntitySet(), content, getEntityProviderReadProperties()); break; // Function Imports case URI10: case URI11: case URI12: case URI13: case URI14: response = (T) EntityProvider.readFunctionImport(getContentType(), uriInfo.getFunctionImport(), content, getEntityProviderReadProperties()); break; default: throw new ODataApplicationException("Unsupported resource type " + uriInfo.getTargetType(), Locale.ENGLISH); } return response; } private <T> void writeContent( final Edm edm, final HttpEntityEnclosingRequestBase httpEntityRequest, final UriInfoWithType uriInfo, final Map<String, String> endpointHttpHeaders, final Object content, final Olingo2ResponseHandler<T> responseHandler, EntityProviderWriteProperties entityProviderWriteProperties) { try { // process resource by UriType final ODataResponse response = writeContent(edm, uriInfo, content, entityProviderWriteProperties); // copy all response headers for (String header : response.getHeaderNames()) { httpEntityRequest.setHeader(header, response.getHeader(header)); } // get (http) entity which is for default Olingo2 implementation an // InputStream if (response.getEntity() instanceof InputStream) { httpEntityRequest.setEntity(new InputStreamEntity((InputStream) response.getEntity())); /* * // avoid sending it without a header field set if * (!httpEntityRequest.containsHeader(HttpHeaders.CONTENT_TYPE)) * { httpEntityRequest.addHeader(HttpHeaders.CONTENT_TYPE, * getContentType()); } */ } // execute HTTP request final Header requestContentTypeHeader = httpEntityRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE); final ContentType requestContentType = requestContentTypeHeader != null ? ContentType.parse(requestContentTypeHeader.getValue()) : contentType; execute(httpEntityRequest, requestContentType, endpointHttpHeaders, new AbstractFutureCallback<T>(responseHandler) { @SuppressWarnings("unchecked") @Override public void onCompleted(HttpResponse result) throws IOException, EntityProviderException, BatchException, ODataApplicationException { // if a entity is created (via POST request) the response // body contains the new created entity HttpStatusCodes statusCode = HttpStatusCodes.fromStatusCode(result.getStatusLine().getStatusCode()); // look for no content, or no response body!!! final boolean noEntity = result.getEntity() == null || result.getEntity().getContentLength() == 0; if (statusCode == HttpStatusCodes.NO_CONTENT || noEntity) { responseHandler.onResponse((T) HttpStatusCodes.fromStatusCode(result.getStatusLine().getStatusCode()), headersToMap(result.getAllHeaders())); } else { switch (uriInfo.getUriType()) { case URI9: // $batch String type = result.containsHeader(HttpHeaders.CONTENT_TYPE) ? result.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue() : null; final List<BatchSingleResponse> singleResponses = EntityProvider.parseBatchResponse(result.getEntity().getContent(), type); // parse batch response bodies final List<Olingo2BatchResponse> responses = new ArrayList<>(); Map<String, String> contentIdLocationMap = new HashMap<>(); final List<Olingo2BatchRequest> batchRequests = (List<Olingo2BatchRequest>) content; final Iterator<Olingo2BatchRequest> iterator = batchRequests.iterator(); for (BatchSingleResponse response : singleResponses) { final Olingo2BatchRequest request = iterator.next(); if (request instanceof Olingo2BatchChangeRequest && ((Olingo2BatchChangeRequest) request).getContentId() != null) { contentIdLocationMap.put("$" + ((Olingo2BatchChangeRequest) request).getContentId(), response.getHeader(HttpHeaders.LOCATION)); } try { responses.add(parseResponse(edm, contentIdLocationMap, request, response)); } catch (Exception e) { // report any parsing errors as error // response responses.add(new Olingo2BatchResponse( Integer.parseInt(response.getStatusCode()), response.getStatusInfo(), response.getContentId(), response .getHeaders(), new ODataApplicationException( "Error parsing response for " + request + ": " + e.getMessage(), Locale.ENGLISH, e))); } } responseHandler.onResponse((T) responses, headersToMap(result.getAllHeaders())); break; case URI4: case URI5: // simple property // get the response content as Object for $value or // Map<String, Object> otherwise final List<EdmProperty> simplePropertyPath = uriInfo.getPropertyPath(); final EdmProperty simpleProperty = simplePropertyPath.get(simplePropertyPath.size() - 1); if (uriInfo.isValue()) { responseHandler.onResponse( (T) EntityProvider.readPropertyValue(simpleProperty, result.getEntity().getContent()), headersToMap(result.getAllHeaders())); } else { responseHandler.onResponse( (T) EntityProvider.readProperty(getContentType(), simpleProperty, result.getEntity().getContent(), getEntityProviderReadProperties()), headersToMap(result.getAllHeaders())); } break; case URI3: // complex property // get the response content as Map<String, Object> final List<EdmProperty> complexPropertyPath = uriInfo.getPropertyPath(); final EdmProperty complexProperty = complexPropertyPath.get(complexPropertyPath.size() - 1); responseHandler.onResponse( (T) EntityProvider.readProperty(getContentType(), complexProperty, result.getEntity().getContent(), getEntityProviderReadProperties()), headersToMap(result.getAllHeaders())); break; case URI7A: // $links with 0..1 cardinality property // get the response content as String final EdmEntitySet targetLinkEntitySet = uriInfo.getTargetEntitySet(); responseHandler.onResponse( (T) EntityProvider.readLink(getContentType(), targetLinkEntitySet, result.getEntity().getContent()), headersToMap(result.getAllHeaders())); break; case URI7B: // $links with * cardinality property // get the response content as // java.util.List<String> final EdmEntitySet targetLinksEntitySet = uriInfo.getTargetEntitySet(); responseHandler.onResponse( (T) EntityProvider.readLinks(getContentType(), targetLinksEntitySet, result.getEntity().getContent()), headersToMap(result.getAllHeaders())); break; case URI1: case URI2: case URI6A: case URI6B: // Entity // get the response content as an ODataEntry object responseHandler.onResponse( (T) EntityProvider.readEntry(response.getContentHeader(), uriInfo.getTargetEntitySet(), result.getEntity().getContent(), getEntityProviderReadProperties()), headersToMap(result.getAllHeaders())); break; default: throw new ODataApplicationException( "Unsupported resource type " + uriInfo.getTargetType(), Locale.ENGLISH); } } } }); } catch (Exception e) { responseHandler.onException(e); } catch (Error e) { responseHandler.onException(new ODataApplicationException("Runtime Error Occurred", Locale.ENGLISH, e)); } } private ODataResponse writeContent( Edm edm, UriInfoWithType uriInfo, Object content, EntityProviderWriteProperties entityProviderWriteProperties) throws ODataApplicationException, EdmException, EntityProviderException, URISyntaxException, IOException { String responseContentType = getContentType(); ODataResponse response; switch (uriInfo.getUriType()) { case URI4: case URI5: // simple property final List<EdmProperty> simplePropertyPath = uriInfo.getPropertyPath(); final EdmProperty simpleProperty = simplePropertyPath.get(simplePropertyPath.size() - 1); responseContentType = simpleProperty.getMimeType(); if (uriInfo.isValue()) { response = EntityProvider.writePropertyValue(simpleProperty, content); responseContentType = TEXT_PLAIN_WITH_CS_UTF_8.toString(); } else { response = EntityProvider.writeProperty(getContentType(), simpleProperty, content); } break; case URI3: // complex property final List<EdmProperty> complexPropertyPath = uriInfo.getPropertyPath(); final EdmProperty complexProperty = complexPropertyPath.get(complexPropertyPath.size() - 1); response = EntityProvider.writeProperty(responseContentType, complexProperty, content); break; case URI7A: // $links with 0..1 cardinality property final EdmEntitySet targetLinkEntitySet = uriInfo.getTargetEntitySet(); EntityProviderWriteProperties linkProperties = EntityProviderWriteProperties.fromProperties(entityProviderWriteProperties) .serviceRoot(new URI(serviceUri + SEPARATOR)).build(); @SuppressWarnings("unchecked") final Map<String, Object> linkMap = (Map<String, Object>) content; response = EntityProvider.writeLink(responseContentType, targetLinkEntitySet, linkMap, linkProperties); break; case URI7B: // $links with * cardinality property final EdmEntitySet targetLinksEntitySet = uriInfo.getTargetEntitySet(); EntityProviderWriteProperties linksProperties = EntityProviderWriteProperties.fromProperties(entityProviderWriteProperties) .serviceRoot(new URI(serviceUri + SEPARATOR)).build(); @SuppressWarnings("unchecked") final List<Map<String, Object>> linksMap = (List<Map<String, Object>>) content; response = EntityProvider.writeLinks(responseContentType, targetLinksEntitySet, linksMap, linksProperties); break; case URI1: case URI2: case URI6A: case URI6B: // Entity final EdmEntitySet targetEntitySet = uriInfo.getTargetEntitySet(); EntityProviderWriteProperties properties = EntityProviderWriteProperties.fromProperties(entityProviderWriteProperties) .serviceRoot(new URI(serviceUri + SEPARATOR)).build(); @SuppressWarnings("unchecked") final Map<String, Object> objectMap = (Map<String, Object>) content; response = EntityProvider.writeEntry(responseContentType, targetEntitySet, objectMap, properties); break; case URI9: // $batch @SuppressWarnings("unchecked") final List<Olingo2BatchRequest> batchParts = (List<Olingo2BatchRequest>) content; response = parseBatchRequest(edm, batchParts); break; default: // notify exception and return!!! throw new ODataApplicationException("Unsupported resource type " + uriInfo.getTargetType(), Locale.ENGLISH); } return response.getContentHeader() != null ? response : ODataResponse.fromResponse(response).contentHeader(responseContentType).build(); } private ODataResponse parseBatchRequest(final Edm edm, final List<Olingo2BatchRequest> batchParts) throws IOException, EntityProviderException, ODataApplicationException, EdmException, URISyntaxException { // create Batch request from parts final ArrayList<BatchPart> parts = new ArrayList<>(); final ArrayList<BatchChangeSetPart> changeSetParts = new ArrayList<>(); final Map<String, String> contentIdMap = new HashMap<>(); for (Olingo2BatchRequest batchPart : batchParts) { if (batchPart instanceof Olingo2BatchQueryRequest) { // need to add change set parts collected so far?? if (!changeSetParts.isEmpty()) { addChangeSetParts(parts, changeSetParts); changeSetParts.clear(); contentIdMap.clear(); } // add to request parts final UriInfoWithType uriInfo = parseUri(edm, batchPart.getResourcePath(), null); parts.add(createBatchQueryPart(uriInfo, (Olingo2BatchQueryRequest) batchPart)); } else { // add to change set parts final BatchChangeSetPart changeSetPart = createBatchChangeSetPart(edm, contentIdMap, (Olingo2BatchChangeRequest) batchPart); changeSetParts.add(changeSetPart); } } // add any remaining change set parts if (!changeSetParts.isEmpty()) { addChangeSetParts(parts, changeSetParts); } final String boundary = BOUNDARY_PREFIX + UUID.randomUUID(); InputStream batchRequest = EntityProvider.writeBatchRequest(parts, boundary); // two blank lines are already added. No need to add extra blank lines final String contentHeader = BATCH_CONTENT_TYPE + BOUNDARY_PARAMETER + boundary; return ODataResponse.entity(batchRequest).contentHeader(contentHeader).build(); } private void addChangeSetParts(ArrayList<BatchPart> parts, ArrayList<BatchChangeSetPart> changeSetParts) { final BatchChangeSet changeSet = BatchChangeSet.newBuilder().build(); for (BatchChangeSetPart changeSetPart : changeSetParts) { changeSet.add(changeSetPart); } parts.add(changeSet); } private BatchChangeSetPart createBatchChangeSetPart( Edm edm, Map<String, String> contentIdMap, Olingo2BatchChangeRequest batchRequest) throws EdmException, URISyntaxException, EntityProviderException, IOException, ODataApplicationException { // build body string String resourcePath = batchRequest.getResourcePath(); // is it a referenced entity? if (resourcePath.startsWith("$")) { resourcePath = replaceContentId(edm, resourcePath, contentIdMap); } final UriInfoWithType uriInfo = parseUri(edm, resourcePath, null); // serialize data into ODataResponse object, if set in request and this // is not a DELETE request final Map<String, String> headers = new HashMap<>(); byte[] body = null; if (batchRequest.getBody() != null && !Operation.DELETE.equals(batchRequest.getOperation())) { final ODataResponse response = writeContent(edm, uriInfo, batchRequest.getBody(), getEntityProviderWriteProperties()); // copy response headers for (String header : response.getHeaderNames()) { headers.put(header, response.getHeader(header)); } // get (http) entity which is for default Olingo2 implementation an // InputStream body = response.getEntity() instanceof InputStream ? EntityProvider.readBinary((InputStream) response.getEntity()) : null; if (body != null) { headers.put(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length)); } } // Olingo is sensitive to batch part charset case!! final ContentType contentType = getResourceContentType(uriInfo); headers.put(HttpHeaders.ACCEPT, contentType.withCharset("").toString().toLowerCase()); final Charset charset = contentType.getCharset(); if (null != charset) { headers.put(HttpHeaders.ACCEPT_CHARSET, charset.name().toLowerCase()); } headers.computeIfAbsent(HttpHeaders.CONTENT_TYPE, k -> getContentType()); // add request headers headers.putAll(batchRequest.getHeaders()); final String contentId = batchRequest.getContentId(); if (contentId != null) { contentIdMap.put("$" + contentId, resourcePath); } return BatchChangeSetPart.uri(createBatchUri(batchRequest)).method(batchRequest.getOperation().getHttpMethod()) .contentId(contentId).headers(headers) .body(body == null ? null : new String(body, Consts.UTF_8)).build(); } private BatchQueryPart createBatchQueryPart(UriInfoWithType uriInfo, Olingo2BatchQueryRequest batchRequest) { final Map<String, String> headers = new HashMap<>(batchRequest.getHeaders()); final ContentType contentType = getResourceContentType(uriInfo); final Charset charset = contentType.getCharset(); if (!headers.containsKey(HttpHeaders.ACCEPT)) { // Olingo is sensitive to batch part charset case!! headers.put(HttpHeaders.ACCEPT, contentType.withCharset("").toString().toLowerCase()); } if (!headers.containsKey(HttpHeaders.ACCEPT_CHARSET) && null != charset) { headers.put(HttpHeaders.ACCEPT_CHARSET, charset.name().toLowerCase()); } return BatchQueryPart.method("GET").uri(createBatchUri(batchRequest)).headers(headers).build(); } private static String replaceContentId(Edm edm, String entityReference, Map<String, String> contentIdMap) throws EdmException { final int pathSeparator = entityReference.indexOf('/'); final StringBuilder referencedEntity; if (pathSeparator == -1) { referencedEntity = new StringBuilder(contentIdMap.get(entityReference)); } else { referencedEntity = new StringBuilder(contentIdMap.get(entityReference.substring(0, pathSeparator))); } // create a dummy entity location by adding a dummy key predicate // look for a Container name if available String referencedEntityName = referencedEntity.toString(); final int containerSeparator = referencedEntityName.lastIndexOf('.'); final EdmEntityContainer entityContainer; if (containerSeparator != -1) { final String containerName = referencedEntityName.substring(0, containerSeparator); referencedEntityName = referencedEntityName.substring(containerSeparator + 1); entityContainer = edm.getEntityContainer(containerName); if (entityContainer == null) { throw new IllegalArgumentException("EDM does not have entity container " + containerName); } } else { entityContainer = edm.getDefaultEntityContainer(); if (entityContainer == null) { throw new IllegalArgumentException( "EDM does not have a default entity container" + ", use a fully qualified entity set name"); } } final EdmEntitySet entitySet = entityContainer.getEntitySet(referencedEntityName); final List<EdmProperty> keyProperties = entitySet.getEntityType().getKeyProperties(); if (keyProperties.size() == 1) { referencedEntity.append("('dummy')"); } else { referencedEntity.append("("); for (EdmProperty keyProperty : keyProperties) { referencedEntity.append(keyProperty.getName()).append('=').append("'dummy',"); } referencedEntity.deleteCharAt(referencedEntity.length() - 1); referencedEntity.append(')'); } return pathSeparator == -1 ? referencedEntityName : referencedEntity.append(entityReference, pathSeparator, entityReference.length()).toString(); } private Olingo2BatchResponse parseResponse( Edm edm, Map<String, String> contentIdLocationMap, Olingo2BatchRequest request, BatchSingleResponse response) throws EntityProviderException, ODataApplicationException { // validate HTTP status final int statusCode = Integer.parseInt(response.getStatusCode()); final String statusInfo = response.getStatusInfo(); final BasicHttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, statusInfo)); final Map<String, String> headers = response.getHeaders(); for (Map.Entry<String, String> entry : headers.entrySet()) { httpResponse.setHeader(entry.getKey(), entry.getValue()); } ByteArrayInputStream content = null; try { if (response.getBody() != null) { String charset = Consts.UTF_8.toString(); try { final ContentType partContentType = receiveWithCharsetParameter( ContentType.parse(headers.get(HttpHeaders.CONTENT_TYPE)), Consts.UTF_8); charset = partContentType.getCharset().toString(); } catch (ParseException | UnsupportedCharsetException ex) { // Use default charset of UTF-8. } final String body = response.getBody(); content = body != null ? new ByteArrayInputStream(body.getBytes(charset)) : null; httpResponse.setEntity(new StringEntity(body, charset)); } AbstractFutureCallback.checkStatus(httpResponse); } catch (ODataApplicationException | UnsupportedEncodingException e) { return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(), e); } // resolve resource path and query params and parse batch part uri final String resourcePath = request.getResourcePath(); final String resolvedResourcePath; if (resourcePath.startsWith("$") && !(METADATA.equals(resourcePath) || BATCH.equals(resourcePath))) { resolvedResourcePath = findLocation(resourcePath, contentIdLocationMap); } else { final String resourceLocation = response.getHeader(HttpHeaders.LOCATION); resolvedResourcePath = resourceLocation != null ? resourceLocation.substring(serviceUri.length()) : resourcePath; } final Map<String, String> resolvedQueryParams = request instanceof Olingo2BatchQueryRequest ? ((Olingo2BatchQueryRequest) request).getQueryParams() : null; final UriInfoWithType uriInfo = parseUri(edm, resolvedResourcePath, resolvedQueryParams); // resolve response content final Object resolvedContent = content != null ? readContent(uriInfo, content) : null; return new Olingo2BatchResponse( statusCode, statusInfo, response.getContentId(), response.getHeaders(), resolvedContent); } private ContentType receiveWithCharsetParameter(ContentType contentType, Charset charset) { if (contentType.getCharset() != null) { return contentType; } final String mimeType = contentType.getMimeType(); if (mimeType.equals(ContentType.TEXT_PLAIN.getMimeType()) || AbstractFutureCallback.ODATA_MIME_TYPE.matcher(mimeType).matches()) { return contentType.withCharset(charset); } return contentType; } private String findLocation(String resourcePath, Map<String, String> contentIdLocationMap) { final int pathSeparator = resourcePath.indexOf('/'); if (pathSeparator == -1) { return contentIdLocationMap.get(resourcePath); } else { return contentIdLocationMap.get(resourcePath.substring(0, pathSeparator)) + resourcePath.substring(pathSeparator); } } private String createBatchUri(Olingo2BatchRequest part) { String result; if (part instanceof Olingo2BatchQueryRequest) { final Olingo2BatchQueryRequest queryPart = (Olingo2BatchQueryRequest) part; result = createUri(queryPart.getResourcePath(), queryPart.getQueryParams()); } else { result = createUri(part.getResourcePath()); } // strip base URI return result.substring(serviceUri.length() + 1); } private String createUri(String resourcePath) { return createUri(resourcePath, null); } private String createUri(String resourcePath, Map<String, String> queryParams) { final StringBuilder absolutUri = new StringBuilder(serviceUri).append(SEPARATOR).append(resourcePath); if (queryParams != null && !queryParams.isEmpty()) { absolutUri.append("?"); int nParams = queryParams.size(); int index = 0; for (Map.Entry<String, String> entry : queryParams.entrySet()) { absolutUri.append(entry.getKey()).append('=').append(entry.getValue()); if (++index < nParams) { absolutUri.append('&'); } } } return absolutUri.toString(); } private static UriInfoWithType parseUri(Edm edm, String resourcePath, Map<String, String> queryParams) { UriInfoWithType result; try { final List<PathSegment> pathSegments = new ArrayList<>(); final String[] segments = new URI(resourcePath).getPath().split(SEPARATOR); if (queryParams == null) { queryParams = Collections.emptyMap(); } for (String segment : segments) { if (segment.indexOf(';') == -1) { pathSegments.add(new ODataPathSegmentImpl(segment, null)); } else { // handle matrix params in path segment final String[] splitSegment = segment.split(";"); segment = splitSegment[0]; Map<String, List<String>> matrixParams = new HashMap<>(); for (int i = 1; i < splitSegment.length; i++) { final String[] param = splitSegment[i].split("="); List<String> values = matrixParams.get(param[0]); if (values == null) { values = new ArrayList<>(); matrixParams.put(param[0], values); } if (param[1].indexOf(',') == -1) { values.add(param[1]); } else { values.addAll(Arrays.asList(param[1].split(","))); } } pathSegments.add(new ODataPathSegmentImpl(segment, matrixParams)); } } result = new UriInfoWithType(UriParser.parse(edm, pathSegments, queryParams), resourcePath); } catch (URISyntaxException | ODataException e) { throw new IllegalArgumentException("resourcePath: " + e.getMessage(), e); } return result; } private static Map<String, String> headersToMap(final Header[] headers) { final Map<String, String> responseHeaders = new HashMap<>(); for (Header header : headers) { responseHeaders.put(header.getName(), header.getValue()); } return responseHeaders; } /** * public for unit test, not to be used otherwise */ public void execute( final HttpUriRequest httpUriRequest, final ContentType contentType, final Map<String, String> endpointHttpHeaders, final FutureCallback<HttpResponse> callback) { // add accept header when its not a form or multipart if (!ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType()) && !contentType.getMimeType().startsWith(MULTIPART_MIME_TYPE)) { // otherwise accept what is being sent httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentType.withCharset("").toString().toLowerCase()); final Charset charset = contentType.getCharset(); if (null != charset) { httpUriRequest.addHeader(HttpHeaders.ACCEPT_CHARSET, charset.name().toLowerCase()); } } // is something being sent? if (httpUriRequest instanceof HttpEntityEnclosingRequestBase && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) { httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType.toString()); } // set user specified custom headers if (httpHeaders != null && !httpHeaders.isEmpty()) { for (Map.Entry<String, String> entry : httpHeaders.entrySet()) { httpUriRequest.setHeader(entry.getKey(), entry.getValue()); } } // set user specified endpoint headers if (endpointHttpHeaders != null && !endpointHttpHeaders.isEmpty()) { for (Map.Entry<String, String> entry : endpointHttpHeaders.entrySet()) { httpUriRequest.setHeader(entry.getKey(), entry.getValue()); } } // add client protocol version if not specified if (!httpUriRequest.containsHeader(ODataHttpHeaders.DATASERVICEVERSION)) { httpUriRequest.addHeader(ODataHttpHeaders.DATASERVICEVERSION, ODataServiceVersion.V20); } if (!httpUriRequest.containsHeader(MAX_DATA_SERVICE_VERSION)) { httpUriRequest.addHeader(MAX_DATA_SERVICE_VERSION, ODataServiceVersion.V30); } // execute request if (client instanceof CloseableHttpAsyncClient) { ((CloseableHttpAsyncClient) client).execute(httpUriRequest, callback); } else { // invoke the callback methods explicitly after executing the // request synchronously try { CloseableHttpResponse result = ((CloseableHttpClient) client).execute(httpUriRequest); callback.completed(result); } catch (IOException e) { callback.failed(e); } } } }
Olingo2AppImpl
java
apache__kafka
connect/api/src/main/java/org/apache/kafka/connect/rest/ConnectRestExtensionContext.java
{ "start": 1234, "end": 1788 }
interface ____ { /** * Provides an implementation of {@link jakarta.ws.rs.core.Configurable} that can be used to register JAX-RS resources. * * @return the JAX-RS {@link jakarta.ws.rs.core.Configurable}; never {@code null} */ Configurable<? extends Configurable<?>> configurable(); /** * Provides the cluster state and health information about the connectors and tasks. * * @return the cluster state information; never {@code null} */ ConnectClusterState clusterState(); }
ConnectRestExtensionContext
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/logging/structured/StructuredLoggingJsonPropertiesBeanFactoryInitializationAotProcessorTests.java
{ "start": 1975, "end": 5408 }
class ____ { @Test void structuredLoggingJsonPropertiesBeanFactoryInitializationAotProcessorIsRegistered() { assertThat(AotServices.factories().load(BeanFactoryInitializationAotProcessor.class)) .anyMatch(StructuredLoggingJsonPropertiesBeanFactoryInitializationAotProcessor.class::isInstance); } @Test void shouldRegisterRuntimeHintsWhenCustomizerIsPresent() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.structured.json.customizer", TestCustomizer.class.getName()); BeanFactoryInitializationAotContribution contribution = getContribution(environment); assertThat(contribution).isNotNull(); RuntimeHints hints = getRuntimeHints(contribution); assertThat(RuntimeHintsPredicates.reflection() .onType(TestCustomizer.class) .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) .accepts(hints); } @Test void shouldRegisterRuntimeHintsWhenCustomStackTracePrinterIsPresent() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.structured.json.stacktrace.printer", TestStackTracePrinter.class.getName()); BeanFactoryInitializationAotContribution contribution = getContribution(environment); assertThat(contribution).isNotNull(); RuntimeHints hints = getRuntimeHints(contribution); assertThat(RuntimeHintsPredicates.reflection() .onType(TestStackTracePrinter.class) .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) .accepts(hints); } @ParameterizedTest @ValueSource(strings = { "logging-system", "standard" }) void shouldNotRegisterRuntimeHintsWhenStackTracePrinterIsNotCustomImplementation(String printer) { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.structured.json.stacktrace.printer", printer); BeanFactoryInitializationAotContribution contribution = getContribution(environment); assertThat(contribution).isNull(); } @Test void shouldNotRegisterRuntimeHintsWhenPropertiesAreNotSet() { MockEnvironment environment = new MockEnvironment(); BeanFactoryInitializationAotContribution contribution = getContribution(environment); assertThat(contribution).isNull(); } @Test void shouldNotRegisterRuntimeHintsWhenCustomizerAndPrinterAreNotSet() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.structured.json.exclude", "something"); BeanFactoryInitializationAotContribution contribution = getContribution(environment); assertThat(contribution).isNull(); } private @Nullable BeanFactoryInitializationAotContribution getContribution(ConfigurableEnvironment environment) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { context.setEnvironment(environment); context.refresh(); return new StructuredLoggingJsonPropertiesBeanFactoryInitializationAotProcessor() .processAheadOfTime(context.getBeanFactory()); } } private RuntimeHints getRuntimeHints(BeanFactoryInitializationAotContribution contribution) { TestGenerationContext generationContext = new TestGenerationContext(); contribution.applyTo(generationContext, mock(BeanFactoryInitializationCode.class)); return generationContext.getRuntimeHints(); } static
StructuredLoggingJsonPropertiesBeanFactoryInitializationAotProcessorTests
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/MulticastDefinition.java
{ "start": 1635, "end": 25217 }
class ____ extends OutputDefinition<MulticastDefinition> implements ExecutorServiceAwareDefinition<MulticastDefinition> { @XmlTransient private ExecutorService executorServiceBean; @XmlTransient private AggregationStrategy aggregationStrategyBean; @XmlTransient private Processor onPrepareProcessor; @XmlAttribute @Metadata(javaType = "org.apache.camel.AggregationStrategy") private String aggregationStrategy; @XmlAttribute @Metadata(label = "advanced") private String aggregationStrategyMethodName; @XmlAttribute @Metadata(label = "advanced", javaType = "java.lang.Boolean") private String aggregationStrategyMethodAllowNull; @Deprecated(since = "4.7.0") @XmlAttribute @Metadata(label = "advanced", javaType = "java.lang.Boolean") private String parallelAggregate; @XmlAttribute @Metadata(javaType = "java.lang.Boolean") private String parallelProcessing; @XmlAttribute @Metadata(javaType = "java.lang.Boolean") private String synchronous; @XmlAttribute @Metadata(javaType = "java.lang.Boolean") private String streaming; @XmlAttribute @Metadata(label = "advanced", javaType = "java.lang.Boolean") private String stopOnException; @XmlAttribute @Metadata(label = "advanced", javaType = "java.time.Duration", defaultValue = "0") private String timeout; @XmlAttribute @Metadata(label = "advanced", javaType = "java.util.concurrent.ExecutorService") private String executorService; @XmlAttribute @Metadata(label = "advanced", javaType = "org.apache.camel.Processor") private String onPrepare; @XmlAttribute @Metadata(label = "advanced", javaType = "java.lang.Boolean") private String shareUnitOfWork; public MulticastDefinition() { } protected MulticastDefinition(MulticastDefinition source) { super(source); this.executorServiceBean = source.executorServiceBean; this.aggregationStrategyBean = source.aggregationStrategyBean; this.onPrepareProcessor = source.onPrepareProcessor; this.aggregationStrategy = source.aggregationStrategy; this.aggregationStrategyMethodName = source.aggregationStrategyMethodName; this.aggregationStrategyMethodAllowNull = source.aggregationStrategyMethodAllowNull; this.parallelAggregate = source.parallelAggregate; this.parallelProcessing = source.parallelProcessing; this.synchronous = source.synchronous; this.streaming = source.streaming; this.stopOnException = source.stopOnException; this.timeout = source.timeout; this.executorService = source.executorService; this.onPrepare = source.onPrepare; this.shareUnitOfWork = source.shareUnitOfWork; } @Override public MulticastDefinition copyDefinition() { return new MulticastDefinition(this); } @Override public List<ProcessorDefinition<?>> getOutputs() { return outputs; } @XmlElementRef @Override public void setOutputs(List<ProcessorDefinition<?>> outputs) { super.setOutputs(outputs); } @Override public String toString() { return "Multicast[" + getOutputs() + "]"; } @Override public String getShortName() { return "multicast"; } @Override public String getLabel() { return "multicast"; } // Fluent API // ------------------------------------------------------------------------- /** * Sets the AggregationStrategy to be used to assemble the replies from the multicasts, into a single outgoing * message from the Multicast using a fluent builder. */ public AggregationStrategyClause<MulticastDefinition> aggregationStrategy() { AggregationStrategyClause<MulticastDefinition> clause = new AggregationStrategyClause<>(this); setAggregationStrategy(clause); return clause; } /** * Sets the AggregationStrategy to be used to assemble the replies from the multicasts, into a single outgoing * message from the Multicast. By default Camel will use the last reply as the outgoing message. You can also use a * POJO as the AggregationStrategy. If an exception is thrown from the aggregate method in the AggregationStrategy, * then by default, that exception is not handled by the error handler. The error handler can be enabled to react if * enabling the shareUnitOfWork option. */ public MulticastDefinition aggregationStrategy(AggregationStrategy aggregationStrategy) { setAggregationStrategy(aggregationStrategy); return this; } /** * Sets a reference to the AggregationStrategy to be used to assemble the replies from the multicasts, into a single * outgoing message from the Multicast. By default Camel will use the last reply as the outgoing message. You can * also use a POJO as the AggregationStrategy. If an exception is thrown from the aggregate method in the * AggregationStrategy, then by default, that exception is not handled by the error handler. The error handler can * be enabled to react if enabling the shareUnitOfWork option. */ public MulticastDefinition aggregationStrategy(String aggregationStrategy) { setAggregationStrategy(aggregationStrategy); return this; } /** * This option can be used to explicit declare the method name to use, when using POJOs as the AggregationStrategy. * * @param methodName the method name to call * @return the builder */ public MulticastDefinition aggregationStrategyMethodName(String methodName) { setAggregationStrategyMethodName(methodName); return this; } /** * If this option is false then the aggregate method is not used if there was no data to enrich. If this option is * true then null values is used as the oldExchange (when no data to enrich), when using POJOs as the * AggregationStrategy * * @return the builder */ public MulticastDefinition aggregationStrategyMethodAllowNull() { setAggregationStrategyMethodAllowNull(Boolean.toString(true)); return this; } /** * If enabled then sending messages to the multicasts occurs concurrently. Note the caller thread will still wait * until all messages has been fully processed, before it continues. Its only the sending and processing the replies * from the multicasts which happens concurrently. * * When parallel processing is enabled, then the Camel routing engin will continue processing using last used thread * from the parallel thread pool. However, if you want to use the original thread that called the multicast, then * make sure to enable the synchronous option as well. * * In parallel processing mode, you may want to also synchronous = true to force this EIP to process the sub-tasks * using the upper bounds of the thread-pool. If using synchronous = false then Camel will allow its reactive * routing engine to use as many threads as possible, which may be available due to sub-tasks using other * thread-pools such as CompletableFuture.runAsync or others. * * @return the builder */ public MulticastDefinition parallelProcessing() { setParallelProcessing(Boolean.toString(true)); return this; } /** * If enabled then sending messages to the multicasts occurs concurrently. Note the caller thread will still wait * until all messages has been fully processed, before it continues. Its only the sending and processing the replies * from the multicasts which happens concurrently. * * When parallel processing is enabled, then the Camel routing engin will continue processing using last used thread * from the parallel thread pool. However, if you want to use the original thread that called the multicast, then * make sure to enable the synchronous option as well. * * In parallel processing mode, you may want to also synchronous = true to force this EIP to process the sub-tasks * using the upper bounds of the thread-pool. If using synchronous = false then Camel will allow its reactive * routing engine to use as many threads as possible, which may be available due to sub-tasks using other * thread-pools such as CompletableFuture.runAsync or others. * * @return the builder */ public MulticastDefinition parallelProcessing(String parallelProcessing) { setParallelProcessing(parallelProcessing); return this; } /** * If enabled then sending messages to the multicasts occurs concurrently. Note the caller thread will still wait * until all messages has been fully processed, before it continues. Its only the sending and processing the replies * from the multicasts which happens concurrently. * * When parallel processing is enabled, then the Camel routing engin will continue processing using last used thread * from the parallel thread pool. However, if you want to use the original thread that called the multicast, then * make sure to enable the synchronous option as well. * * In parallel processing mode, you may want to also synchronous = true to force this EIP to process the sub-tasks * using the upper bounds of the thread-pool. If using synchronous = false then Camel will allow its reactive * routing engine to use as many threads as possible, which may be available due to sub-tasks using other * thread-pools such as CompletableFuture.runAsync or others. * * @return the builder */ public MulticastDefinition parallelProcessing(boolean parallelProcessing) { setParallelProcessing(Boolean.toString(parallelProcessing)); return this; } /** * Sets whether synchronous processing should be strictly used. When enabled then the same thread is used to * continue routing after the multicast is complete, even if parallel processing is enabled. * * @return the builder */ public MulticastDefinition synchronous() { return synchronous(true); } /** * Sets whether synchronous processing should be strictly used. When enabled then the same thread is used to * continue routing after the multicast is complete, even if parallel processing is enabled. * * @return the builder */ public MulticastDefinition synchronous(boolean synchronous) { return synchronous(Boolean.toString(synchronous)); } /** * Sets whether synchronous processing should be strictly used. When enabled then the same thread is used to * continue routing after the multicast is complete, even if parallel processing is enabled. * * @return the builder */ public MulticastDefinition synchronous(String synchronous) { setSynchronous(synchronous); return this; } /** * If enabled then the aggregate method on AggregationStrategy can be called concurrently. Notice that this would * require the implementation of AggregationStrategy to be implemented as thread-safe. By default this is false * meaning that Camel synchronizes the call to the aggregate method. Though in some use-cases this can be used to * archive higher performance when the AggregationStrategy is implemented as thread-safe. * * @return the builder */ @Deprecated(since = "4.7.0") public MulticastDefinition parallelAggregate() { setParallelAggregate(Boolean.toString(true)); return this; } /** * If enabled then the aggregate method on AggregationStrategy can be called concurrently. Notice that this would * require the implementation of AggregationStrategy to be implemented as thread-safe. By default this is false * meaning that Camel synchronizes the call to the aggregate method. Though in some use-cases this can be used to * archive higher performance when the AggregationStrategy is implemented as thread-safe. * * @return the builder */ @Deprecated(since = "4.7.0") public MulticastDefinition parallelAggregate(boolean parallelAggregate) { setParallelAggregate(Boolean.toString(parallelAggregate)); return this; } /** * If enabled then the aggregate method on AggregationStrategy can be called concurrently. Notice that this would * require the implementation of AggregationStrategy to be implemented as thread-safe. By default this is false * meaning that Camel synchronizes the call to the aggregate method. Though in some use-cases this can be used to * archive higher performance when the AggregationStrategy is implemented as thread-safe. * * @return the builder */ @Deprecated(since = "4.7.0") public MulticastDefinition parallelAggregate(String parallelAggregate) { setParallelAggregate(parallelAggregate); return this; } /** * If enabled then Camel will process replies out-of-order, eg in the order they come back. If disabled, Camel will * process replies in the same order as defined by the multicast. * * @return the builder */ public MulticastDefinition streaming() { setStreaming(Boolean.toString(true)); return this; } /** * Will now stop further processing if an exception or failure occurred during processing of an * {@link org.apache.camel.Exchange} and the caused exception will be thrown. * <p/> * Will also stop if processing the exchange failed (has a fault message) or an exception was thrown and handled by * the error handler (such as using onException). In all situations the multicast will stop further processing. This * is the same behavior as in pipeline, which is used by the routing engine. * <p/> * The default behavior is to <b>not</b> stop but continue processing till the end * * @return the builder */ public MulticastDefinition stopOnException() { return stopOnException(Boolean.toString(true)); } /** * Will now stop further processing if an exception or failure occurred during processing of an * {@link org.apache.camel.Exchange} and the caused exception will be thrown. * <p/> * Will also stop if processing the exchange failed (has a fault message) or an exception was thrown and handled by * the error handler (such as using onException). In all situations the multicast will stop further processing. This * is the same behavior as in pipeline, which is used by the routing engine. * <p/> * The default behavior is to <b>not</b> stop but continue processing till the end * * @return the builder */ public MulticastDefinition stopOnException(String stopOnException) { setStopOnException(stopOnException); return this; } /** * To use a custom Thread Pool to be used for parallel processing. Notice if you set this option, then parallel * processing is automatically implied, and you do not have to enable that option as well. */ @Override public MulticastDefinition executorService(ExecutorService executorService) { this.executorServiceBean = executorService; return this; } /** * Refers to a custom Thread Pool to be used for parallel processing. Notice if you set this option, then parallel * processing is automatically implied, and you do not have to enable that option as well. */ @Override public MulticastDefinition executorService(String executorService) { setExecutorService(executorService); return this; } /** * Set the {@link Processor} to use when preparing the {@link org.apache.camel.Exchange} to be send using a fluent * builder. */ public ProcessClause<MulticastDefinition> onPrepare() { ProcessClause<MulticastDefinition> clause = new ProcessClause<>(this); this.onPrepareProcessor = clause; return clause; } /** * Uses the {@link Processor} when preparing the {@link org.apache.camel.Exchange} to be send. This can be used to * deep-clone messages that should be send, or any custom logic needed before the exchange is send. * * @param onPrepare the processor * @return the builder */ public MulticastDefinition onPrepare(Processor onPrepare) { this.onPrepareProcessor = onPrepare; return this; } /** * Uses the {@link Processor} when preparing the {@link org.apache.camel.Exchange} to be send. This can be used to * deep-clone messages that should be send, or any custom logic needed before the exchange is send. * * @param onPrepare reference to the processor to lookup in the {@link org.apache.camel.spi.Registry} * @return the builder */ public MulticastDefinition onPrepare(String onPrepare) { setOnPrepare(onPrepare); return this; } /** * Sets a total timeout specified in millis, when using parallel processing. If the Multicast hasn't been able to * send and process all replies within the given timeframe, then the timeout triggers and the Multicast breaks out * and continues. Notice if you provide a TimeoutAwareAggregationStrategy then the timeout method is invoked before * breaking out. If the timeout is reached with running tasks still remaining, certain tasks for which it is * difficult for Camel to shut down in a graceful manner may continue to run. So use this option with a bit of care. * * @param timeout timeout in millis * @return the builder */ public MulticastDefinition timeout(long timeout) { return timeout(Long.toString(timeout)); } /** * Sets a total timeout specified in millis, when using parallel processing. If the Multicast hasn't been able to * send and process all replies within the given timeframe, then the timeout triggers and the Multicast breaks out * and continues. Notice if you provide a TimeoutAwareAggregationStrategy then the timeout method is invoked before * breaking out. If the timeout is reached with running tasks still remaining, certain tasks for which it is * difficult for Camel to shut down in a graceful manner may continue to run. So use this option with a bit of care. * * @param timeout timeout in millis * @return the builder */ public MulticastDefinition timeout(String timeout) { setTimeout(timeout); return this; } /** * Shares the {@link org.apache.camel.spi.UnitOfWork} with the parent and each of the sub messages. Multicast will * by default not share unit of work between the parent exchange and each multicasted exchange. This means each sub * exchange has its own individual unit of work. * * @return the builder. */ public MulticastDefinition shareUnitOfWork() { setShareUnitOfWork(Boolean.toString(true)); return this; } public AggregationStrategy getAggregationStrategyBean() { return aggregationStrategyBean; } public Processor getOnPrepareProcessor() { return onPrepareProcessor; } @Override public ExecutorService getExecutorServiceBean() { return executorServiceBean; } @Override public String getExecutorServiceRef() { return executorService; } public String getParallelProcessing() { return parallelProcessing; } public void setParallelProcessing(String parallelProcessing) { this.parallelProcessing = parallelProcessing; } public String getSynchronous() { return synchronous; } public void setSynchronous(String synchronous) { this.synchronous = synchronous; } public String getStreaming() { return streaming; } public void setStreaming(String streaming) { this.streaming = streaming; } public String getStopOnException() { return stopOnException; } public void setStopOnException(String stopOnException) { this.stopOnException = stopOnException; } public String getAggregationStrategy() { return aggregationStrategy; } /** * Refers to an AggregationStrategy to be used to assemble the replies from the multicasts, into a single outgoing * message from the Multicast. By default Camel will use the last reply as the outgoing message. You can also use a * POJO as the AggregationStrategy */ public void setAggregationStrategy(String aggregationStrategy) { this.aggregationStrategy = aggregationStrategy; } /** * Refers to an AggregationStrategy to be used to assemble the replies from the multicasts, into a single outgoing * message from the Multicast. By default Camel will use the last reply as the outgoing message. You can also use a * POJO as the AggregationStrategy */ public void setAggregationStrategy(AggregationStrategy aggregationStrategy) { this.aggregationStrategyBean = aggregationStrategy; } public String getAggregationStrategyMethodName() { return aggregationStrategyMethodName; } /** * This option can be used to explicit declare the method name to use, when using POJOs as the AggregationStrategy. */ public void setAggregationStrategyMethodName(String aggregationStrategyMethodName) { this.aggregationStrategyMethodName = aggregationStrategyMethodName; } public String getAggregationStrategyMethodAllowNull() { return aggregationStrategyMethodAllowNull; } /** * If this option is false then the aggregate method is not used if there was no data to enrich. If this option is * true then null values is used as the oldExchange (when no data to enrich), when using POJOs as the * AggregationStrategy */ public void setAggregationStrategyMethodAllowNull(String aggregationStrategyMethodAllowNull) { this.aggregationStrategyMethodAllowNull = aggregationStrategyMethodAllowNull; } public String getExecutorService() { return executorService; } /** * Refers to a custom Thread Pool to be used for parallel processing. Notice if you set this option, then parallel * processing is automatic implied, and you do not have to enable that option as well. */ public void setExecutorService(String executorService) { this.executorService = executorService; } public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } public String getShareUnitOfWork() { return shareUnitOfWork; } public void setShareUnitOfWork(String shareUnitOfWork) { this.shareUnitOfWork = shareUnitOfWork; } @Deprecated(since = "4.7.0") public String getParallelAggregate() { return parallelAggregate; } @Deprecated(since = "4.7.0") public void setParallelAggregate(String parallelAggregate) { this.parallelAggregate = parallelAggregate; } public String getOnPrepare() { return onPrepare; } public void setOnPrepare(String onPrepare) { this.onPrepare = onPrepare; } }
MulticastDefinition
java
google__dagger
javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java
{ "start": 28667, "end": 29112 }
interface ____ {"); } }); } @Test public void grandchildBindingConflictsWithGrandparent() { Source aComponent = CompilerTests.javaSource( "test.A", "package test;", "", "import dagger.Component;", "import dagger.Module;", "import dagger.Provides;", "", "@Component(modules = A.AModule.class)", "
A
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/Spr12278Tests.java
{ "start": 2112, "end": 2378 }
class ____ { private final String autowiredName; // No @Autowired - implicit wiring @SuppressWarnings("unused") public SingleConstructorComponent(String autowiredName) { this.autowiredName = autowiredName; } } private static
SingleConstructorComponent
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/common/search/aggregations/MissingHelper.java
{ "start": 681, "end": 1855 }
class ____ implements Releasable { private final BigArrays bigArrays; private BitArray tracker; public MissingHelper(BigArrays bigArrays) { this.bigArrays = bigArrays; } public void markMissing(long index) { if (tracker == null) { tracker = new BitArray(index, bigArrays); } tracker.set(index); } public void markNotMissing(long index) { if (tracker == null) { return; } tracker.clear(index); } public void swap(long lhs, long rhs) { if (tracker == null) { return; } boolean backup = tracker.get(lhs); if (tracker.get(rhs)) { tracker.set(lhs); } else { tracker.clear(lhs); } if (backup) { tracker.set(rhs); } else { tracker.clear(rhs); } } public boolean isEmpty(long index) { if (tracker == null) { return false; } return tracker.get(index); } @Override public void close() { if (tracker != null) { tracker.close(); } } }
MissingHelper
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/bidirectional/BiDirectionalOneToOneFetchTest.java
{ "start": 7507, "end": 7631 }
class ____ { @Id private Long id; public EntityC() { } public EntityC(Long id) { this.id = id; } } }
EntityC
java
google__auto
common/src/main/java/com/google/auto/common/Overrides.java
{ "start": 2881, "end": 6868 }
class ____ extends Overrides { private final Types typeUtils; ExplicitOverrides(Types typeUtils) { this.typeUtils = typeUtils; } @Override public boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement in) { if (!overrider.getSimpleName().equals(overridden.getSimpleName())) { // They must have the same name. return false; } // We should just be able to write overrider.equals(overridden) here, but that runs afoul // of a problem with Eclipse. If for example you look at the method Stream<E> stream() in // Collection<E>, as obtained by collectionTypeElement.getEnclosedElements(), it will not // compare equal to the method Stream<E> stream() as obtained by // elementUtils.getAllMembers(listTypeElement), even though List<E> inherits the method // from Collection<E>. The reason is that, in ecj, getAllMembers does type substitution, // so the return type of stream() is Stream<E'>, where E' is the E from List<E> rather than // the one from Collection<E>. Instead we compare the enclosing element, which will be // Collection<E> no matter how we got the method. If two methods are in the same type // then it's impossible for one to override the other, regardless of whether they are the // same method. if (overrider.getEnclosingElement().equals(overridden.getEnclosingElement())) { return false; } if (overridden.getModifiers().contains(Modifier.STATIC)) { // Static methods can't be overridden (though they can be hidden by other static methods). return false; } if (overrider.getParameters().size() != overridden.getParameters().size()) { // One method can't override another if they have a different number of parameters. // Varargs `Foo...` appears as `Foo[]` here; there is a separate // ExecutableElement.isVarArgs() method to tell whether a method is varargs, but that has no // effect on override logic. // The check here isn't strictly needed but avoids unnecessary work. return false; } Visibility overriddenVisibility = Visibility.ofElement(overridden); Visibility overriderVisibility = Visibility.ofElement(overrider); if (overriddenVisibility.equals(Visibility.PRIVATE) || overriderVisibility.compareTo(overriddenVisibility) < 0) { // Private methods can't be overridden, and methods can't be overridden by less-visible // methods. The latter condition is enforced by the compiler so in theory we might report // an "incorrect" result here for code that javac would not have allowed. return false; } if (!isSubsignature(overrider, overridden, in)) { return false; } if (!MoreElements.methodVisibleFromPackage(overridden, MoreElements.getPackage(overrider))) { // If the overridden method is a package-private method in a different package then it // can't be overridden. return false; } if (!MoreElements.isType(overridden.getEnclosingElement())) { return false; // We don't know how this could happen but we avoid blowing up if it does. } TypeElement overriddenType = MoreElements.asType(overridden.getEnclosingElement()); // We erase the types before checking subtypes, because the TypeMirror we get for List<E> is // not a subtype of the one we get for Collection<E> since the two E instances are not the // same. For the purposes of overriding, type parameters in the containing type should not // matter because if the code compiles at all then they must be consistent. if (!typeUtils.isSubtype( typeUtils.erasure(in.asType()), typeUtils.erasure(overriddenType.asType()))) { return false; } if (in.getKind().isClass()) { // Method mC in or inherited by
ExplicitOverrides
java
apache__camel
components/camel-fhir/camel-fhir-component/src/main/java/org/apache/camel/component/fhir/FhirEndpoint.java
{ "start": 2780, "end": 7345 }
class ____ extends AbstractApiEndpoint<FhirApiName, FhirConfiguration> implements EndpointServiceLocation { private static final String EXTRA_PARAMETERS_PROPERTY = "extraParameters"; private Object apiProxy; @UriParam private FhirConfiguration configuration; public FhirEndpoint(String uri, FhirComponent component, FhirApiName apiName, String methodName, FhirConfiguration endpointConfiguration) { super(uri, component, apiName, methodName, FhirApiCollection.getCollection().getHelper(apiName), endpointConfiguration); this.configuration = endpointConfiguration; } @Override public String getServiceUrl() { return configuration.getServerUrl(); } @Override public String getServiceProtocol() { return "fhir"; } @Override public Map<String, String> getServiceMetadata() { if (configuration.getUsername() != null) { return Map.of("username", configuration.getUsername()); } return null; } @Override public Producer createProducer() throws Exception { return new FhirProducer(this); } @Override public Consumer createConsumer(Processor processor) throws Exception { // make sure inBody is not set for consumers if (inBody != null) { throw new IllegalArgumentException("Option inBody is not supported for consumer endpoint"); } final FhirConsumer consumer = new FhirConsumer(this, processor); // also set consumer.* properties configureConsumer(consumer); return consumer; } @Override protected ApiMethodPropertiesHelper<FhirConfiguration> getPropertiesHelper() { return FhirPropertiesHelper.getHelper(getCamelContext()); } @Override protected String getThreadProfileName() { return FhirConstants.THREAD_PROFILE_NAME; } @Override protected void afterConfigureProperties() { IGenericClient client = getClient(); switch (apiName) { case CAPABILITIES: apiProxy = new FhirCapabilities(client); break; case CREATE: apiProxy = new FhirCreate(client); break; case DELETE: apiProxy = new FhirDelete(client); break; case HISTORY: apiProxy = new FhirHistory(client); break; case LOAD_PAGE: apiProxy = new FhirLoadPage(client); break; case META: apiProxy = new FhirMeta(client); break; case OPERATION: apiProxy = new FhirOperation(client); break; case PATCH: apiProxy = new FhirPatch(client); break; case READ: apiProxy = new FhirRead(client); break; case SEARCH: apiProxy = new FhirSearch(client); break; case TRANSACTION: apiProxy = new FhirTransaction(client); break; case UPDATE: apiProxy = new FhirUpdate(client); break; case VALIDATE: apiProxy = new FhirValidate(client); break; default: throw new IllegalArgumentException("Invalid API name " + apiName); } } @Override public void interceptProperties(Map<String, Object> properties) { Map<ExtraParameters, Object> extraProperties = getExtraParameters(properties); for (ExtraParameters extraParameter : ExtraParameters.values()) { Object value = properties.get(extraParameter.getParam()); if (value != null) { extraProperties.put(extraParameter, value); } } properties.put(EXTRA_PARAMETERS_PROPERTY, extraProperties); } public IGenericClient getClient() { return configuration.getClient(); } private Map<ExtraParameters, Object> getExtraParameters(Map<String, Object> properties) { Object extraParameters = properties.get(EXTRA_PARAMETERS_PROPERTY); if (extraParameters == null) { return new EnumMap<>(ExtraParameters.class); } return (Map<ExtraParameters, Object>) extraParameters; } @Override public Object getApiProxy(ApiMethod method, Map<String, Object> args) { return apiProxy; } }
FhirEndpoint
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptivebatch/PointwiseBlockingResultInfoTest.java
{ "start": 1273, "end": 3689 }
class ____ { @Test void testGetNumBytesProduced() { PointwiseBlockingResultInfo resultInfo = new PointwiseBlockingResultInfo(new IntermediateDataSetID(), 2, 2); resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {32L, 32L})); resultInfo.recordPartitionInfo(1, new ResultPartitionBytes(new long[] {64L, 64L})); assertThat(resultInfo.getNumBytesProduced()).isEqualTo(192L); } @Test void testGetNumBytesProducedWithIndexRange() { PointwiseBlockingResultInfo resultInfo = new PointwiseBlockingResultInfo(new IntermediateDataSetID(), 2, 2); resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {32L, 64L})); resultInfo.recordPartitionInfo(1, new ResultPartitionBytes(new long[] {128L, 256L})); IndexRange partitionIndexRange = new IndexRange(0, 0); IndexRange subpartitionIndexRange = new IndexRange(0, 1); assertThat(resultInfo.getNumBytesProduced(partitionIndexRange, subpartitionIndexRange)) .isEqualTo(96L); } @Test void testGetBytesWithPartialPartitionInfos() { PointwiseBlockingResultInfo resultInfo = new PointwiseBlockingResultInfo(new IntermediateDataSetID(), 2, 2); resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {32L, 64L})); assertThatThrownBy(resultInfo::getNumBytesProduced) .isInstanceOf(IllegalStateException.class); } @Test void testPartitionFinishedMultiTimes() { PointwiseBlockingResultInfo resultInfo = new PointwiseBlockingResultInfo(new IntermediateDataSetID(), 2, 2); resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {32L, 64L})); resultInfo.recordPartitionInfo(1, new ResultPartitionBytes(new long[] {64L, 128L})); assertThat(resultInfo.getNumOfRecordedPartitions()).isEqualTo(2); assertThat(resultInfo.getNumBytesProduced()).isEqualTo(288L); // reset partition info resultInfo.resetPartitionInfo(0); assertThat(resultInfo.getNumOfRecordedPartitions()).isOne(); // record partition info again resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {64L, 128L})); assertThat(resultInfo.getNumBytesProduced()).isEqualTo(384L); } }
PointwiseBlockingResultInfoTest
java
apache__camel
components/camel-slack/src/generated/java/org/apache/camel/component/slack/SlackEndpointConfigurer.java
{ "start": 732, "end": 11419 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { SlackEndpoint target = (SlackEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "backofferrorthreshold": case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true; case "backoffidlethreshold": case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true; case "backoffmultiplier": case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "conversationtype": case "conversationType": target.setConversationType(property(camelContext, com.slack.api.model.ConversationType.class, value)); return true; case "delay": target.setDelay(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true; case "iconemoji": case "iconEmoji": target.setIconEmoji(property(camelContext, java.lang.String.class, value)); return true; case "iconurl": case "iconUrl": target.setIconUrl(property(camelContext, java.lang.String.class, value)); return true; case "initialdelay": case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "maxresults": case "maxResults": target.setMaxResults(property(camelContext, java.lang.String.class, value)); return true; case "naturalorder": case "naturalOrder": target.setNaturalOrder(property(camelContext, boolean.class, value)); return true; case "pollstrategy": case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true; case "repeatcount": case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true; case "runlogginglevel": case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true; case "scheduledexecutorservice": case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true; case "scheduler": target.setScheduler(property(camelContext, java.lang.Object.class, value)); return true; case "schedulerproperties": case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true; case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true; case "serverurl": case "serverUrl": target.setServerUrl(property(camelContext, java.lang.String.class, value)); return true; case "startscheduler": case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true; case "timeunit": case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true; case "token": target.setToken(property(camelContext, java.lang.String.class, value)); return true; case "usefixeddelay": case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true; case "username": target.setUsername(property(camelContext, java.lang.String.class, value)); return true; case "webhookurl": case "webhookUrl": target.setWebhookUrl(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "backofferrorthreshold": case "backoffErrorThreshold": return int.class; case "backoffidlethreshold": case "backoffIdleThreshold": return int.class; case "backoffmultiplier": case "backoffMultiplier": return int.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "conversationtype": case "conversationType": return com.slack.api.model.ConversationType.class; case "delay": return long.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "greedy": return boolean.class; case "iconemoji": case "iconEmoji": return java.lang.String.class; case "iconurl": case "iconUrl": return java.lang.String.class; case "initialdelay": case "initialDelay": return long.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "maxresults": case "maxResults": return java.lang.String.class; case "naturalorder": case "naturalOrder": return boolean.class; case "pollstrategy": case "pollStrategy": return org.apache.camel.spi.PollingConsumerPollStrategy.class; case "repeatcount": case "repeatCount": return long.class; case "runlogginglevel": case "runLoggingLevel": return org.apache.camel.LoggingLevel.class; case "scheduledexecutorservice": case "scheduledExecutorService": return java.util.concurrent.ScheduledExecutorService.class; case "scheduler": return java.lang.Object.class; case "schedulerproperties": case "schedulerProperties": return java.util.Map.class; case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": return boolean.class; case "serverurl": case "serverUrl": return java.lang.String.class; case "startscheduler": case "startScheduler": return boolean.class; case "timeunit": case "timeUnit": return java.util.concurrent.TimeUnit.class; case "token": return java.lang.String.class; case "usefixeddelay": case "useFixedDelay": return boolean.class; case "username": return java.lang.String.class; case "webhookurl": case "webhookUrl": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { SlackEndpoint target = (SlackEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "backofferrorthreshold": case "backoffErrorThreshold": return target.getBackoffErrorThreshold(); case "backoffidlethreshold": case "backoffIdleThreshold": return target.getBackoffIdleThreshold(); case "backoffmultiplier": case "backoffMultiplier": return target.getBackoffMultiplier(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "conversationtype": case "conversationType": return target.getConversationType(); case "delay": return target.getDelay(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "greedy": return target.isGreedy(); case "iconemoji": case "iconEmoji": return target.getIconEmoji(); case "iconurl": case "iconUrl": return target.getIconUrl(); case "initialdelay": case "initialDelay": return target.getInitialDelay(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "maxresults": case "maxResults": return target.getMaxResults(); case "naturalorder": case "naturalOrder": return target.isNaturalOrder(); case "pollstrategy": case "pollStrategy": return target.getPollStrategy(); case "repeatcount": case "repeatCount": return target.getRepeatCount(); case "runlogginglevel": case "runLoggingLevel": return target.getRunLoggingLevel(); case "scheduledexecutorservice": case "scheduledExecutorService": return target.getScheduledExecutorService(); case "scheduler": return target.getScheduler(); case "schedulerproperties": case "schedulerProperties": return target.getSchedulerProperties(); case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": return target.isSendEmptyMessageWhenIdle(); case "serverurl": case "serverUrl": return target.getServerUrl(); case "startscheduler": case "startScheduler": return target.isStartScheduler(); case "timeunit": case "timeUnit": return target.getTimeUnit(); case "token": return target.getToken(); case "usefixeddelay": case "useFixedDelay": return target.isUseFixedDelay(); case "username": return target.getUsername(); case "webhookurl": case "webhookUrl": return target.getWebhookUrl(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "schedulerproperties": case "schedulerProperties": return java.lang.Object.class; default: return null; } } }
SlackEndpointConfigurer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryParenthesesTest.java
{ "start": 4249, "end": 4558 }
class ____ { Function<Void, Function<Void, Void>> r = x -> (y -> y); } """) .doTest(); } @Test public void lambda() { helper .addSourceLines( "Test.java", """ import java.util.function.Function;
Test
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/client/ClientHttpResponse.java
{ "start": 1115, "end": 1707 }
interface ____ extends HttpInputMessage, Closeable { /** * Get the HTTP status code as an {@link HttpStatusCode}. * @return the HTTP status as {@code HttpStatusCode} value (never {@code null}) * @throws IOException in case of I/O errors */ HttpStatusCode getStatusCode() throws IOException; /** * Get the HTTP status text of the response. * @return the HTTP status text * @throws IOException in case of I/O errors */ String getStatusText() throws IOException; /** * Close this response, freeing any resources created. */ @Override void close(); }
ClientHttpResponse
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableRetryPredicate.java
{ "start": 981, "end": 1684 }
class ____<T> extends AbstractObservableWithUpstream<T, T> { final Predicate<? super Throwable> predicate; final long count; public ObservableRetryPredicate(Observable<T> source, long count, Predicate<? super Throwable> predicate) { super(source); this.predicate = predicate; this.count = count; } @Override public void subscribeActual(Observer<? super T> observer) { SequentialDisposable sa = new SequentialDisposable(); observer.onSubscribe(sa); RepeatObserver<T> rs = new RepeatObserver<>(observer, count, predicate, sa, source); rs.subscribeNext(); } static final
ObservableRetryPredicate
java
quarkusio__quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/WhenSectionHelper.java
{ "start": 662, "end": 3498 }
class ____ implements SectionHelper { private static final String VALUE = "value"; private static final String WHEN = "when"; private static final String SWITCH = "switch"; private static final String IS = "is"; private static final String CASE = "case"; private static final String ELSE = "else"; private final Expression value; private final List<CaseBlock> caseBlocks; WhenSectionHelper(SectionInitContext context) { this.value = context.getExpression(VALUE); ImmutableList.Builder<CaseBlock> builder = ImmutableList.builder(); for (SectionBlock block : context.getBlocks()) { if (!SectionHelperFactory.MAIN_BLOCK_NAME.equals(block.label)) { switch (block.label) { case IS: case CASE: case ELSE: builder.add(new CaseBlock(block, context)); break; case SectionHelperFactory.MAIN_BLOCK_NAME: break; default: // This should never happen throw new TemplateException("Invalid block: " + block); } } } this.caseBlocks = builder.build(); } @Override public CompletionStage<ResultNode> resolve(SectionResolutionContext context) { return context.resolutionContext().evaluate(value) .thenCompose(value -> { if (value != null && value.getClass().isEnum()) { return resolveEnumCaseBlocks(context, value, caseBlocks); } return resolveCaseBlocks(context, value, caseBlocks.iterator()); }); } CompletionStage<ResultNode> resolveCaseBlocks(SectionResolutionContext context, Object value, Iterator<CaseBlock> caseBlocks) { CaseBlock caseBlock = caseBlocks.next(); return caseBlock.resolve(context, value).thenCompose(r -> { if (r) { return context.execute(caseBlock.block, context.resolutionContext()); } else { if (caseBlocks.hasNext()) { return resolveCaseBlocks(context, value, caseBlocks); } else { return ResultNode.NOOP; } } }); } CompletionStage<ResultNode> resolveEnumCaseBlocks(SectionResolutionContext context, Object value, List<CaseBlock> caseBlocks) { for (CaseBlock caseBlock : caseBlocks) { if (caseBlock.resolveEnum(context, value)) { return context.execute(caseBlock.block, context.resolutionContext()); } } return ResultNode.NOOP; } public static
WhenSectionHelper
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/security/auth/KafkaPrincipal.java
{ "start": 2405, "end": 4154 }
class ____ implements Principal { public static final String USER_TYPE = "User"; public static final KafkaPrincipal ANONYMOUS = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "ANONYMOUS"); private final String principalType; private final String name; private volatile boolean tokenAuthenticated; public KafkaPrincipal(String principalType, String name) { this(principalType, name, false); } public KafkaPrincipal(String principalType, String name, boolean tokenAuthenticated) { this.principalType = requireNonNull(principalType, "Principal type cannot be null"); this.name = requireNonNull(name, "Principal name cannot be null"); this.tokenAuthenticated = tokenAuthenticated; } @Override public String toString() { return principalType + ":" + name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; KafkaPrincipal that = (KafkaPrincipal) o; return principalType.equals(that.principalType) && name.equals(that.name); } @Override public int hashCode() { int result = principalType != null ? principalType.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); return result; } @Override public String getName() { return name; } public String getPrincipalType() { return principalType; } public void tokenAuthenticated(boolean tokenAuthenticated) { this.tokenAuthenticated = tokenAuthenticated; } public boolean tokenAuthenticated() { return tokenAuthenticated; } }
KafkaPrincipal
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorBuilder.java
{ "start": 2271, "end": 7325 }
class ____ { private final RpcService rpcService; private final HighAvailabilityServices haServices; private ResourceID resourceId = ResourceID.generate(); private Configuration configuration = new Configuration(); @Nullable private TaskManagerConfiguration taskManagerConfiguration = null; @Nullable private TaskManagerServices taskManagerServices = null; private ExternalResourceInfoProvider externalResourceInfoProvider = ExternalResourceInfoProvider.NO_EXTERNAL_RESOURCES; private HeartbeatServices heartbeatServices = new HeartbeatServicesImpl(1 << 20, 1 << 20); private TaskManagerMetricGroup taskManagerMetricGroup = UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup(); @Nullable private String metricQueryServiceAddress = null; @Nullable private BlobCacheService taskExecutorBlobService = null; private FatalErrorHandler fatalErrorHandler = NoOpFatalErrorHandler.INSTANCE; private TaskExecutorPartitionTracker partitionTracker = new TestingTaskExecutorPartitionTracker(); private final WorkingDirectory workingDirectory; private TaskExecutorBuilder( RpcService rpcService, HighAvailabilityServices haServices, WorkingDirectory workingDirectory) { this.rpcService = rpcService; this.haServices = haServices; this.workingDirectory = workingDirectory; } public TaskExecutorBuilder setConfiguration(Configuration configuration) { this.configuration = configuration; return this; } public TaskExecutorBuilder setResourceId(ResourceID resourceId) { this.resourceId = resourceId; return this; } public TaskExecutor build() throws Exception { final TaskExecutorBlobService resolvedTaskExecutorBlobService; TaskExecutorResourceUtils.adjustForLocalExecution(configuration); if (taskExecutorBlobService == null) { resolvedTaskExecutorBlobService = NoOpTaskExecutorBlobService.INSTANCE; } else { resolvedTaskExecutorBlobService = taskExecutorBlobService; } final TaskExecutorResourceSpec taskExecutorResourceSpec = TaskExecutorResourceUtils.resourceSpecFromConfigForLocalExecution(configuration); final TaskManagerConfiguration resolvedTaskManagerConfiguration; if (taskManagerConfiguration == null) { resolvedTaskManagerConfiguration = TaskManagerConfiguration.fromConfiguration( configuration, taskExecutorResourceSpec, rpcService.getAddress(), workingDirectory.getTmpDirectory()); } else { resolvedTaskManagerConfiguration = taskManagerConfiguration; } final TaskManagerServices resolvedTaskManagerServices; if (taskManagerServices == null) { final TaskManagerServicesConfiguration taskManagerServicesConfiguration = TaskManagerServicesConfiguration.fromConfiguration( configuration, resourceId, rpcService.getAddress(), true, taskExecutorResourceSpec, workingDirectory); resolvedTaskManagerServices = TaskManagerServices.fromConfiguration( taskManagerServicesConfiguration, VoidPermanentBlobService.INSTANCE, UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup(), Executors.newDirectExecutorService(), rpcService.getScheduledExecutor(), throwable -> {}, workingDirectory); } else { resolvedTaskManagerServices = taskManagerServices; } final DelegationTokenReceiverRepository delegationTokenReceiverRepository = new DelegationTokenReceiverRepository(configuration, null); return new TaskExecutor( rpcService, resolvedTaskManagerConfiguration, haServices, resolvedTaskManagerServices, externalResourceInfoProvider, heartbeatServices, taskManagerMetricGroup, metricQueryServiceAddress, resolvedTaskExecutorBlobService, fatalErrorHandler, partitionTracker, delegationTokenReceiverRepository); } public static TaskExecutorBuilder newBuilder( RpcService rpcService, HighAvailabilityServices highAvailabilityServices, WorkingDirectory workingDirectory) { return new TaskExecutorBuilder(rpcService, highAvailabilityServices, workingDirectory); } }
TaskExecutorBuilder
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java
{ "start": 5506, "end": 5573 }
class ____ extends BarTestCase { @Configuration static
BazTestCase
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/processor/internals/InternalTopologyBuilderTest.java
{ "start": 70446, "end": 71436 }
class ____ implements ProcessorWrapper { @Override public <KIn, VIn, KOut, VOut> WrappedProcessorSupplier<KIn, VIn, KOut, VOut> wrapProcessorSupplier(final String processorName, final ProcessorSupplier<KIn, VIn, KOut, VOut> processorSupplier) { return () -> (Processor<KIn, VIn, KOut, VOut>) record -> { // do nothing }; } @Override public <KIn, VIn, VOut> WrappedFixedKeyProcessorSupplier<KIn, VIn, VOut> wrapFixedKeyProcessorSupplier(final String processorName, final FixedKeyProcessorSupplier<KIn, VIn, VOut> processorSupplier) { return () -> (FixedKeyProcessor<KIn, VIn, VOut>) record -> { // do nothing }; } } }
ProcessorSkippingWrapper
java
google__error-prone
check_api/src/main/java/com/google/errorprone/matchers/Throws.java
{ "start": 975, "end": 1553 }
class ____ implements Matcher<StatementTree> { private final Matcher<? super ExpressionTree> thrownMatcher; /** * New matcher for a {@code throw} statement where the thrown item is matched by the passed {@code * thrownMatcher}. */ public Throws(Matcher<? super ExpressionTree> thrownMatcher) { this.thrownMatcher = thrownMatcher; } @Override public boolean matches(StatementTree expressionTree, VisitorState state) { return expressionTree instanceof ThrowTree throwTree && thrownMatcher.matches(throwTree.getExpression(), state); } }
Throws
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldBoolArrayTest.java
{ "start": 170, "end": 684 }
class ____ extends TestCase { public void test_intArray() throws Exception { Model model = JSON.parseObject("{\"value\":[1,null,true,false,0]}", Model.class); assertNotNull(model.value); assertEquals(5, model.value.length); assertEquals(true, model.value[0]); assertEquals(false, model.value[1]); assertEquals(true, model.value[2]); assertEquals(false, model.value[3]); assertEquals(false, model.value[4]); } public static
FieldBoolArrayTest
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/operators/SelectorFunctionKeysTest.java
{ "start": 6230, "end": 6508 }
class ____ implements KeySelector<PojoWithMultiplePojos, Tuple2<Integer, String>> { @Override public Tuple2<Integer, String> getKey(PojoWithMultiplePojos v) { return new Tuple2<>(v.i0, v.p1.b); } } public static
KeySelector3
java
apache__avro
lang/java/ipc/src/main/java/org/apache/avro/ipc/SaslSocketTransceiver.java
{ "start": 1524, "end": 1749 }
class ____ extends Transceiver { private static final Logger LOG = LoggerFactory.getLogger(SaslSocketTransceiver.class); private static final ByteBuffer EMPTY = ByteBuffer.allocate(0); private static
SaslSocketTransceiver
java
apache__camel
components/camel-rss/src/test/java/org/apache/camel/component/rss/RssEntryPollingConsumerTest.java
{ "start": 1040, "end": 1617 }
class ____ extends CamelTestSupport { @Test public void testListOfEntriesIsSplitIntoPieces() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(10); mock.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("rss:file:src/test/data/rss20.xml?splitEntries=true&sortEntries=true&delay=100").to("mock:result"); } }; } }
RssEntryPollingConsumerTest
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/sink/abilities/SupportsTargetColumnWriting.java
{ "start": 2300, "end": 2746 }
interface ____ { /** * Provides an array of column index paths related to user specified target column list. * * <p>See the documentation of {@link SupportsTargetColumnWriting} for more information. * * @param targetColumns column index paths * @return true if the target columns are applied successfully, false otherwise. */ boolean applyTargetColumns(int[][] targetColumns); }
SupportsTargetColumnWriting
java
apache__rocketmq
controller/src/main/java/org/apache/rocketmq/controller/impl/task/BrokerCloseChannelResponse.java
{ "start": 990, "end": 1291 }
class ____ implements CommandCustomHeader { public BrokerCloseChannelResponse() { } @Override public void checkFields() throws RemotingCommandException { } @Override public String toString() { return "BrokerCloseChannelResponse{}"; } }
BrokerCloseChannelResponse
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/StreamCachingChoiceTest.java
{ "start": 1058, "end": 2765 }
class ____ extends ContextTestSupport { private static final String TEST_FILE = "src/test/resources/org/apache/camel/converter/stream/test.xml"; @Test public void testStreamCaching() throws Exception { getMockEndpoint("mock:paris").expectedMessageCount(0); getMockEndpoint("mock:madrid").expectedMessageCount(0); getMockEndpoint("mock:london").expectedMessageCount(1); getMockEndpoint("mock:other").expectedMessageCount(1); File file = new File(TEST_FILE); FileInputStreamCache cache = new FileInputStreamCache(file); template.sendBody("direct:start", cache); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start") .choice() .when().simple("${body} contains 'Paris'") .to("mock:paris") .when().simple("${body} contains 'London'") .to("mock:london") .otherwise() .to("mock:other") .end() .choice() .when().simple("${body} contains 'Paris'") .to("mock:paris") .when().simple("${body} contains 'Madrid'") .to("mock:madrid") .otherwise() .to("mock:other") .end(); } }; } }
StreamCachingChoiceTest
java
apache__logging-log4j2
log4j-iostreams/src/main/java/org/apache/logging/log4j/io/internal/InternalWriter.java
{ "start": 1195, "end": 2607 }
class ____ extends Writer { private final CharStreamLogger logger; private final String fqcn; public InternalWriter(final ExtendedLogger logger, final String fqcn, final Level level, final Marker marker) { this.logger = new CharStreamLogger(logger, level, marker); this.fqcn = fqcn; } @Override public void close() throws IOException { this.logger.close(this.fqcn); } @Override public void flush() throws IOException { // do nothing } @Override public String toString() { return this.getClass().getSimpleName() + "[fqcn=" + this.fqcn + ", logger=" + this.logger + "]"; } @Override public void write(final char[] cbuf) throws IOException { this.logger.put(this.fqcn, cbuf, 0, cbuf.length); } @Override public void write(final char[] cbuf, final int off, final int len) throws IOException { this.logger.put(this.fqcn, cbuf, off, len); } @Override public void write(final int c) throws IOException { this.logger.put(this.fqcn, (char) c); } @Override public void write(final String str) throws IOException { this.logger.put(this.fqcn, str, 0, str.length()); } @Override public void write(final String str, final int off, final int len) throws IOException { this.logger.put(this.fqcn, str, off, len); } }
InternalWriter
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvtVO/ae/huangliang2/Floor.java
{ "start": 151, "end": 185 }
interface ____ extends Area { }
Floor
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/security/DuplicatedNamedAuthPolicyValidationFailureTest.java
{ "start": 1431, "end": 1843 }
class ____ implements HttpSecurityPolicy { @Override public Uni<CheckResult> checkPermission(RoutingContext request, Uni<SecurityIdentity> identity, AuthorizationRequestContext requestContext) { return null; } @Override public String name() { return POLICY_NAME; } } @ApplicationScoped public static
NamedPolicy_1
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/PersistenceUnit.java
{ "start": 1431, "end": 1815 }
class ____ extends AnnotationLiteral<PersistenceUnit> implements PersistenceUnit { private String name; public PersistenceUnitLiteral(String name) { this.name = name; } @Override public String value() { return name; } } @Target(PACKAGE) @Retention(RUNTIME) @Documented @
PersistenceUnitLiteral
java
spring-projects__spring-boot
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java
{ "start": 15265, "end": 15326 }
class ____ too * long. */ @FunctionalInterface public
takes
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/JsonTypeInfoIgnored2968Test.java
{ "start": 1386, "end": 1435 }
class ____ extends Animal {} static abstract
Dog
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestProtosLegacy.java
{ "start": 58170, "end": 65334 }
class ____ extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_EchoResponseProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_EchoResponseProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto.class, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto.Builder.class); } // Construct using org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); message_ = ""; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_EchoResponseProto_descriptor; } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto getDefaultInstanceForType() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto.getDefaultInstance(); } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto build() { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto buildPartial() { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto result = new org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.message_ = message_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto) { return mergeFrom((org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto other) { if (other == org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto.getDefaultInstance()) return this; if (other.hasMessage()) { bitField0_ |= 0x00000001; message_ = other.message_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasMessage()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required string message = 1; private java.lang.Object message_ = ""; /** * <code>required string message = 1;</code> */ public boolean hasMessage() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string message = 1;</code> */ public java.lang.String getMessage() { java.lang.Object ref = message_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); message_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string message = 1;</code> */ public com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string message = 1;</code> */ public Builder setMessage( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; message_ = value; onChanged(); return this; } /** * <code>required string message = 1;</code> */ public Builder clearMessage() { bitField0_ = (bitField0_ & ~0x00000001); message_ = getDefaultInstance().getMessage(); onChanged(); return this; } /** * <code>required string message = 1;</code> */ public Builder setMessageBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; message_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:hadoop.common.EchoResponseProto) } static { defaultInstance = new EchoResponseProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:hadoop.common.EchoResponseProto) } public
Builder
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/MetadataUpdater.java
{ "start": 1467, "end": 4229 }
interface ____ extends Closeable { /** * Gets the current cluster info without blocking. */ List<Node> fetchNodes(); /** * Returns true if an update to the cluster metadata info is due. */ boolean isUpdateDue(long now); /** * Starts a cluster metadata update if needed and possible. Returns the time until the metadata update (which would * be 0 if an update has been started as a result of this call). * * If the implementation relies on `NetworkClient` to send requests, `handleSuccessfulResponse` will be * invoked after the metadata response is received. * * The semantics of `needed` and `possible` are implementation-dependent and may take into account a number of * factors like node availability, how long since the last metadata update, etc. */ long maybeUpdate(long now); /** * Handle a server disconnect. * * This provides a mechanism for the `MetadataUpdater` implementation to use the NetworkClient instance for its own * requests with special handling for disconnections of such requests. * * @param now Current time in milliseconds * @param nodeId The id of the node that disconnected * @param maybeAuthException Optional authentication error */ void handleServerDisconnect(long now, String nodeId, Optional<AuthenticationException> maybeAuthException); /** * Handle a metadata request failure. * * @param now Current time in milliseconds * @param maybeFatalException Optional fatal error (e.g. {@link UnsupportedVersionException}) */ void handleFailedRequest(long now, Optional<KafkaException> maybeFatalException); /** * Handle responses for metadata requests. * * This provides a mechanism for the `MetadataUpdater` implementation to use the NetworkClient instance for its own * requests with special handling for completed receives of such requests. */ void handleSuccessfulResponse(RequestHeader requestHeader, long now, MetadataResponse metadataResponse); /** * Returns true if metadata couldn't be fetched for `rebootstrapTriggerMs` or if server requested rebootstrap. * * @param now Current time in milliseconds * @param rebootstrapTriggerMs Configured timeout after which rebootstrap is triggered */ default boolean needsRebootstrap(long now, long rebootstrapTriggerMs) { return false; } /** * Performs rebootstrap, replacing the existing cluster with the bootstrap cluster. * * @param now Current time in milliseconds */ default void rebootstrap(long now) {} /** * Close this updater. */ @Override void close(); }
MetadataUpdater
java
apache__dubbo
dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounterTest.java
{ "start": 924, "end": 1392 }
class ____ { @Test void test() { TimeWindowCounter counter = new TimeWindowCounter(10, 1); counter.increment(); Assertions.assertEquals(1, counter.get()); counter.decrement(); Assertions.assertEquals(0, counter.get()); counter.increment(); counter.increment(); Assertions.assertEquals(2, counter.get()); Assertions.assertTrue(counter.bucketLivedSeconds() <= 1); } }
TimeWindowCounterTest
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/Resetable.java
{ "start": 865, "end": 970 }
interface ____ { /** * reset. * * @param url */ void reset(URL url); }
Resetable
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/alias/IndicesAliasesRequest.java
{ "start": 4087, "end": 5366 }
class ____ implements AliasesRequest, Writeable, ToXContentObject { private static final ParseField INDEX = new ParseField("index"); private static final ParseField INDICES = new ParseField("indices"); private static final ParseField ALIAS = new ParseField("alias"); private static final ParseField ALIASES = new ParseField("aliases"); private static final ParseField FILTER = new ParseField("filter"); private static final ParseField ROUTING = new ParseField("routing"); private static final ParseField INDEX_ROUTING = new ParseField("index_routing", "indexRouting", "index-routing"); private static final ParseField SEARCH_ROUTING = new ParseField("search_routing", "searchRouting", "search-routing"); private static final ParseField IS_WRITE_INDEX = new ParseField("is_write_index"); private static final ParseField IS_HIDDEN = new ParseField("is_hidden"); private static final ParseField MUST_EXIST = new ParseField("must_exist"); private static final ParseField ADD = new ParseField("add"); private static final ParseField REMOVE = new ParseField("remove"); private static final ParseField REMOVE_INDEX = new ParseField("remove_index"); public
AliasActions
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/KnativeComponentBuilderFactory.java
{ "start": 1815, "end": 16184 }
interface ____ extends ComponentBuilder<KnativeComponent> { /** * CloudEvent headers to override. * * The option is a: &lt;code&gt;java.util.Map&amp;lt;java.lang.String, * java.lang.String&amp;gt;&lt;/code&gt; type. * * Group: common * * @param ceOverride the value to set * @return the dsl builder */ default KnativeComponentBuilder ceOverride(java.util.Map<java.lang.String, java.lang.String> ceOverride) { doSetProperty("ceOverride", ceOverride); return this; } /** * Set the version of the cloudevents spec. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: 1.0 * Group: common * * @param cloudEventsSpecVersion the value to set * @return the dsl builder */ default KnativeComponentBuilder cloudEventsSpecVersion(java.lang.String cloudEventsSpecVersion) { doSetProperty("cloudEventsSpecVersion", cloudEventsSpecVersion); return this; } /** * Set the event-type information of the produced events. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: org.apache.camel.event * Group: common * * @param cloudEventsType the value to set * @return the dsl builder */ default KnativeComponentBuilder cloudEventsType(java.lang.String cloudEventsType) { doSetProperty("cloudEventsType", cloudEventsType); return this; } /** * Set the configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.knative.KnativeConfiguration&lt;/code&gt; type. * * Group: common * * @param configuration the value to set * @return the dsl builder */ default KnativeComponentBuilder configuration(org.apache.camel.component.knative.KnativeConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * The protocol consumer factory. * * The option is a: * &lt;code&gt;org.apache.camel.component.knative.spi.KnativeConsumerFactory&lt;/code&gt; type. * * Group: common * * @param consumerFactory the value to set * @return the dsl builder */ default KnativeComponentBuilder consumerFactory(org.apache.camel.component.knative.spi.KnativeConsumerFactory consumerFactory) { doSetProperty("consumerFactory", consumerFactory); return this; } /** * The environment. * * The option is a: * &lt;code&gt;org.apache.camel.component.knative.spi.KnativeEnvironment&lt;/code&gt; type. * * Group: common * * @param environment the value to set * @return the dsl builder */ default KnativeComponentBuilder environment(org.apache.camel.component.knative.spi.KnativeEnvironment environment) { doSetProperty("environment", environment); return this; } /** * The path ot the environment definition. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param environmentPath the value to set * @return the dsl builder */ default KnativeComponentBuilder environmentPath(java.lang.String environmentPath) { doSetProperty("environmentPath", environmentPath); return this; } /** * Set the filters. * * The option is a: &lt;code&gt;java.util.Map&amp;lt;java.lang.String, * java.lang.String&amp;gt;&lt;/code&gt; type. * * Group: common * * @param filters the value to set * @return the dsl builder */ default KnativeComponentBuilder filters(java.util.Map<java.lang.String, java.lang.String> filters) { doSetProperty("filters", filters); return this; } /** * The protocol producer factory. * * The option is a: * &lt;code&gt;org.apache.camel.component.knative.spi.KnativeProducerFactory&lt;/code&gt; type. * * Group: common * * @param producerFactory the value to set * @return the dsl builder */ default KnativeComponentBuilder producerFactory(org.apache.camel.component.knative.spi.KnativeProducerFactory producerFactory) { doSetProperty("producerFactory", producerFactory); return this; } /** * The SinkBinding configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.knative.spi.KnativeSinkBinding&lt;/code&gt; type. * * Group: common * * @param sinkBinding the value to set * @return the dsl builder */ default KnativeComponentBuilder sinkBinding(org.apache.camel.component.knative.spi.KnativeSinkBinding sinkBinding) { doSetProperty("sinkBinding", sinkBinding); return this; } /** * Set the transport options. * * The option is a: &lt;code&gt;java.util.Map&amp;lt;java.lang.String, * java.lang.Object&amp;gt;&lt;/code&gt; type. * * Group: common * * @param transportOptions the value to set * @return the dsl builder */ default KnativeComponentBuilder transportOptions(java.util.Map<java.lang.String, java.lang.Object> transportOptions) { doSetProperty("transportOptions", transportOptions); return this; } /** * The name of the service to lookup from the KnativeEnvironment. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param typeId the value to set * @return the dsl builder */ default KnativeComponentBuilder typeId(java.lang.String typeId) { doSetProperty("typeId", typeId); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default KnativeComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Transforms the reply into a cloud event that will be processed by the * caller. When listening to events from a Knative Broker, if this flag * is enabled, replies will be published to the same Broker where the * request comes from (beware that if you don't change the type of the * received message, you may create a loop and receive your same reply). * When this flag is disabled, CloudEvent headers are removed from the * reply. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param replyWithCloudEvent the value to set * @return the dsl builder */ default KnativeComponentBuilder replyWithCloudEvent(boolean replyWithCloudEvent) { doSetProperty("replyWithCloudEvent", replyWithCloudEvent); return this; } /** * If the consumer should construct a full reply to knative request. * * The option is a: &lt;code&gt;java.lang.Boolean&lt;/code&gt; type. * * Default: true * Group: consumer (advanced) * * @param reply the value to set * @return the dsl builder */ default KnativeComponentBuilder reply(java.lang.Boolean reply) { doSetProperty("reply", reply); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default KnativeComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * The version of the k8s resource referenced by the endpoint. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: advanced * * @param apiVersion the value to set * @return the dsl builder */ default KnativeComponentBuilder apiVersion(java.lang.String apiVersion) { doSetProperty("apiVersion", apiVersion); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default KnativeComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * The type of the k8s resource referenced by the endpoint. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: advanced * * @param kind the value to set * @return the dsl builder */ default KnativeComponentBuilder kind(java.lang.String kind) { doSetProperty("kind", kind); return this; } /** * The name of the k8s resource referenced by the endpoint. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: advanced * * @param name the value to set * @return the dsl builder */ default KnativeComponentBuilder name(java.lang.String name) { doSetProperty("name", name); return this; } /** * Used for enabling or disabling all consumer based health checks from * this component. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckConsumerEnabled the value to set * @return the dsl builder */ default KnativeComponentBuilder healthCheckConsumerEnabled(boolean healthCheckConsumerEnabled) { doSetProperty("healthCheckConsumerEnabled", healthCheckConsumerEnabled); return this; } /** * Used for enabling or disabling all producer based health checks from * this component. Notice: Camel has by default disabled all producer * based health-checks. You can turn on producer checks globally by * setting camel.health.producersEnabled=true. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckProducerEnabled the value to set * @return the dsl builder */ default KnativeComponentBuilder healthCheckProducerEnabled(boolean healthCheckProducerEnabled) { doSetProperty("healthCheckProducerEnabled", healthCheckProducerEnabled); return this; } }
KnativeComponentBuilder
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ser/jdk/JDKKeySerializers.java
{ "start": 616, "end": 5380 }
class ____ { protected final static ValueSerializer<Object> DEFAULT_STRING_SERIALIZER = new StringKeySerializer(); /** * @param config Serialization configuration in use, may be needed in choosing * serializer to use * @param rawKeyType Type of key values to serialize * @param useDefault If no match is found, should we return fallback deserializer * (true), or null (false)? */ public static ValueSerializer<Object> getStdKeySerializer(SerializationConfig config, Class<?> rawKeyType, boolean useDefault) { // 24-Sep-2015, tatu: Important -- should ONLY consider types for which `@JsonValue` // cannot be used, since caller has not yet checked for that annotation // This is why Enum types are not handled here quite yet // [databind#943: Use a dynamic key serializer if we are not given actual // type declaration if ((rawKeyType == null) || (rawKeyType == Object.class)) { return new Dynamic(); } if (rawKeyType == String.class) { return DEFAULT_STRING_SERIALIZER; } if (rawKeyType.isPrimitive()) { rawKeyType = ClassUtil.wrapperType(rawKeyType); } if (rawKeyType == Integer.class) { return new Default(Default.TYPE_INTEGER, rawKeyType); } if (rawKeyType == Long.class) { return new Default(Default.TYPE_LONG, rawKeyType); } if (rawKeyType.isPrimitive() || Number.class.isAssignableFrom(rawKeyType)) { // 28-Jun-2016, tatu: Used to just return DEFAULT_KEY_SERIALIZER, but makes // more sense to use simpler one directly return new Default(Default.TYPE_TO_STRING, rawKeyType); } if (rawKeyType == Class.class) { return new Default(Default.TYPE_CLASS, rawKeyType); } if (Date.class.isAssignableFrom(rawKeyType)) { return new Default(Default.TYPE_DATE, rawKeyType); } if (Calendar.class.isAssignableFrom(rawKeyType)) { return new Default(Default.TYPE_CALENDAR, rawKeyType); } // other JDK types we know convert properly with 'toString()'? if (rawKeyType == java.util.UUID.class) { return new Default(Default.TYPE_TO_STRING, rawKeyType); } if (rawKeyType == byte[].class) { return new Default(Default.TYPE_BYTE_ARRAY, rawKeyType); } if (useDefault) { // 19-Oct-2016, tatu: Used to just return DEFAULT_KEY_SERIALIZER but why not: return new Default(Default.TYPE_TO_STRING, rawKeyType); } return null; } /** * Method called if no specified key serializer was located; will return a * "default" key serializer except with special handling for {@code Enum}s */ public static ValueSerializer<Object> getFallbackKeySerializer(SerializationConfig config, Class<?> rawKeyType, AnnotatedClass annotatedClass) { if (rawKeyType != null) { // 29-Sep-2015, tatu: Odd case here, of `Enum`, which we may get for `EnumMap`; not sure // if that is a bug or feature. Regardless, it seems to require dynamic handling // (compared to getting actual fully typed Enum). // Note that this might even work from the earlier point, but let's play it safe for now // 11-Aug-2016, tatu: Turns out we get this if `EnumMap` is the root value because // then there is no static type if (rawKeyType == Enum.class) { return new Dynamic(); } // 29-Sep-2019, tatu: [databind#2457] cannot use 'rawKeyType.isEnum()`, won't work // for subtypes. if (ClassUtil.isEnumType(rawKeyType)) { return EnumKeySerializer.construct(rawKeyType, EnumDefinition.construct(config, annotatedClass).valuesToWrite(config)); } } // 19-Oct-2016, tatu: Used to just return DEFAULT_KEY_SERIALIZER but why not: return new Default(Default.TYPE_TO_STRING, rawKeyType); } /* /********************************************************** /* Standard implementations used /********************************************************** */ /** * This is a "chameleon" style multi-type key serializer for simple * standard JDK types. *<p> * TODO: Should (but does not yet) support re-configuring format used for * {@link java.util.Date} and {@link java.util.Calendar} key serializers, * as well as alternative configuration of Enum key serializers. */ public static
JDKKeySerializers
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/TestPlannerOptimizer.java
{ "start": 1243, "end": 4851 }
class ____ { private final EsqlParser parser; private final Analyzer analyzer; private final LogicalPlanOptimizer logicalOptimizer; private final PhysicalPlanOptimizer physicalPlanOptimizer; private final Mapper mapper; private final Configuration config; public TestPlannerOptimizer(Configuration config, Analyzer analyzer) { this( config, analyzer, new LogicalPlanOptimizer(new LogicalOptimizerContext(config, FoldContext.small(), analyzer.context().minimumVersion())) ); } public TestPlannerOptimizer(Configuration config, Analyzer analyzer, LogicalPlanOptimizer logicalOptimizer) { this.analyzer = analyzer; this.config = config; this.logicalOptimizer = logicalOptimizer; parser = new EsqlParser(); physicalPlanOptimizer = new PhysicalPlanOptimizer(new PhysicalOptimizerContext(config, analyzer.context().minimumVersion())); mapper = new Mapper(); } public PhysicalPlan plan(String query) { return plan(query, EsqlTestUtils.TEST_SEARCH_STATS); } public PhysicalPlan plan(String query, SearchStats stats) { return plan(query, stats, analyzer); } public PhysicalPlan plan(String query, SearchStats stats, Analyzer analyzer) { return plan(query, stats, analyzer, null); } public PhysicalPlan plan(String query, SearchStats stats, Analyzer analyzer, @Nullable QueryBuilder esFilter) { PhysicalPlan plan = PlannerUtils.integrateEsFilterIntoFragment(physicalPlan(query, analyzer), esFilter); return optimizedPlan(plan, stats); } public PhysicalPlan plan(String query, SearchStats stats, EsqlFlags esqlFlags) { return optimizedPlan(physicalPlan(query, analyzer), stats, esqlFlags); } private PhysicalPlan optimizedPlan(PhysicalPlan plan, SearchStats searchStats) { return optimizedPlan(plan, searchStats, new EsqlFlags(true)); } private PhysicalPlan optimizedPlan(PhysicalPlan plan, SearchStats searchStats, EsqlFlags esqlFlags) { // System.out.println("* Physical Before\n" + plan); var physicalPlan = EstimatesRowSize.estimateRowSize(0, physicalPlanOptimizer.optimize(plan)); // System.out.println("* Physical After\n" + physicalPlan); // the real execution breaks the plan at the exchange and then decouples the plan // this is of no use in the unit tests, which checks the plan as a whole instead of each // individually hence why here the plan is kept as is var logicalTestOptimizer = new LocalLogicalPlanOptimizer( new LocalLogicalOptimizerContext(config, FoldContext.small(), searchStats) ); var physicalTestOptimizer = new TestLocalPhysicalPlanOptimizer( new LocalPhysicalOptimizerContext(TEST_PLANNER_SETTINGS, esqlFlags, config, FoldContext.small(), searchStats), true ); var l = PlannerUtils.localPlan(physicalPlan, logicalTestOptimizer, physicalTestOptimizer); // handle local reduction alignment l = PhysicalPlanOptimizerTests.localRelationshipAlignment(l); // System.out.println("* Localized DataNode Plan\n" + l); return l; } private PhysicalPlan physicalPlan(String query, Analyzer analyzer) { LogicalPlan logical = logicalOptimizer.optimize(analyzer.analyze(parser.createStatement(query))); // System.out.println("Logical\n" + logical); return mapper.map(new Versioned<>(logical, analyzer.context().minimumVersion())); } }
TestPlannerOptimizer
java
micronaut-projects__micronaut-core
jackson-databind/src/test/java/io/micronaut/jackson/databind/GraphQLResponseBody.java
{ "start": 296, "end": 640 }
class ____ { private final Map<String, Object> specification; @JsonCreator public GraphQLResponseBody(Map<String, Object> specification) { this.specification = specification; } @JsonAnyGetter @JsonInclude public Map<String, Object> getSpecification() { return specification; } }
GraphQLResponseBody
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/S3ATestUtils.java
{ "start": 21183, "end": 21275 }
class ____"); skipIfS3ExpressBucket(configuration); } /** * Skip a test if ACL
tests
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/filters/GracefulShutdownFilter.java
{ "start": 428, "end": 2515 }
class ____ implements ShutdownListener, Handler<HttpServerRequest> { private static final Logger log = Logger.getLogger(GracefulShutdownFilter.class); private volatile Handler<HttpServerRequest> next; private volatile boolean running = true; private final AtomicInteger currentRequestCount = new AtomicInteger(); private final AtomicReference<ShutdownNotification> notification = new AtomicReference<>(); private final Handler<Void> requestDoneHandler = new Handler<>() { @Override public void handle(Void event) { int count = currentRequestCount.decrementAndGet(); if (!running) { if (count == 0) { ShutdownNotification n = notification.get(); if (n != null) { if (notification.compareAndSet(n, null)) { n.done(); log.info("All HTTP requests complete"); } } } } } }; @Override public void handle(HttpServerRequest event) { if (!running) { event.response().setStatusCode(HttpResponseStatus.SERVICE_UNAVAILABLE.code()) .putHeader(HttpHeaderNames.CONNECTION, "close").end(); return; } currentRequestCount.incrementAndGet(); //todo: some way to do this without a wrapper solution ((QuarkusRequestWrapper) event).addRequestDoneHandler(requestDoneHandler); next.handle(event); } @Override public void shutdown(ShutdownNotification notification) { this.notification.set(notification); running = false; if (currentRequestCount.get() == 0) { if (this.notification.compareAndSet(notification, null)) { notification.done(); } } else { log.info("Waiting for HTTP requests to complete"); } } public void next(Handler<HttpServerRequest> next) { this.next = next; } }
GracefulShutdownFilter
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ErroneousThreadPoolConstructorCheckerTest.java
{ "start": 9348, "end": 9803 }
class ____ { public void createThreadPool() { new ThreadPoolExecutor(0, 20, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); } } """) .addOutputLines( "Test.java", """ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
Test
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/DisplayNameGenerator.java
{ "start": 3364, "end": 3764 }
class ____ generate a name for; never {@code null} * @return the display name for the class; never blank */ String generateDisplayNameForClass(Class<?> testClass); /** * Generate a display name for the given {@link Nested @Nested} inner test * class. * * <p>If this method returns {@code null}, the default display name * generator will be used instead. * * @param nestedClass the
to
java
apache__maven
impl/maven-testing/src/main/java/org/apache/maven/api/plugin/testing/MojoTest.java
{ "start": 1659, "end": 3198 }
class ____ { * @Inject * private SomeComponent component; * * @Test * @InjectMojo(goal = "my-goal") * @MojoParameter(name = "parameter", value = "value") * void testMojoExecution(MyMojo mojo) { * // mojo is instantiated with the specified parameters * // component is automatically injected * mojo.execute(); * // verify execution results * } * * @Provides * @Singleton * SomeComponent provideMockedComponent() { * return mock(SomeComponent.class); * } * } * } * </pre> * * <p>The annotation supports:</p> * <ul> * <li>Automatic Mojo instantiation and configuration</li> * <li>Parameter injection via {@link MojoParameter}</li> * <li>Component injection via {@link org.apache.maven.api.di.Inject}</li> * <li>Mock component injection via {@link org.apache.maven.api.di.Provides}</li> * <li>Custom POM configuration via {@link InjectMojo#pom()}</li> * <li>Base directory configuration for test resources</li> * </ul> * * <p>This annotation replaces the legacy maven-plugin-testing-harness functionality * with a modern, annotation-based approach that integrates with JUnit Jupiter and * Maven's new dependency injection framework.</p> * * @see MojoExtension * @see InjectMojo * @see MojoParameter * @see org.apache.maven.api.di.Inject * @see org.apache.maven.api.di.Provides * @since 4.0.0 */ @Retention(RetentionPolicy.RUNTIME) @ExtendWith(MojoExtension.class) @Target(ElementType.TYPE) public @
MyMojoTest
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/search/arguments/SugGetArgs.java
{ "start": 626, "end": 857 }
class ____<K, V> { private boolean fuzzy; private boolean withScores; private boolean withPayloads; private Long max; /** * Builder entry points for {@link SugGetArgs}. */ public static
SugGetArgs
java
quarkusio__quarkus
extensions/flyway/runtime-dev/src/main/java/io/quarkus/flyway/runtime/dev/ui/FlywayJsonRpcService.java
{ "start": 10133, "end": 10568 }
class ____ { public String name; public boolean hasMigrations; public boolean createPossible; public FlywayDatasource() { } public FlywayDatasource(String name, boolean hasMigrations, boolean createPossible) { this.name = name; this.hasMigrations = hasMigrations; this.createPossible = createPossible; } } public static
FlywayDatasource
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/DubboXmlProviderTest.java
{ "start": 1131, "end": 2684 }
class ____ { @Test void testProvider() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml"); context.start(); Object bean = context.getBean("helloService"); Assertions.assertNotNull(bean); } @Test void testProvider2() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml"); context.start(); Assertions.assertNotNull(context.getBean("helloService")); ClassPathXmlApplicationContext context2 = new ClassPathXmlApplicationContext( "classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-consumer.xml"); context2.start(); HelloService helloService = context2.getBean("helloService", HelloService.class); Assertions.assertNotNull(helloService); RpcException exception = Assertions.assertThrows(RpcException.class, () -> helloService.sayHello("dubbo")); Assertions.assertTrue( exception .getMessage() .contains( "Failed to invoke the method sayHello in the service org.apache.dubbo.config.spring.api.HelloService. No provider available for the service org.apache.dubbo.config.spring.api.HelloService")); } }
DubboXmlProviderTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/OptionalOneToOnePKJCQueryTest.java
{ "start": 7401, "end": 7637 }
class ____ { @Id private long id; @OneToOne @PrimaryKeyJoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) private BarWithIdNamedId bar; } @Entity(name = "BarWithIdNamedId") public static
FooHasBarWithIdNamedId
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/external/response/elastic/ElasticInferenceServiceDenseTextEmbeddingsResponseEntity.java
{ "start": 1013, "end": 4074 }
class ____ { /** * Parses the Elastic Inference Service Dense Text Embeddings response. * * For a request like: * * <pre> * <code> * { * "inputs": ["Embed this text", "Embed this text, too"] * } * </code> * </pre> * * The response would look like: * * <pre> * <code> * { * "data": [ * [ * 2.1259406, * 1.7073475, * 0.9020516 * ], * (...) * ], * "meta": { * "usage": {...} * } * } * </code> * </pre> */ public static DenseEmbeddingFloatResults fromResponse(Request request, HttpResult response) throws IOException { try (var p = XContentFactory.xContent(XContentType.JSON).createParser(XContentParserConfiguration.EMPTY, response.body())) { return EmbeddingFloatResult.PARSER.apply(p, null).toDenseEmbeddingFloatResults(); } } public record EmbeddingFloatResult(List<EmbeddingFloatResultEntry> embeddingResults) { @SuppressWarnings("unchecked") public static final ConstructingObjectParser<EmbeddingFloatResult, Void> PARSER = new ConstructingObjectParser<>( EmbeddingFloatResult.class.getSimpleName(), true, args -> new EmbeddingFloatResult((List<EmbeddingFloatResultEntry>) args[0]) ); static { // Custom field declaration to handle array of arrays format PARSER.declareField(constructorArg(), (parser, context) -> { return XContentParserUtils.parseList(parser, (p, index) -> { List<Float> embedding = XContentParserUtils.parseList(p, (innerParser, innerIndex) -> innerParser.floatValue()); return EmbeddingFloatResultEntry.fromFloatArray(embedding); }); }, new ParseField("data"), org.elasticsearch.xcontent.ObjectParser.ValueType.OBJECT_ARRAY); } public DenseEmbeddingFloatResults toDenseEmbeddingFloatResults() { return new DenseEmbeddingFloatResults( embeddingResults.stream().map(entry -> DenseEmbeddingFloatResults.Embedding.of(entry.embedding)).toList() ); } } /** * Represents a single embedding entry in the response. * For the Elastic Inference Service, each entry is just an array of floats (no wrapper object). * This is a simpler wrapper that just holds the float array. */ public record EmbeddingFloatResultEntry(List<Float> embedding) { public static EmbeddingFloatResultEntry fromFloatArray(List<Float> floats) { return new EmbeddingFloatResultEntry(floats); } } private ElasticInferenceServiceDenseTextEmbeddingsResponseEntity() {} }
ElasticInferenceServiceDenseTextEmbeddingsResponseEntity
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/proxy/TestProxy.java
{ "start": 223, "end": 554 }
class ____ extends TestCase { public void test_0() throws Exception { Object vo = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {I.class}, new VO()); String text = JSON.toJSONString(vo); System.out.println(text); } public static
TestProxy
java
spring-projects__spring-boot
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java
{ "start": 25887, "end": 25981 }
class ____ { } @ConfigurationProperties("gh4415") public static
Gh4415PropertiesConfiguration
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartEvents.java
{ "start": 2920, "end": 3611 }
class ____ extends AbstractPartEvent { private static final DataBuffer EMPTY = DefaultDataBufferFactory.sharedInstance.allocateBuffer(0); private final DataBuffer content; private final boolean last; public DefaultPartEvent(HttpHeaders headers) { this(headers, EMPTY, true); } public DefaultPartEvent(HttpHeaders headers, DataBuffer content, boolean last) { super(headers); this.content = content; this.last = last; } @Override public DataBuffer content() { return this.content; } @Override public boolean isLast() { return this.last; } } /** * Default implementation of {@link FormPartEvent}. */ private static final
DefaultPartEvent
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/TahuEdgeEndpointBuilderFactory.java
{ "start": 20869, "end": 23113 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final TahuEdgeHeaderNameBuilder INSTANCE = new TahuEdgeHeaderNameBuilder(); /** * The Sparkplug message type of the message. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code TahuMessageType}. */ public String tahuMessageType() { return "CamelTahuMessageType"; } /** * The Sparkplug edge node descriptor string source of a message or * metric. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code TahuEdgeNodeDescriptor}. */ public String tahuEdgeNodeDescriptor() { return "CamelTahuEdgeNodeDescriptor"; } /** * The timestamp of a Sparkplug message. * * The option is a: {@code Long} type. * * Group: producer * * @return the name of the header {@code TahuMessageTimestamp}. */ public String tahuMessageTimestamp() { return "CamelTahuMessageTimestamp"; } /** * The UUID of a Sparkplug message. * * The option is a: {@code java.util.UUID} type. * * Group: producer * * @return the name of the header {@code TahuMessageUUID}. */ public String tahuMessageUUID() { return "CamelTahuMessageUUID"; } /** * The sequence number of a Sparkplug message. * * The option is a: {@code Long} type. * * Group: producer * * @return the name of the header {@code TahuMessageSequenceNumber}. */ public String tahuMessageSequenceNumber() { return "CamelTahuMessageSequenceNumber"; } } static TahuEdgeEndpointBuilder endpointBuilder(String componentName, String path) {
TahuEdgeHeaderNameBuilder
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/record/DefaultRecordBatch.java
{ "start": 24667, "end": 26762 }
class ____ implements CloseableIterator<Record> { private final Long logAppendTime; private final long baseOffset; private final long baseTimestamp; private final int baseSequence; private final int numRecords; private int readRecords = 0; RecordIterator() { this.logAppendTime = timestampType() == TimestampType.LOG_APPEND_TIME ? maxTimestamp() : null; this.baseOffset = baseOffset(); this.baseTimestamp = baseTimestamp(); this.baseSequence = baseSequence(); int numRecords = count(); if (numRecords < 0) throw new InvalidRecordException("Found invalid record count " + numRecords + " in magic v" + magic() + " batch"); this.numRecords = numRecords; } @Override public boolean hasNext() { return readRecords < numRecords; } @Override public Record next() { if (readRecords >= numRecords) throw new NoSuchElementException(); readRecords++; Record rec = readNext(baseOffset, baseTimestamp, baseSequence, logAppendTime); if (readRecords == numRecords) { // Validate that the actual size of the batch is equal to declared size // by checking that after reading declared number of items, there no items left // (overflow case, i.e. reading past buffer end is checked elsewhere). if (!ensureNoneRemaining()) throw new InvalidRecordException("Incorrect declared batch size, records still remaining in file"); } return rec; } protected abstract Record readNext(long baseOffset, long baseTimestamp, int baseSequence, Long logAppendTime); protected abstract boolean ensureNoneRemaining(); @Override public void remove() { throw new UnsupportedOperationException(); } } // visible for testing abstract
RecordIterator
java
elastic__elasticsearch
x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/NodesDeprecationCheckAction.java
{ "start": 947, "end": 1306 }
class ____ extends ActionType<NodesDeprecationCheckResponse> { public static final NodesDeprecationCheckAction INSTANCE = new NodesDeprecationCheckAction(); public static final String NAME = "cluster:admin/xpack/deprecation/nodes/info"; private NodesDeprecationCheckAction() { super(NAME); } public static
NodesDeprecationCheckAction
java
elastic__elasticsearch
client/rest/src/main/java/org/elasticsearch/client/Request.java
{ "start": 1148, "end": 6102 }
class ____ { private final String method; private final String endpoint; private final Map<String, String> parameters = new HashMap<>(); private HttpEntity entity; private RequestOptions options = RequestOptions.DEFAULT; /** * Create the {@linkplain Request}. * @param method the HTTP method * @param endpoint the path of the request (without scheme, host, port, or prefix) */ public Request(String method, String endpoint) { this.method = Objects.requireNonNull(method, "method cannot be null"); this.endpoint = Objects.requireNonNull(endpoint, "endpoint cannot be null"); } /** * The HTTP method. */ public String getMethod() { return method; } /** * The path of the request (without scheme, host, port, or prefix). */ public String getEndpoint() { return endpoint; } /** * Add a query string parameter. * @param name the name of the url parameter. Must not be null. * @param value the value of the url parameter. If {@code null} then * the parameter is sent as {@code name} rather than {@code name=value} * @throws IllegalArgumentException if a parameter with that name has * already been set */ public void addParameter(String name, String value) { Objects.requireNonNull(name, "url parameter name cannot be null"); if (parameters.containsKey(name)) { throw new IllegalArgumentException("url parameter [" + name + "] has already been set to [" + parameters.get(name) + "]"); } else { parameters.put(name, value); } } public void addParameters(Map<String, String> paramSource) { paramSource.forEach(this::addParameter); } /** * Query string parameters. The returned map is an unmodifiable view of the * map in the request so calls to {@link #addParameter(String, String)} * will change it. */ public Map<String, String> getParameters() { return unmodifiableMap(parameters); } /** * Set the body of the request. If not set or set to {@code null} then no * body is sent with the request. */ public void setEntity(HttpEntity entity) { this.entity = entity; } /** * Set the body of the request to a string. If not set or set to * {@code null} then no body is sent with the request. The * {@code Content-Type} will be sent as {@code application/json}. * If you need a different content type then use * {@link #setEntity(HttpEntity)}. */ public void setJsonEntity(String body) { setEntity(body == null ? null : new NStringEntity(body, ContentType.APPLICATION_JSON)); } /** * The body of the request. If {@code null} then no body * is sent with the request. */ public HttpEntity getEntity() { return entity; } /** * Set the portion of an HTTP request to Elasticsearch that can be * manipulated without changing Elasticsearch's behavior. */ public void setOptions(RequestOptions options) { Objects.requireNonNull(options, "options cannot be null"); this.options = options; } /** * Set the portion of an HTTP request to Elasticsearch that can be * manipulated without changing Elasticsearch's behavior. */ public void setOptions(RequestOptions.Builder options) { Objects.requireNonNull(options, "options cannot be null"); this.options = options.build(); } /** * Get the portion of an HTTP request to Elasticsearch that can be * manipulated without changing Elasticsearch's behavior. */ public RequestOptions getOptions() { return options; } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("Request{"); b.append("method='").append(method).append('\''); b.append(", endpoint='").append(endpoint).append('\''); if (false == parameters.isEmpty()) { b.append(", params=").append(parameters); } if (entity != null) { b.append(", entity=").append(entity); } b.append(", options=").append(options); return b.append('}').toString(); } @Override public boolean equals(Object obj) { if (obj == null || (obj.getClass() != getClass())) { return false; } if (obj == this) { return true; } Request other = (Request) obj; return method.equals(other.method) && endpoint.equals(other.endpoint) && parameters.equals(other.parameters) && Objects.equals(entity, other.entity) && options.equals(other.options); } @Override public int hashCode() { return Objects.hash(method, endpoint, parameters, entity, options); } }
Request
java
dropwizard__dropwizard
dropwizard-testing/src/main/java/io/dropwizard/testing/common/Resource.java
{ "start": 1308, "end": 1490 }
class ____ { /** * A {@link Resource} builder which enables configuration of a Jersey testing environment. */ @SuppressWarnings("unchecked") public static
Resource
java
apache__rocketmq
test/src/main/java/org/apache/rocketmq/test/util/TestUtil.java
{ "start": 1076, "end": 3629 }
class ____ { private TestUtil() { } public static Long parseStringToLong(String s, Long defval) { Long val = defval; try { val = Long.parseLong(s); } catch (NumberFormatException e) { val = defval; } return val; } public static Integer parseStringToInteger(String s, Integer defval) { Integer val = defval; try { val = Integer.parseInt(s); } catch (NumberFormatException e) { val = defval; } return val; } public static String addQuoteToParamater(String param) { StringBuilder sb = new StringBuilder("'"); sb.append(param).append("'"); return sb.toString(); } public static void waitForMonment(long time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } public static void waitForSeconds(long time) { try { TimeUnit.SECONDS.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } public static void waitForMinutes(long time) { try { TimeUnit.MINUTES.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } public static void waitForInputQuit() { waitForInput("quit"); } public static void waitForInput(String keyWord) { waitForInput(keyWord, String.format("The thread will wait until you input stop command[%s]:", keyWord)); } public static void waitForInput(String keyWord, String info) { try { byte[] b = new byte[1024]; int n = System.in.read(b); String s = new String(b, 0, n - 1, StandardCharsets.UTF_8).replace("\r", "").replace("\n", ""); while (!s.equals(keyWord)) { n = System.in.read(b); s = new String(b, 0, n - 1, StandardCharsets.UTF_8); } } catch (IOException e) { e.printStackTrace(); } } public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet()); list.sort(Map.Entry.comparingByValue()); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; } }
TestUtil
java
quarkusio__quarkus
extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/binder/netty/NettyMetricsProvider.java
{ "start": 302, "end": 912 }
class ____ { public static final String NETTY_DEFAULT_POOLED_ALLOCATOR_NAME = "pooled"; public static final String NETTY_DEFAULT_UNPOOLED_ALLOCATOR_NAME = "unpooled"; @Produces @Singleton public MeterBinder pooledByteBufAllocatorMetrics() { return new NettyAllocatorMetrics(NETTY_DEFAULT_POOLED_ALLOCATOR_NAME, PooledByteBufAllocator.DEFAULT); } @Produces @Singleton public MeterBinder unpooledByteBufAllocatorMetrics() { return new NettyAllocatorMetrics(NETTY_DEFAULT_UNPOOLED_ALLOCATOR_NAME, UnpooledByteBufAllocator.DEFAULT); } }
NettyMetricsProvider
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LongRevEntityInheritanceChildAuditing.java
{ "start": 1128, "end": 2198 }
class ____ { @Test public void testChildRevColumnType(DomainModelScope scope) { // Hibernate now sorts columns that are part of the key and therefore this test needs to test // for the existence of the specific key column rather than the expectation that is exists at // a specific order. List<Selectable> childEntityKeyColumns = scope.getDomainModel() .getEntityBinding( ChildEntity.class.getName() + "_AUD" ) .getKey() .getSelectables(); final String revisionColumnName = "REV"; // default revision field name Column column = getColumnFromIteratorByName( childEntityKeyColumns, revisionColumnName ); assertNotNull( column ); assertEquals( "int", column.getSqlType() ); } private Column getColumnFromIteratorByName(List<Selectable> selectables, String columnName) { for ( Selectable selectable : selectables ) { if ( selectable instanceof Column ) { Column column = (Column) selectable; if ( columnName.equals( column.getName() ) ) { return column; } } } return null; } }
LongRevEntityInheritanceChildAuditing
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringManagedCustomProcessorTest.java
{ "start": 3101, "end": 3609 }
class ____ implements Processor { private String foo = "hey"; @ManagedAttribute(description = "Foo is the foo") public String getFoo() { return foo; } @ManagedAttribute(description = "Foo is the foo") public void setFoo(String foo) { this.foo = foo; } @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader("foo", getFoo()); } } }
MyCustomProcessor
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/NestedChoiceWithEndChoiceIssueTest.java
{ "start": 1367, "end": 5497 }
class ____ extends ContextTestSupport { @Override protected CamelContext createCamelContext() throws Exception { CamelContext ctx = super.createCamelContext(); ctx.getCamelContextExtension().addContextPlugin(NodeIdFactory.class, buildNodeIdFactory()); return ctx; } private static NodeIdFactory buildNodeIdFactory() { return new NodeIdFactory() { @Override public String createId(NamedNode definition) { return definition.getShortName(); // do not use counter } }; } @Test public void testNestedChoiceOtherwise() throws Exception { String xml = PluginHelper.getModelToXMLDumper(context).dumpModelAsXml(context, context.getRouteDefinition("myRoute")); assertNotNull(xml); log.info(xml); String expected = IOHelper.stripLineComments( Paths.get("src/test/resources/org/apache/camel/processor/NestedChoiceWithEndChoiceIssueTest.xml"), "#", true); expected = StringHelper.after(expected, "-->"); assertThat(expected).isEqualToNormalizingNewlines("\n" + xml + "\n"); getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:result").expectedBodiesReceived("2"); getMockEndpoint("mock:result").expectedHeaderReceived("count", "1000"); template.sendBodyAndHeader("direct:start", 1, "count", 1); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:test").routeId("myRoute") .choice() .when(simple("${header.count} < 1000 && ${body} == 0")) .setHeader("count", simple("${header.count}++")) .setBody(constant(1)) .log("First when. Header is:${header.count} Body is:${body}") .to("direct:test") .when(simple("${header.count} < 1000 && ${body} == 1")) .setHeader("count", simple("${header.count}++")) .setBody().constant(2) .log("Second when. Header is:${header.count} Body is:${body}") .to("direct:test") .when(simple("${header.count} < 1000 && ${body} == 2")) .setHeader("count").simple("${header.count}++") .setBody(constant(0)) .choice() .when(simple("${header.count} < 500")) .log("Third when and small header. Header is:${header.count} Body is:${body}") .when(simple("${header.count} < 900")) .log("Third when and big header. Header is:${header.count} Body is:${body}") .otherwise() .log("Third when and header over 900. Header is:${header.count} Body is:${body}") .choice() .when(simple("${header.count} == 996")) .log("Deep choice log. Header is:${header.count}") .setHeader("count", constant(998)) .end().endChoice() .end() .to("direct:test") .endChoice() .otherwise() .log("Header is:${header.count}") .log("Final Body is:${body}") .end(); from("direct:start").routeId("start") .to("direct:test") .to("mock:result"); } }; } }
NestedChoiceWithEndChoiceIssueTest
java
elastic__elasticsearch
x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/plan/QueryPlanTests.java
{ "start": 1599, "end": 6222 }
class ____ extends ESTestCase { public void testTransformWithExpressionTopLevel() throws Exception { Limit limit = new Limit(EMPTY, of(42), relation()); LogicalPlan transformed = limit.transformExpressionsOnly(Literal.class, l -> of(24)); assertEquals(Limit.class, transformed.getClass()); Limit l = (Limit) transformed; assertEquals(24, l.limit().fold()); } public void testTransformWithExpressionTree() throws Exception { Limit limit = new Limit(EMPTY, of(42), relation()); OrderBy o = new OrderBy(EMPTY, limit, emptyList()); LogicalPlan transformed = o.transformExpressionsDown(Literal.class, l -> of(24)); assertEquals(OrderBy.class, transformed.getClass()); OrderBy order = (OrderBy) transformed; assertEquals(Limit.class, order.child().getClass()); assertEquals(24, ((Limit) order.child()).limit().fold()); } public void testTransformWithExpressionTopLevelInCollection() throws Exception { FieldAttribute one = fieldAttribute("one", INTEGER); FieldAttribute two = fieldAttribute("two", INTEGER); Project project = new Project(EMPTY, relation(), asList(one, two)); LogicalPlan transformed = project.transformExpressionsOnly( NamedExpression.class, n -> n.name().equals("one") ? new FieldAttribute(EMPTY, "changed", one.field()) : n ); assertEquals(Project.class, transformed.getClass()); Project p = (Project) transformed; assertEquals(2, p.projections().size()); assertSame(two, p.projections().get(1)); NamedExpression o = p.projections().get(0); assertEquals("changed", o.name()); } public void testForEachWithExpressionTopLevel() throws Exception { Alias one = new Alias(EMPTY, "one", of(42)); FieldAttribute two = fieldAttribute(); Project project = new Project(EMPTY, relation(), asList(one, two)); List<Object> list = new ArrayList<>(); project.forEachExpression(Literal.class, l -> { if (l.fold().equals(42)) { list.add(l.fold()); } }); assertEquals(singletonList(one.child().fold()), list); } public void testForEachWithExpressionTree() throws Exception { Limit limit = new Limit(EMPTY, of(42), relation()); OrderBy o = new OrderBy(EMPTY, limit, emptyList()); List<Object> list = new ArrayList<>(); o.forEachExpressionDown(Literal.class, l -> { if (l.fold().equals(42)) { list.add(l.fold()); } }); assertEquals(singletonList(limit.limit().fold()), list); } public void testForEachWithExpressionTopLevelInCollection() throws Exception { FieldAttribute one = fieldAttribute("one", INTEGER); FieldAttribute two = fieldAttribute("two", INTEGER); Project project = new Project(EMPTY, relation(), asList(one, two)); List<NamedExpression> list = new ArrayList<>(); project.forEachExpression(NamedExpression.class, n -> { if (n.name().equals("one")) { list.add(n); } }); assertEquals(singletonList(one), list); } // TODO: duplicate of testForEachWithExpressionTopLevel, let's remove it. public void testForEachWithExpressionTreeInCollection() throws Exception { Alias one = new Alias(EMPTY, "one", of(42)); FieldAttribute two = fieldAttribute(); Project project = new Project(EMPTY, relation(), asList(one, two)); List<Object> list = new ArrayList<>(); project.forEachExpression(Literal.class, l -> { if (l.fold().equals(42)) { list.add(l.fold()); } }); assertEquals(singletonList(one.child().fold()), list); } public void testPlanExpressions() { Alias one = new Alias(EMPTY, "one", of(42)); FieldAttribute two = fieldAttribute(); Project project = new Project(EMPTY, relation(), asList(one, two)); assertThat(Expressions.names(project.expressions()), contains("one", two.name())); } public void testPlanReferences() { var one = fieldAttribute("one", INTEGER); var two = fieldAttribute("two", INTEGER); var add = new Add(EMPTY, one, two); var field = fieldAttribute("field", INTEGER); var filter = new Filter(EMPTY, relation(), equalsOf(field, add)); assertThat(Expressions.names(filter.references()), contains("field", "one", "two")); } }
QueryPlanTests
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/subscribers/BoundedSubscriberTest.java
{ "start": 1175, "end": 13854 }
class ____ extends RxJavaTest { @Test public void onSubscribeThrows() { final List<Object> received = new ArrayList<>(); BoundedSubscriber<Object> subscriber = new BoundedSubscriber<>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { received.add(o); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { received.add(throwable); } }, new Action() { @Override public void run() throws Exception { received.add(1); } }, new Consumer<Subscription>() { @Override public void accept(Subscription subscription) throws Exception { throw new TestException(); } }, 128); assertFalse(subscriber.isDisposed()); Flowable.just(1).subscribe(subscriber); assertTrue(received.toString(), received.get(0) instanceof TestException); assertEquals(received.toString(), 1, received.size()); assertTrue(subscriber.isDisposed()); } @Test public void onNextThrows() { final List<Object> received = new ArrayList<>(); BoundedSubscriber<Object> subscriber = new BoundedSubscriber<>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { throw new TestException(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { received.add(throwable); } }, new Action() { @Override public void run() throws Exception { received.add(1); } }, new Consumer<Subscription>() { @Override public void accept(Subscription subscription) throws Exception { subscription.request(128); } }, 128); assertFalse(subscriber.isDisposed()); Flowable.just(1).subscribe(subscriber); assertTrue(received.toString(), received.get(0) instanceof TestException); assertEquals(received.toString(), 1, received.size()); assertTrue(subscriber.isDisposed()); } @Test public void onErrorThrows() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { final List<Object> received = new ArrayList<>(); BoundedSubscriber<Object> subscriber = new BoundedSubscriber<>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { received.add(o); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { throw new TestException("Inner"); } }, new Action() { @Override public void run() throws Exception { received.add(1); } }, new Consumer<Subscription>() { @Override public void accept(Subscription subscription) throws Exception { subscription.request(128); } }, 128); assertFalse(subscriber.isDisposed()); Flowable.<Integer>error(new TestException("Outer")).subscribe(subscriber); assertTrue(received.toString(), received.isEmpty()); assertTrue(subscriber.isDisposed()); TestHelper.assertError(errors, 0, CompositeException.class); List<Throwable> ce = TestHelper.compositeList(errors.get(0)); TestHelper.assertError(ce, 0, TestException.class, "Outer"); TestHelper.assertError(ce, 1, TestException.class, "Inner"); } finally { RxJavaPlugins.reset(); } } @Test public void onCompleteThrows() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { final List<Object> received = new ArrayList<>(); BoundedSubscriber<Object> subscriber = new BoundedSubscriber<>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { received.add(o); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { received.add(throwable); } }, new Action() { @Override public void run() throws Exception { throw new TestException(); } }, new Consumer<Subscription>() { @Override public void accept(Subscription subscription) throws Exception { subscription.request(128); } }, 128); assertFalse(subscriber.isDisposed()); Flowable.<Integer>empty().subscribe(subscriber); assertTrue(received.toString(), received.isEmpty()); assertTrue(subscriber.isDisposed()); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void onNextThrowsCancelsUpstream() { PublishProcessor<Integer> pp = PublishProcessor.create(); final List<Throwable> errors = new ArrayList<>(); BoundedSubscriber<Integer> s = new BoundedSubscriber<>(new Consumer<Integer>() { @Override public void accept(Integer v) throws Exception { throw new TestException(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable e) throws Exception { errors.add(e); } }, new Action() { @Override public void run() throws Exception { } }, new Consumer<Subscription>() { @Override public void accept(Subscription subscription) throws Exception { subscription.request(128); } }, 128); pp.subscribe(s); assertTrue("No observers?!", pp.hasSubscribers()); assertTrue("Has errors already?!", errors.isEmpty()); pp.onNext(1); assertFalse("Has observers?!", pp.hasSubscribers()); assertFalse("No errors?!", errors.isEmpty()); assertTrue(errors.toString(), errors.get(0) instanceof TestException); } @Test public void onSubscribeThrowsCancelsUpstream() { PublishProcessor<Integer> pp = PublishProcessor.create(); final List<Throwable> errors = new ArrayList<>(); BoundedSubscriber<Integer> s = new BoundedSubscriber<>(new Consumer<Integer>() { @Override public void accept(Integer v) throws Exception { } }, new Consumer<Throwable>() { @Override public void accept(Throwable e) throws Exception { errors.add(e); } }, new Action() { @Override public void run() throws Exception { } }, new Consumer<Subscription>() { @Override public void accept(Subscription s) throws Exception { throw new TestException(); } }, 128); pp.subscribe(s); assertFalse("Has observers?!", pp.hasSubscribers()); assertFalse("No errors?!", errors.isEmpty()); assertTrue(errors.toString(), errors.get(0) instanceof TestException); } @Test public void badSourceOnSubscribe() { Flowable<Integer> source = Flowable.fromPublisher(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { BooleanSubscription s1 = new BooleanSubscription(); s.onSubscribe(s1); BooleanSubscription s2 = new BooleanSubscription(); s.onSubscribe(s2); assertFalse(s1.isCancelled()); assertTrue(s2.isCancelled()); s.onNext(1); s.onComplete(); } }); final List<Object> received = new ArrayList<>(); BoundedSubscriber<Object> subscriber = new BoundedSubscriber<>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { received.add(v); } }, new Consumer<Throwable>() { @Override public void accept(Throwable e) throws Exception { received.add(e); } }, new Action() { @Override public void run() throws Exception { received.add(100); } }, new Consumer<Subscription>() { @Override public void accept(Subscription s) throws Exception { s.request(128); } }, 128); source.subscribe(subscriber); assertEquals(Arrays.asList(1, 100), received); } @Test @SuppressUndeliverable public void badSourceEmitAfterDone() { Flowable<Integer> source = Flowable.fromPublisher(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { BooleanSubscription s1 = new BooleanSubscription(); s.onSubscribe(s1); s.onNext(1); s.onComplete(); s.onNext(2); s.onError(new TestException()); s.onComplete(); } }); final List<Object> received = new ArrayList<>(); BoundedSubscriber<Object> subscriber = new BoundedSubscriber<>(new Consumer<Object>() { @Override public void accept(Object v) throws Exception { received.add(v); } }, new Consumer<Throwable>() { @Override public void accept(Throwable e) throws Exception { received.add(e); } }, new Action() { @Override public void run() throws Exception { received.add(100); } }, new Consumer<Subscription>() { @Override public void accept(Subscription s) throws Exception { s.request(128); } }, 128); source.subscribe(subscriber); assertEquals(Arrays.asList(1, 100), received); } @Test public void onErrorMissingShouldReportNoCustomOnError() { BoundedSubscriber<Integer> subscriber = new BoundedSubscriber<>(Functions.<Integer>emptyConsumer(), Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION, Functions.<Subscription>boundedConsumer(128), 128); assertFalse(subscriber.hasCustomOnError()); } @Test public void customOnErrorShouldReportCustomOnError() { BoundedSubscriber<Integer> subscriber = new BoundedSubscriber<>(Functions.<Integer>emptyConsumer(), Functions.<Throwable>emptyConsumer(), Functions.EMPTY_ACTION, Functions.<Subscription>boundedConsumer(128), 128); assertTrue(subscriber.hasCustomOnError()); } @Test public void cancel() { BoundedSubscriber<Integer> subscriber = new BoundedSubscriber<>(Functions.<Integer>emptyConsumer(), Functions.<Throwable>emptyConsumer(), Functions.EMPTY_ACTION, Functions.<Subscription>boundedConsumer(128), 128); BooleanSubscription bs = new BooleanSubscription(); subscriber.onSubscribe(bs); subscriber.cancel(); assertTrue(bs.isCancelled()); } @Test public void dispose() { BoundedSubscriber<Integer> subscriber = new BoundedSubscriber<>(Functions.<Integer>emptyConsumer(), Functions.<Throwable>emptyConsumer(), Functions.EMPTY_ACTION, Functions.<Subscription>boundedConsumer(128), 128); BooleanSubscription bs = new BooleanSubscription(); subscriber.onSubscribe(bs); assertFalse(subscriber.isDisposed()); subscriber.dispose(); assertTrue(bs.isCancelled()); assertTrue(subscriber.isDisposed()); } }
BoundedSubscriberTest
java
elastic__elasticsearch
distribution/archives/integ-test-zip/src/javaRestTest/java/org/elasticsearch/test/rest/RequestsWithoutContentIT.java
{ "start": 781, "end": 4714 }
class ____ extends ESRestTestCase { @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local().build(); @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } public void testIndexMissingBody() throws IOException { ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request(randomBoolean() ? "POST" : "PUT", "/idx/_doc/123")) ); assertResponseException(responseException, "request body is required"); } public void testBulkMissingBody() throws IOException { Request request = new Request(randomBoolean() ? "POST" : "PUT", "/_bulk"); request.setJsonEntity(""); ResponseException responseException = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertResponseException(responseException, "request body is required"); } public void testPutSettingsMissingBody() throws IOException { ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request("PUT", "/_settings")) ); assertResponseException(responseException, "request body is required"); } public void testPutMappingsMissingBody() throws IOException { ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request(randomBoolean() ? "POST" : "PUT", "/test_index/_mapping")) ); assertResponseException(responseException, "request body is required"); } public void testPutIndexTemplateMissingBody() throws IOException { ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request(randomBoolean() ? "PUT" : "POST", "/_template/my_template")) ); assertResponseException(responseException, "request body is required"); } public void testMultiSearchMissingBody() throws IOException { ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request(randomBoolean() ? "POST" : "GET", "/_msearch")) ); assertResponseException(responseException, "request body or source parameter is required"); } public void testPutPipelineMissingBody() throws IOException { ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request("PUT", "/_ingest/pipeline/my_pipeline")) ); assertResponseException(responseException, "request body or source parameter is required"); } public void testSimulatePipelineMissingBody() throws IOException { ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request(randomBoolean() ? "POST" : "GET", "/_ingest/pipeline/my_pipeline/_simulate")) ); assertResponseException(responseException, "request body or source parameter is required"); } public void testPutScriptMissingBody() throws IOException { ResponseException responseException = expectThrows( ResponseException.class, () -> client().performRequest(new Request(randomBoolean() ? "POST" : "PUT", "/_scripts/lang")) ); assertResponseException(responseException, "request body is required"); } private static void assertResponseException(ResponseException responseException, String message) { assertEquals(400, responseException.getResponse().getStatusLine().getStatusCode()); assertThat(responseException.getMessage(), containsString(message)); } }
RequestsWithoutContentIT
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/KeyStoresFactory.java
{ "start": 1309, "end": 2224 }
interface ____ extends Configurable { /** * Initializes the keystores of the factory. * * @param mode if the keystores are to be used in client or server mode. * @throws IOException thrown if the keystores could not be initialized due * to an IO error. * @throws GeneralSecurityException thrown if the keystores could not be * initialized due to an security error. */ public void init(SSLFactory.Mode mode) throws IOException, GeneralSecurityException; /** * Releases any resources being used. */ public void destroy(); /** * Returns the keymanagers for owned certificates. * * @return the keymanagers for owned certificates. */ public KeyManager[] getKeyManagers(); /** * Returns the trustmanagers for trusted certificates. * * @return the trustmanagers for trusted certificates. */ public TrustManager[] getTrustManagers(); }
KeyStoresFactory
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/UriAssert.java
{ "start": 687, "end": 730 }
class ____ {@link java.net.URI}s */ public
for
java
redisson__redisson
redisson/src/main/java/org/redisson/spring/transaction/RedissonTransactionManager.java
{ "start": 1429, "end": 5796 }
class ____ extends AbstractPlatformTransactionManager implements ResourceTransactionManager { private static final long serialVersionUID = -6151310954082124041L; private RedissonClient redisson; public RedissonTransactionManager(RedissonClient redisson) { this.redisson = redisson; } public RTransaction getCurrentTransaction() { RedissonTransactionHolder to = (RedissonTransactionHolder) TransactionSynchronizationManager.getResource(redisson); if (to == null) { throw new NoTransactionException("No transaction is available for the current thread"); } return to.getTransaction(); } @Override protected Object doGetTransaction() throws TransactionException { RedissonTransactionObject transactionObject = new RedissonTransactionObject(); RedissonTransactionHolder holder = (RedissonTransactionHolder) TransactionSynchronizationManager.getResource(redisson); if (holder != null) { transactionObject.setTransactionHolder(holder); } return transactionObject; } @Override protected boolean isExistingTransaction(Object transaction) throws TransactionException { RedissonTransactionObject transactionObject = (RedissonTransactionObject) transaction; return transactionObject.getTransactionHolder() != null; } @Override protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { RedissonTransactionObject tObject = (RedissonTransactionObject) transaction; if (tObject.getTransactionHolder() == null) { int timeout = determineTimeout(definition); TransactionOptions options = TransactionOptions.defaults(); if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { options.timeout(timeout, TimeUnit.SECONDS); } RTransaction trans = redisson.createTransaction(options); RedissonTransactionHolder holder = new RedissonTransactionHolder(); holder.setTransaction(trans); tObject.setTransactionHolder(holder); TransactionSynchronizationManager.bindResource(redisson, holder); } } @Override protected void doCommit(DefaultTransactionStatus status) throws TransactionException { RedissonTransactionObject to = (RedissonTransactionObject) status.getTransaction(); try { to.getTransactionHolder().getTransaction().commit(); } catch (org.redisson.transaction.TransactionException e) { throw new TransactionSystemException("Unable to commit transaction", e); } } @Override protected void doRollback(DefaultTransactionStatus status) throws TransactionException { RedissonTransactionObject to = (RedissonTransactionObject) status.getTransaction(); try { to.getTransactionHolder().getTransaction().rollback(); } catch (org.redisson.transaction.TransactionException e) { throw new TransactionSystemException("Unable to rollback transaction", e); } } @Override protected void doSetRollbackOnly(DefaultTransactionStatus status) throws TransactionException { RedissonTransactionObject to = (RedissonTransactionObject) status.getTransaction(); to.setRollbackOnly(true); } @Override protected void doResume(Object transaction, Object suspendedResources) throws TransactionException { TransactionSynchronizationManager.bindResource(redisson, suspendedResources); } @Override protected Object doSuspend(Object transaction) throws TransactionException { RedissonTransactionObject to = (RedissonTransactionObject) transaction; to.setTransactionHolder(null); return TransactionSynchronizationManager.unbindResource(redisson); } @Override protected void doCleanupAfterCompletion(Object transaction) { TransactionSynchronizationManager.unbindResourceIfPossible(redisson); RedissonTransactionObject to = (RedissonTransactionObject) transaction; to.getTransactionHolder().setTransaction(null); } @Override public Object getResourceFactory() { return redisson; } }
RedissonTransactionManager
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/EpochManager.java
{ "start": 1404, "end": 1529 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(EpochManager.class); /** * This
EpochManager
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/mixins/MixinInheritanceTest.java
{ "start": 745, "end": 907 }
class ____ extends Beano2 { @Override @JSONField(name = "name") public abstract String getNameo(); } static abstract
BeanoMixinSuper2
java
apache__flink
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/RocksDBListState.java
{ "start": 2655, "end": 11022 }
class ____<K, N, V> extends AbstractRocksDBState<K, N, List<V>> implements InternalListState<K, N, V> { /** Serializer for the values. */ private TypeSerializer<V> elementSerializer; private final ListDelimitedSerializer listSerializer; /** Separator of StringAppendTestOperator in RocksDB. */ private static final byte DELIMITER = ','; /** * Creates a new {@code RocksDBListState}. * * @param columnFamily The RocksDB column family that this state is associated to. * @param namespaceSerializer The serializer for the namespace. * @param valueSerializer The serializer for the state. * @param defaultValue The default value for the state. * @param backend The backend for which this state is bind to. */ private RocksDBListState( ColumnFamilyHandle columnFamily, TypeSerializer<N> namespaceSerializer, TypeSerializer<List<V>> valueSerializer, List<V> defaultValue, RocksDBKeyedStateBackend<K> backend) { super(columnFamily, namespaceSerializer, valueSerializer, defaultValue, backend); ListSerializer<V> castedListSerializer = (ListSerializer<V>) valueSerializer; this.elementSerializer = castedListSerializer.getElementSerializer(); this.listSerializer = new ListDelimitedSerializer(); } @Override public TypeSerializer<K> getKeySerializer() { return backend.getKeySerializer(); } @Override public TypeSerializer<N> getNamespaceSerializer() { return namespaceSerializer; } @Override public TypeSerializer<List<V>> getValueSerializer() { return valueSerializer; } @Override public Iterable<V> get() throws IOException, RocksDBException { return getInternal(); } @Override public List<V> getInternal() throws IOException, RocksDBException { byte[] key = serializeCurrentKeyWithGroupAndNamespace(); byte[] valueBytes = backend.db.get(columnFamily, key); return listSerializer.deserializeList(valueBytes, elementSerializer); } @Override public void add(V value) throws IOException, RocksDBException { Preconditions.checkNotNull(value, "You cannot add null to a ListState."); backend.db.merge( columnFamily, writeOptions, serializeCurrentKeyWithGroupAndNamespace(), serializeValue(value, elementSerializer)); } @Override public void mergeNamespaces(N target, Collection<N> sources) { if (sources == null || sources.isEmpty()) { return; } try { // create the target full-binary-key setCurrentNamespace(target); final byte[] targetKey = serializeCurrentKeyWithGroupAndNamespace(); // merge the sources to the target for (N source : sources) { if (source != null) { setCurrentNamespace(source); final byte[] sourceKey = serializeCurrentKeyWithGroupAndNamespace(); byte[] valueBytes = backend.db.get(columnFamily, sourceKey); if (valueBytes != null) { backend.db.delete(columnFamily, writeOptions, sourceKey); backend.db.merge(columnFamily, writeOptions, targetKey, valueBytes); } } } } catch (Exception e) { throw new FlinkRuntimeException("Error while merging state in RocksDB", e); } } @Override public void update(List<V> valueToStore) throws IOException, RocksDBException { updateInternal(valueToStore); } @Override public void updateInternal(List<V> values) throws IOException, RocksDBException { Preconditions.checkNotNull(values, "List of values to add cannot be null."); if (!values.isEmpty()) { backend.db.put( columnFamily, writeOptions, serializeCurrentKeyWithGroupAndNamespace(), listSerializer.serializeList(values, elementSerializer)); } else { clear(); } } @Override public void addAll(List<V> values) throws IOException, RocksDBException { Preconditions.checkNotNull(values, "List of values to add cannot be null."); if (!values.isEmpty()) { backend.db.merge( columnFamily, writeOptions, serializeCurrentKeyWithGroupAndNamespace(), listSerializer.serializeList(values, elementSerializer)); } } @Override public void migrateSerializedValue( DataInputDeserializer serializedOldValueInput, DataOutputSerializer serializedMigratedValueOutput, TypeSerializer<List<V>> priorSerializer, TypeSerializer<List<V>> newSerializer, TtlTimeProvider ttlTimeProvider) throws StateMigrationException { Preconditions.checkArgument( priorSerializer instanceof TtlAwareSerializer.TtlAwareListSerializer); Preconditions.checkArgument( newSerializer instanceof TtlAwareSerializer.TtlAwareListSerializer); TtlAwareSerializer<V, ?> priorTtlAwareElementSerializer = ((TtlAwareSerializer.TtlAwareListSerializer<V>) priorSerializer) .getElementSerializer(); TtlAwareSerializer<V, ?> newTtlAwareElementSerializer = ((TtlAwareSerializer.TtlAwareListSerializer<V>) newSerializer) .getElementSerializer(); try { while (serializedOldValueInput.available() > 0) { newTtlAwareElementSerializer.migrateValueFromPriorSerializer( priorTtlAwareElementSerializer, () -> ListDelimitedSerializer.deserializeNextElement( serializedOldValueInput, priorTtlAwareElementSerializer), serializedMigratedValueOutput, ttlTimeProvider); if (serializedOldValueInput.available() > 0) { serializedMigratedValueOutput.write(DELIMITER); } } } catch (Exception e) { throw new StateMigrationException( "Error while trying to migrate RocksDB list state.", e); } } @Override protected RocksDBListState<K, N, V> setValueSerializer( TypeSerializer<List<V>> valueSerializer) { super.setValueSerializer(valueSerializer); this.elementSerializer = ((ListSerializer<V>) valueSerializer).getElementSerializer(); return this; } @SuppressWarnings("unchecked") static <E, K, N, SV, S extends State, IS extends S> IS create( StateDescriptor<S, SV> stateDesc, Tuple2<ColumnFamilyHandle, RegisteredKeyValueStateBackendMetaInfo<N, SV>> registerResult, RocksDBKeyedStateBackend<K> backend) { return (IS) new RocksDBListState<>( registerResult.f0, registerResult.f1.getNamespaceSerializer(), (TypeSerializer<List<E>>) registerResult.f1.getStateSerializer(), (List<E>) stateDesc.getDefaultValue(), backend); } @SuppressWarnings("unchecked") static <E, K, N, SV, S extends State, IS extends S> IS update( StateDescriptor<S, SV> stateDesc, Tuple2<ColumnFamilyHandle, RegisteredKeyValueStateBackendMetaInfo<N, SV>> registerResult, IS existingState) { return (IS) ((RocksDBListState<K, N, E>) existingState) .setNamespaceSerializer(registerResult.f1.getNamespaceSerializer()) .setValueSerializer( (TypeSerializer<List<E>>) registerResult.f1.getStateSerializer()) .setDefaultValue((List<E>) stateDesc.getDefaultValue()) .setColumnFamily(registerResult.f0); } static
RocksDBListState
java
apache__camel
components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityTestHelper.java
{ "start": 1025, "end": 2252 }
class ____ { private UniVocityTestHelper() { // Helper class } /** * Creates a Map with the given key values * * @param keyValues the key values * @return Map with the given key values */ public static Map<String, String> asMap(String... keyValues) { if (keyValues == null || keyValues.length % 2 == 1) { throw new IllegalArgumentException("You must specify key values with an even number."); } Map<String, String> result = new LinkedHashMap<>(keyValues.length / 2); for (int i = 0; i < keyValues.length; i += 2) { result.put(keyValues[i], keyValues[i + 1]); } return result; } /** * Joins the given lines with the platform new line. * * @param lines lines to join * @return joined lines with the platform new line */ public static String join(String... lines) { if (lines == null || lines.length == 0) { return ""; } StringBuilder sb = new StringBuilder(); for (String line : lines) { sb.append(line).append(lineSeparator()); } return sb.toString(); } }
UniVocityTestHelper
java
quarkusio__quarkus
extensions/hibernate-validator/spi/src/main/java/io/quarkus/hibernate/validator/spi/AdditionalConstrainedClassBuildItem.java
{ "start": 106, "end": 1217 }
class ____ extends MultiBuildItem { private static final byte[] EMPTY = new byte[0]; private final Class<?> clazz; private final String name; private final byte[] bytes; private AdditionalConstrainedClassBuildItem(Class<?> clazz) { this.clazz = clazz; this.name = clazz.getName(); this.bytes = EMPTY; } private AdditionalConstrainedClassBuildItem(String name, byte[] bytes) { this.clazz = null; this.name = name; this.bytes = bytes; } public static AdditionalConstrainedClassBuildItem of(Class<?> clazz) { return new AdditionalConstrainedClassBuildItem(clazz); } public static AdditionalConstrainedClassBuildItem of(String name, byte[] bytes) { return new AdditionalConstrainedClassBuildItem(name, bytes); } public Class<?> getClazz() { return clazz; } public String getName() { return name; } public byte[] getBytes() { return bytes; } public boolean isGenerated() { return clazz == null; } }
AdditionalConstrainedClassBuildItem
java
netty__netty
codec-native-quic/src/test/java/io/netty/handler/codec/quic/QuicConnectionIdGeneratorTest.java
{ "start": 1038, "end": 3787 }
class ____ extends AbstractQuicTest { @Test public void testRandomness() { QuicConnectionIdGenerator idGenerator = QuicConnectionIdGenerator.randomGenerator(); ByteBuffer id = idGenerator.newId(Quiche.QUICHE_MAX_CONN_ID_LEN); ByteBuffer id2 = idGenerator.newId(Quiche.QUICHE_MAX_CONN_ID_LEN); assertThat(id.remaining()).isGreaterThan(0); assertThat(id2.remaining()).isGreaterThan(0); assertNotEquals(id, id2); id = idGenerator.newId(10); id2 = idGenerator.newId(10); assertEquals(10, id.remaining()); assertEquals(10, id2.remaining()); assertNotEquals(id, id2); byte[] input = new byte[1024]; ThreadLocalRandom.current().nextBytes(input); id = idGenerator.newId(ByteBuffer.wrap(input), 10); id2 = idGenerator.newId(ByteBuffer.wrap(input), 10); assertEquals(10, id.remaining()); assertEquals(10, id2.remaining()); assertNotEquals(id, id2); } @Test public void testThrowsIfInputTooBig() { QuicConnectionIdGenerator idGenerator = QuicConnectionIdGenerator.randomGenerator(); assertThrows(IllegalArgumentException.class, () -> idGenerator.newId(Integer.MAX_VALUE)); } @Test public void testThrowsIfInputTooBig2() { QuicConnectionIdGenerator idGenerator = QuicConnectionIdGenerator.randomGenerator(); assertThrows(IllegalArgumentException.class, () -> idGenerator.newId(ByteBuffer.wrap(new byte[8]), Integer.MAX_VALUE)); } @Test public void testSignIdGenerator() { QuicConnectionIdGenerator idGenerator = QuicConnectionIdGenerator.signGenerator(); byte[] input = new byte[1024]; byte[] input2 = new byte[1024]; ThreadLocalRandom.current().nextBytes(input); ThreadLocalRandom.current().nextBytes(input2); ByteBuffer id = idGenerator.newId(ByteBuffer.wrap(input), 10); ByteBuffer id2 = idGenerator.newId(ByteBuffer.wrap(input), 10); ByteBuffer id3 = idGenerator.newId(ByteBuffer.wrap(input2), 10); assertEquals(10, id.remaining()); assertEquals(10, id2.remaining()); assertEquals(10, id3.remaining()); assertEquals(id, id2); assertNotEquals(id, id3); assertThrows(UnsupportedOperationException.class, () -> idGenerator.newId(10)); assertThrows(NullPointerException.class, () -> idGenerator.newId(null, 10)); assertThrows(IllegalArgumentException.class, () -> idGenerator.newId(ByteBuffer.wrap(new byte[0]), 10)); assertThrows(IllegalArgumentException.class, () -> idGenerator.newId(ByteBuffer.wrap(input), Integer.MAX_VALUE)); } }
QuicConnectionIdGeneratorTest
java
quarkusio__quarkus
extensions/spring-data-jpa/deployment/src/test/java/io/quarkus/spring/data/deployment/WithDoubleValue.java
{ "start": 51, "end": 132 }
interface ____ { Integer getId(); Double getDoubleValue(); }
WithDoubleValue
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IgniteMessagingEndpointBuilderFactory.java
{ "start": 15813, "end": 18436 }
interface ____ extends EndpointProducerBuilder { default IgniteMessagingEndpointProducerBuilder basic() { return (IgniteMessagingEndpointProducerBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedIgniteMessagingEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedIgniteMessagingEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } } /** * Builder for endpoint for the Ignite Messaging component. */ public
AdvancedIgniteMessagingEndpointProducerBuilder
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodes.java
{ "start": 900, "end": 1284 }
class ____ normally loaded through a bean factory. * * <p>Used by Spring's {@link SQLErrorCodeSQLExceptionTranslator}. * The file "sql-error-codes.xml" in this package contains default * {@code SQLErrorCodes} instances for various databases. * * @author Thomas Risberg * @author Juergen Hoeller * @see SQLErrorCodesFactory * @see SQLErrorCodeSQLExceptionTranslator */ public
are
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/fielddata/FieldDataStats.java
{ "start": 7122, "end": 9274 }
class ____ { private long buildTimeMillis; @Nullable private Map<String, GlobalOrdinalFieldStats> fieldGlobalOrdinalsStats; public GlobalOrdinalsStats(long buildTimeMillis, Map<String, GlobalOrdinalFieldStats> fieldGlobalOrdinalsStats) { this.buildTimeMillis = buildTimeMillis; this.fieldGlobalOrdinalsStats = fieldGlobalOrdinalsStats; } public long getBuildTimeMillis() { return buildTimeMillis; } @Nullable public Map<String, GlobalOrdinalFieldStats> getFieldGlobalOrdinalsStats() { return fieldGlobalOrdinalsStats; } void add(GlobalOrdinalsStats other) { buildTimeMillis += other.buildTimeMillis; if (fieldGlobalOrdinalsStats != null && other.fieldGlobalOrdinalsStats != null) { for (var entry : other.fieldGlobalOrdinalsStats.entrySet()) { fieldGlobalOrdinalsStats.merge( entry.getKey(), entry.getValue(), (value1, value2) -> new GlobalOrdinalFieldStats( value1.totalBuildingTime + value2.totalBuildingTime, Math.max(value1.valueCount, value2.valueCount) ) ); } } else if (other.fieldGlobalOrdinalsStats != null) { fieldGlobalOrdinalsStats = other.fieldGlobalOrdinalsStats; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GlobalOrdinalsStats that = (GlobalOrdinalsStats) o; return buildTimeMillis == that.buildTimeMillis && Objects.equals(fieldGlobalOrdinalsStats, that.fieldGlobalOrdinalsStats); } @Override public int hashCode() { return Objects.hash(buildTimeMillis, fieldGlobalOrdinalsStats); } public record GlobalOrdinalFieldStats(long totalBuildingTime, long valueCount) {} } }
GlobalOrdinalsStats
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/scheduling/config/FixedRateTask.java
{ "start": 990, "end": 1970 }
class ____ extends IntervalTask { /** * Create a new {@code FixedRateTask}. * @param runnable the underlying task to execute * @param interval how often in milliseconds the task should be executed * @param initialDelay the initial delay before first execution of the task * @deprecated as of 6.0, in favor on {@link #FixedRateTask(Runnable, Duration, Duration)} */ @Deprecated(since = "6.0") public FixedRateTask(Runnable runnable, long interval, long initialDelay) { super(runnable, interval, initialDelay); } /** * Create a new {@code FixedRateTask}. * @param runnable the underlying task to execute * @param interval how often the task should be executed * @param initialDelay the initial delay before first execution of the task * @since 6.0 */ public FixedRateTask(Runnable runnable, Duration interval, Duration initialDelay) { super(runnable, interval, initialDelay); } FixedRateTask(IntervalTask task) { super(task); } }
FixedRateTask
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/plugins/PluginsServiceTests.java
{ "start": 32544, "end": 32994 }
class ____ extends Plugin implements ClusterPlugin { @Override public Map<String, Supplier<ShardsAllocator>> getShardsAllocators(Settings settings, ClusterSettings clusterSettings) { return Map.of(); } } """))); var pluginService = newPluginsService(settings); try { assertCriticalWarnings(""" Plugin
DeprecatedPlugin
java
resilience4j__resilience4j
resilience4j-spring6/src/test/java/io/github/resilience4j/spring6/RateLimiterDummyService.java
{ "start": 316, "end": 3706 }
class ____ implements TestDummyService { @Override @RateLimiter(name = BACKEND, fallbackMethod = "recovery") public String sync() { return syncError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "recovery") public String syncSuccess() { return "ok"; } @Override public CompletionStage<String> asyncThreadPool() { //no-op return null; } @Override public CompletionStage<String> asyncThreadPoolSuccess() { // no-op return null; } @Override @RateLimiter(name = BACKEND, fallbackMethod = "completionStageRecovery") public CompletionStage<String> async() { return asyncError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "fluxRecovery") public Flux<String> flux() { return fluxError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "monoRecovery") public Mono<String> mono(String parameter) { return monoError(parameter); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "observableRecovery") public Observable<String> observable() { return observableError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "singleRecovery") public Single<String> single() { return singleError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "completableRecovery") public Completable completable() { return completableError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "maybeRecovery") public Maybe<String> maybe() { return maybeError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "flowableRecovery") public Flowable<String> flowable() { return flowableError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "rx3ObservableRecovery") public io.reactivex.rxjava3.core.Observable<String> rx3Observable() { return rx3ObservableError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "rx3SingleRecovery") public io.reactivex.rxjava3.core.Single<String> rx3Single() { return rx3SingleError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "rx3CompletableRecovery") public io.reactivex.rxjava3.core.Completable rx3Completable() { return rx3CompletableError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "rx3MaybeRecovery") public io.reactivex.rxjava3.core.Maybe<String> rx3Maybe() { return rx3MaybeError(); } @Override @RateLimiter(name = BACKEND, fallbackMethod = "rx3FlowableRecovery") public io.reactivex.rxjava3.core.Flowable<String> rx3Flowable() { return rx3FlowableError(); } @Override @RateLimiter(name = "#root.args[0]", fallbackMethod = "#{'recovery'}") public String spelSync(String backend) { return syncError(); } @Override @RateLimiter(name = "#root.args[0]", fallbackMethod = "recovery") public String spelSyncNoCfg(String backend) { return backend; } @Override @RateLimiter(name = "#root.args[0]", configuration = BACKEND, fallbackMethod = "recovery") public String spelSyncWithCfg(String backend) { return backend; } }
RateLimiterDummyService
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/MutableRecordReader.java
{ "start": 1162, "end": 2024 }
class ____<T extends IOReadableWritable> extends AbstractRecordReader<T> implements MutableReader<T> { /** * Creates a new MutableRecordReader that de-serializes records from the given input gate and * can spill partial records to disk, if they grow large. * * @param inputGate The input gate to read from. * @param tmpDirectories The temp directories. USed for spilling if the reader concurrently * reconstructs multiple large records. */ public MutableRecordReader(InputGate inputGate, String[] tmpDirectories) { super(inputGate, tmpDirectories); } @Override public boolean next(final T target) throws IOException, InterruptedException { return getNextRecord(target); } @Override public void clearBuffers() { super.clearBuffers(); } }
MutableRecordReader
java
quarkusio__quarkus
test-framework/common/src/main/java/io/quarkus/test/common/RestorableSystemProperties.java
{ "start": 115, "end": 1868 }
class ____ implements Closeable { final Map<String, String> sysPropRestore; RestorableSystemProperties(Map<String, String> sysPropRestore) { this.sysPropRestore = sysPropRestore; } public static RestorableSystemProperties setProperties(Map<String, String> props, String... additionalKeysToSave) { Map<String, String> sysPropRestore = new HashMap<>(); for (var i : additionalKeysToSave) { sysPropRestore.put(i, System.getProperty(i)); } for (Map.Entry<String, String> i : props.entrySet()) { sysPropRestore.put(i.getKey(), System.getProperty(i.getKey())); } for (Map.Entry<String, String> i : props.entrySet()) { if (i.getKey() == null) { throw new IllegalArgumentException( String.format("Internal error: Cannot set null key as a system property (value is %s)", i.getValue())); } if (i.getValue() == null) { throw new IllegalArgumentException( String.format("Internal error: Cannot use null value as a system property (key is %s)", i.getKey())); } System.setProperty(i.getKey(), i.getValue()); } return new RestorableSystemProperties(sysPropRestore); } @Override public void close() { for (Map.Entry<String, String> entry : sysPropRestore.entrySet()) { String val = entry.getValue(); if (val == null) { System.clearProperty(entry.getKey()); } else { System.setProperty(entry.getKey(), val); } } } }
RestorableSystemProperties
java
apache__logging-log4j2
log4j-to-jul/src/test/java/org/apache/logging/log4j/tojul/LoggerTest.java
{ "start": 8108, "end": 8660 }
class ____ we have called (indirect), not in the test method itself. */ @Test void indirectSource() { java.util.logging.Logger.getLogger(Another.class.getName()).setLevel(Level.INFO); new Another(handler); final List<LogRecord> logs = handler.getStoredLogRecords(); assertThat(logs).hasSize(1); final LogRecord log1 = logs.get(0); assertThat(log1.getSourceClassName()).isEqualTo(Another.class.getName()); assertThat(log1.getSourceMethodName()).isEqualTo("<init>"); } static
that
java
apache__camel
components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/TrustAllOptions.java
{ "start": 1506, "end": 3236 }
class ____ implements TrustOptions { public static TrustAllOptions INSTANCE = new TrustAllOptions(); private static final TrustManager TRUST_ALL_MANAGER = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String authType) { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; private static final Provider PROVIDER = new Provider("", "0.0", "") { }; private TrustAllOptions() { // Avoid direct instantiation. } @Override public TrustOptions copy() { return this; } @Override public TrustManagerFactory getTrustManagerFactory(Vertx vertx) { return new TrustManagerFactory(new TrustManagerFactorySpi() { @Override protected void engineInit(KeyStore keyStore) { } @Override protected void engineInit(ManagerFactoryParameters managerFactoryParameters) { } @Override protected TrustManager[] engineGetTrustManagers() { return new TrustManager[] { TRUST_ALL_MANAGER }; } }, PROVIDER, "") { }; } @Override public Function<String, TrustManager[]> trustManagerMapper(Vertx vertx) { return new Function<String, TrustManager[]>() { @Override public TrustManager[] apply(String name) { return new TrustManager[] { TRUST_ALL_MANAGER }; } }; } }
TrustAllOptions
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/impl/pb/NamenodeHeartbeatRequestPBImpl.java
{ "start": 1964, "end": 3906 }
class ____ extends NamenodeHeartbeatRequest implements PBRecord { private FederationProtocolPBTranslator<NamenodeHeartbeatRequestProto, Builder, NamenodeHeartbeatRequestProtoOrBuilder> translator = new FederationProtocolPBTranslator<NamenodeHeartbeatRequestProto, Builder, NamenodeHeartbeatRequestProtoOrBuilder>( NamenodeHeartbeatRequestProto.class); public NamenodeHeartbeatRequestPBImpl() { } @Override public NamenodeHeartbeatRequestProto getProto() { return this.translator.build(); } @Override public void setProto(Message proto) { this.translator.setProto(proto); } @Override public void readInstance(String base64String) throws IOException { this.translator.readInstance(base64String); } @Override public MembershipState getNamenodeMembership() throws IOException { NamenodeMembershipRecordProto membershipProto = this.translator.getProtoOrBuilder().getNamenodeMembership(); MembershipState membership = StateStoreSerializer.newRecord(MembershipState.class); if (membership instanceof MembershipStatePBImpl) { MembershipStatePBImpl membershipPB = (MembershipStatePBImpl)membership; membershipPB.setProto(membershipProto); return membershipPB; } else { throw new IOException("Cannot get membership from request"); } } @Override public void setNamenodeMembership(MembershipState membership) throws IOException { if (membership instanceof MembershipStatePBImpl) { MembershipStatePBImpl membershipPB = (MembershipStatePBImpl)membership; NamenodeMembershipRecordProto membershipProto = (NamenodeMembershipRecordProto)membershipPB.getProto(); this.translator.getBuilder().setNamenodeMembership(membershipProto); } else { throw new IOException("Cannot set mount table entry"); } } }
NamenodeHeartbeatRequestPBImpl
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/cache/CacheKey.java
{ "start": 884, "end": 3753 }
class ____ implements Cloneable, Serializable { private static final long serialVersionUID = 1146682552656046210L; public static final CacheKey NULL_CACHE_KEY = new CacheKey() { private static final long serialVersionUID = 1L; @Override public void update(Object object) { throw new CacheException("Not allowed to update a null cache key instance."); } @Override public void updateAll(Object[] objects) { throw new CacheException("Not allowed to update a null cache key instance."); } }; private static final int DEFAULT_MULTIPLIER = 37; private static final int DEFAULT_HASHCODE = 17; private final int multiplier; private int hashcode; private long checksum; private int count; // 8/21/2017 - Sonarlint flags this as needing to be marked transient. While true if content is not serializable, this // is not always true and thus should not be marked transient. private List<Object> updateList; public CacheKey() { this.hashcode = DEFAULT_HASHCODE; this.multiplier = DEFAULT_MULTIPLIER; this.count = 0; this.updateList = new ArrayList<>(); } public CacheKey(Object[] objects) { this(); updateAll(objects); } public int getUpdateCount() { return updateList.size(); } public void update(Object object) { int baseHashCode = object == null ? 1 : ArrayUtil.hashCode(object); count++; checksum += baseHashCode; baseHashCode *= count; hashcode = multiplier * hashcode + baseHashCode; updateList.add(object); } public void updateAll(Object[] objects) { for (Object o : objects) { update(o); } } @Override public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof CacheKey)) { return false; } final CacheKey cacheKey = (CacheKey) object; if ((hashcode != cacheKey.hashcode) || (checksum != cacheKey.checksum) || (count != cacheKey.count)) { return false; } for (int i = 0; i < updateList.size(); i++) { Object thisObject = updateList.get(i); Object thatObject = cacheKey.updateList.get(i); if (!ArrayUtil.equals(thisObject, thatObject)) { return false; } } return true; } @Override public int hashCode() { return hashcode; } @Override public String toString() { StringJoiner returnValue = new StringJoiner(":"); returnValue.add(String.valueOf(hashcode)); returnValue.add(String.valueOf(checksum)); updateList.stream().map(ArrayUtil::toString).forEach(returnValue::add); return returnValue.toString(); } @Override public CacheKey clone() throws CloneNotSupportedException { CacheKey clonedCacheKey = (CacheKey) super.clone(); clonedCacheKey.updateList = new ArrayList<>(updateList); return clonedCacheKey; } }
CacheKey
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/foreach/OuterFieldProperties.java
{ "start": 829, "end": 1097 }
class ____ { private String name; protected List<InnerEach> inner; public String getName() { return name; } public void setName(String name) { this.name = name; } @EachProperty("inner") public static
OuterFieldProperties
java
spring-projects__spring-boot
module/spring-boot-health/src/main/java/org/springframework/boot/health/contributor/MapCompositeHealthContributor.java
{ "start": 1127, "end": 2209 }
class ____<V> implements CompositeHealthContributor { private final Map<String, HealthContributor> contributors; MapCompositeHealthContributor(Map<String, V> map, Function<V, ? extends HealthContributor> valueAdapter) { Assert.notNull(map, "'map' must not be null"); Assert.notNull(valueAdapter, "'valueAdapter' must not be null"); LinkedHashMap<String, HealthContributor> contributors = new LinkedHashMap<>(); map.forEach((key, value) -> { Assert.notNull(key, "'map' must not contain null keys"); Assert.notNull(value, "'map' must not contain null values"); Assert.isTrue(!key.contains("/"), "'map' keys must not contain a '/'"); contributors.put(key, valueAdapter.apply(value)); }); this.contributors = Collections.unmodifiableMap(contributors); } @Override public @Nullable HealthContributor getContributor(String name) { return this.contributors.get(name); } @Override public Stream<Entry> stream() { return this.contributors.entrySet().stream().map((entry) -> new Entry(entry.getKey(), entry.getValue())); } }
MapCompositeHealthContributor
java
apache__logging-log4j2
log4j-1.2-api/src/main/java/org/apache/log4j/helpers/Loader.java
{ "start": 928, "end": 1533 }
class ____ { static final String TSTR = "Caught Exception while in Loader.getResource. This may be innocuous."; private static boolean ignoreTCL; static { final String ignoreTCLProp = OptionConverter.getSystemProperty("log4j.ignoreTCL", null); if (ignoreTCLProp != null) { ignoreTCL = OptionConverter.toBoolean(ignoreTCLProp, true); } } /** * This method will search for <code>resource</code> in different places. The search order is as follows: * <ol> * <p> * <li>Search for <code>resource</code> using the thread context
Loader
java
quarkusio__quarkus
integration-tests/grpc-cli/src/main/java/io/quarkus/grpc/examples/cli/HelloWorldService.java
{ "start": 219, "end": 1271 }
class ____ extends GreeterGrpc.GreeterImplBase { private HelloReply getReply(HelloRequest request) { String name = request.getName(); return HelloReply.newBuilder().setMessage("Hello " + name).build(); } @Override public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) { responseObserver.onNext(getReply(request)); responseObserver.onCompleted(); } @Override public StreamObserver<HelloRequest> multiHello(StreamObserver<HelloReply> responseObserver) { return new StreamObserver<>() { @Override public void onNext(HelloRequest helloRequest) { responseObserver.onNext(getReply(helloRequest)); } @Override public void onError(Throwable throwable) { responseObserver.onError(throwable); } @Override public void onCompleted() { responseObserver.onCompleted(); } }; } }
HelloWorldService
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-shuffle/src/main/java/org/apache/hadoop/mapred/ShuffleHandler.java
{ "start": 26786, "end": 28248 }
class ____ { public final String jobId; public final String user; public final String attemptId; AttemptPathIdentifier(String jobId, String user, String attemptId) { this.jobId = jobId; this.user = user; this.attemptId = attemptId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AttemptPathIdentifier that = (AttemptPathIdentifier) o; if (!attemptId.equals(that.attemptId)) { return false; } if (!jobId.equals(that.jobId)) { return false; } return true; } @Override public int hashCode() { int result = jobId.hashCode(); result = 31 * result + attemptId.hashCode(); return result; } @Override public String toString() { return "AttemptPathIdentifier{" + "attemptId='" + attemptId + '\'' + ", jobId='" + jobId + '\'' + '}'; } } private static String getBaseLocation(String jobId, String user) { final JobID jobID = JobID.forName(jobId); final ApplicationId appID = ApplicationId.newInstance(Long.parseLong(jobID.getJtIdentifier()), jobID.getId()); return ContainerLocalizer.USERCACHE + "/" + user + "/" + ContainerLocalizer.APPCACHE + "/" + appID + "/output" + "/"; } }
AttemptPathIdentifier
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/EntityTypeChangeAuditDefaultTrackingTest.java
{ "start": 4197, "end": 4354 }
class ____ extends TrackingModifiedEntitiesRevisionMapping { } //end::envers-tracking-modified-entities-revchanges-example[] }
CustomTrackingRevisionEntity
java
apache__camel
components/camel-dropbox/src/main/java/org/apache/camel/component/dropbox/util/DropboxException.java
{ "start": 860, "end": 1205 }
class ____ extends Exception { private static final long serialVersionUID = 1L; public DropboxException(Throwable e) { super(e); } public DropboxException(String message) { super(message); } public DropboxException(String message, Throwable cause) { super(message, cause); } }
DropboxException