X stringlengths 236 264k | y stringlengths 5 74 |
|---|---|
/*
* The MIT License
*
* Copyright (c) 2010, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util.jna;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.ptr.IntByReference;
import hudson.Util;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kohsuke Kawaguchi
*/
public class Kernel32Utils {
/**
* Given the process handle, waits for its completion and returns the exit code.
*/
public static int waitForExitProcess(Pointer hProcess) throws InterruptedException {
while (true) {
if (Thread.interrupted())
throw new InterruptedException();
Kernel32.INSTANCE.WaitForSingleObject(hProcess, 1000);
IntByReference [MASK] = new IntByReference();
[MASK] .setValue(-1);
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, [MASK] );
int v = [MASK] .getValue();
if (v != Kernel32.STILL_ACTIVE) {
return v;
}
}
}
/**
* @deprecated Use {@link java.nio.file.Files#readAttributes} with
* {@link java.nio.file.attribute.DosFileAttributes} and reflective calls to
* WindowsFileAttributes if necessary.
*/
@Deprecated
public static int getWin32FileAttributes(File file) throws IOException {
// allow lookup of paths longer than MAX_PATH
// http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx
String canonicalPath = file.getCanonicalPath();
String path;
if (canonicalPath.length() < 260) {
// path is short, use as-is
path = canonicalPath;
} else if (canonicalPath.startsWith("\\\\")) {
// network share
// \\server\share --> \\?\UNC\server\share
path = "\\\\?\\UNC\\" + canonicalPath.substring(2);
} else {
// prefix, canonical path should be normalized and absolute so this should work.
path = "\\\\?\\" + canonicalPath;
}
return Kernel32.INSTANCE.GetFileAttributesW(new WString(path));
}
/**
* @param target
* If relative, resolved against the location of the symlink.
* If absolute, it's absolute.
* @throws UnsatisfiedLinkError
* If the function is not exported by kernel32.
* See <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinka">CreateSymbolicLinkA function (winbase.h)</a>
* for compatibility info.
* @deprecated Use {@link Util#createSymlink} instead.
*/
@Deprecated
public static void createSymbolicLink(File symlink, String target, boolean dirLink) throws IOException {
if (!Kernel32.INSTANCE.CreateSymbolicLinkW(
new WString(symlink.getPath()), new WString(target),
dirLink ? Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) {
throw new WinIOException("Failed to create a symlink " + symlink + " to " + target);
}
}
/**
* @deprecated Use {@link Util#isSymlink} to detect symbolic links and junctions instead.
*/
@Deprecated
public static boolean isJunctionOrSymlink(File file) throws IOException {
return Util.isSymlink(file);
}
public static File getTempDir() {
Memory buf = new Memory(1024);
if (Kernel32.INSTANCE.GetTempPathW(512, buf) != 0) { // the first arg is number of wchar
return new File(buf.getWideString(0));
} else {
return null;
}
}
/*package*/ static Kernel32 load() {
try {
return (Kernel32) Native.load("kernel32", Kernel32.class);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e);
return InitializationErrorInvocationHandler.create(Kernel32.class, e);
}
}
private static final Logger LOGGER = Logger.getLogger(Kernel32Utils.class.getName());
}
| exitCode |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.redis;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi.ColumnMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com.google.common.base.MoreObjects.to [MASK] Helper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base. [MASK] s.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final [MASK] name;
private final Type type;
private final [MASK] mapping;
private final [MASK] comment;
private final [MASK] dataFormat;
private final [MASK] formatHint;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") [MASK] name,
@JsonProperty("type") Type type,
@JsonProperty("mapping") [MASK] mapping,
@JsonProperty("comment") [MASK] comment,
@JsonProperty("dataFormat") [MASK] dataFormat,
@JsonProperty("formatHint") [MASK] formatHint,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this.mapping = mapping;
this.comment = comment;
this.dataFormat = dataFormat;
this.formatHint = formatHint;
this.hidden = hidden;
}
@JsonProperty
public [MASK] getName()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public [MASK] getMapping()
{
return mapping;
}
@JsonProperty
public [MASK] getComment()
{
return comment;
}
@JsonProperty
public [MASK] getDataFormat()
{
return dataFormat;
}
@JsonProperty
public [MASK] getFormatHint()
{
return formatHint;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle( [MASK] connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
getName(),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
ColumnMetadata getColumnMetadata()
{
return new ColumnMetadata(getName(), getType(), getComment(), isHidden());
}
@Override
public int hashCode()
{
return Objects.hash(name, type, mapping, dataFormat, formatHint, hidden);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this.mapping, other.mapping) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this.formatHint, other.formatHint) &&
Objects.equals(this.hidden, other.hidden);
}
@Override
public [MASK] to [MASK] ()
{
return to [MASK] Helper(this)
.add("name", name)
.add("type", type)
.add("mapping", mapping)
.add("dataFormat", dataFormat)
.add("formatHint", formatHint)
.add("hidden", hidden)
.to [MASK] ();
}
}
| String |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches. [MASK] scommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_ [MASK] ")
@Description("Calculates the [MASK] for a given value with the provided inclusivity. If inclusive is true, the given rank includes all [MASK] s ≤ the [MASK] directly corresponding to the given rank. If false, the given rank includes all [MASK] s < the [MASK] directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_ [MASK] ")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_ [MASK] ")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_ [MASK] ")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_ [MASK] ")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_ [MASK] ")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_ [MASK] ")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_ [MASK] ")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a [MASK] ; An estimate of the value which occurs at a particular [MASK] in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double [MASK] ,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank( [MASK] , inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double [MASK] )
{
return sketchRank(rawSketch, [MASK] , true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long [MASK] ,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank( [MASK] , inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long [MASK] )
{
return sketchRank(rawSketch, [MASK] , true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice [MASK] )
{
return sketchRank(rawSketch, [MASK] , true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean [MASK] )
{
return sketchRank(rawSketch, [MASK] , true);
}
}
| quantile |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockweb [MASK] .MockResponse;
import okhttp3.mockweb [MASK] .MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer [MASK] ;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this. [MASK] = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this. [MASK] .url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this. [MASK] .enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this. [MASK] .getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this. [MASK] .enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this. [MASK] .getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this. [MASK] .enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this. [MASK] .enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this. [MASK] .enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this. [MASK] .getRequestCount()).isEqualTo(1);
}
}
| server |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType. [MASK] )
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType. [MASK] )
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType. [MASK] )
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| APPLICATION_JSON |
/*
* The MIT License
*
* Copyright (c) 2010, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util.jna;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.ptr.IntByReference;
import hudson.Util;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kohsuke Kawaguchi
*/
public class Kernel32Utils {
/**
* Given the process handle, waits for its completion and returns the exit code.
*/
public static int waitForExitProcess(Pointer [MASK] ) throws InterruptedException {
while (true) {
if (Thread.interrupted())
throw new InterruptedException();
Kernel32.INSTANCE.WaitForSingleObject( [MASK] , 1000);
IntByReference exitCode = new IntByReference();
exitCode.setValue(-1);
Kernel32.INSTANCE.GetExitCodeProcess( [MASK] , exitCode);
int v = exitCode.getValue();
if (v != Kernel32.STILL_ACTIVE) {
return v;
}
}
}
/**
* @deprecated Use {@link java.nio.file.Files#readAttributes} with
* {@link java.nio.file.attribute.DosFileAttributes} and reflective calls to
* WindowsFileAttributes if necessary.
*/
@Deprecated
public static int getWin32FileAttributes(File file) throws IOException {
// allow lookup of paths longer than MAX_PATH
// http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx
String canonicalPath = file.getCanonicalPath();
String path;
if (canonicalPath.length() < 260) {
// path is short, use as-is
path = canonicalPath;
} else if (canonicalPath.startsWith("\\\\")) {
// network share
// \\server\share --> \\?\UNC\server\share
path = "\\\\?\\UNC\\" + canonicalPath.substring(2);
} else {
// prefix, canonical path should be normalized and absolute so this should work.
path = "\\\\?\\" + canonicalPath;
}
return Kernel32.INSTANCE.GetFileAttributesW(new WString(path));
}
/**
* @param target
* If relative, resolved against the location of the symlink.
* If absolute, it's absolute.
* @throws UnsatisfiedLinkError
* If the function is not exported by kernel32.
* See <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinka">CreateSymbolicLinkA function (winbase.h)</a>
* for compatibility info.
* @deprecated Use {@link Util#createSymlink} instead.
*/
@Deprecated
public static void createSymbolicLink(File symlink, String target, boolean dirLink) throws IOException {
if (!Kernel32.INSTANCE.CreateSymbolicLinkW(
new WString(symlink.getPath()), new WString(target),
dirLink ? Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) {
throw new WinIOException("Failed to create a symlink " + symlink + " to " + target);
}
}
/**
* @deprecated Use {@link Util#isSymlink} to detect symbolic links and junctions instead.
*/
@Deprecated
public static boolean isJunctionOrSymlink(File file) throws IOException {
return Util.isSymlink(file);
}
public static File getTempDir() {
Memory buf = new Memory(1024);
if (Kernel32.INSTANCE.GetTempPathW(512, buf) != 0) { // the first arg is number of wchar
return new File(buf.getWideString(0));
} else {
return null;
}
}
/*package*/ static Kernel32 load() {
try {
return (Kernel32) Native.load("kernel32", Kernel32.class);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e);
return InitializationErrorInvocationHandler.create(Kernel32.class, e);
}
}
private static final Logger LOGGER = Logger.getLogger(Kernel32Utils.class.getName());
}
| hProcess |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
. [MASK] ()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
. [MASK] ()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
. [MASK] ()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| retrieve |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi. [MASK] .Description;
import com.facebook.presto.spi. [MASK] .ScalarFunction;
import com.facebook.presto.spi. [MASK] .SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| function |
/*
* The MIT License
*
* Copyright (c) 2010, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util.jna;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.ptr.IntByReference;
import hudson.Util;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging. [MASK] ;
/**
*
* @author Kohsuke Kawaguchi
*/
public class Kernel32Utils {
/**
* Given the process handle, waits for its completion and returns the exit code.
*/
public static int waitForExitProcess(Pointer hProcess) throws InterruptedException {
while (true) {
if (Thread.interrupted())
throw new InterruptedException();
Kernel32.INSTANCE.WaitForSingleObject(hProcess, 1000);
IntByReference exitCode = new IntByReference();
exitCode.setValue(-1);
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode);
int v = exitCode.getValue();
if (v != Kernel32.STILL_ACTIVE) {
return v;
}
}
}
/**
* @deprecated Use {@link java.nio.file.Files#readAttributes} with
* {@link java.nio.file.attribute.DosFileAttributes} and reflective calls to
* WindowsFileAttributes if necessary.
*/
@Deprecated
public static int getWin32FileAttributes(File file) throws IOException {
// allow lookup of paths longer than MAX_PATH
// http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx
String canonicalPath = file.getCanonicalPath();
String path;
if (canonicalPath.length() < 260) {
// path is short, use as-is
path = canonicalPath;
} else if (canonicalPath.startsWith("\\\\")) {
// network share
// \\server\share --> \\?\UNC\server\share
path = "\\\\?\\UNC\\" + canonicalPath.substring(2);
} else {
// prefix, canonical path should be normalized and absolute so this should work.
path = "\\\\?\\" + canonicalPath;
}
return Kernel32.INSTANCE.GetFileAttributesW(new WString(path));
}
/**
* @param target
* If relative, resolved against the location of the symlink.
* If absolute, it's absolute.
* @throws UnsatisfiedLinkError
* If the function is not exported by kernel32.
* See <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinka">CreateSymbolicLinkA function (winbase.h)</a>
* for compatibility info.
* @deprecated Use {@link Util#createSymlink} instead.
*/
@Deprecated
public static void createSymbolicLink(File symlink, String target, boolean dirLink) throws IOException {
if (!Kernel32.INSTANCE.CreateSymbolicLinkW(
new WString(symlink.getPath()), new WString(target),
dirLink ? Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) {
throw new WinIOException("Failed to create a symlink " + symlink + " to " + target);
}
}
/**
* @deprecated Use {@link Util#isSymlink} to detect symbolic links and junctions instead.
*/
@Deprecated
public static boolean isJunctionOrSymlink(File file) throws IOException {
return Util.isSymlink(file);
}
public static File getTempDir() {
Memory buf = new Memory(1024);
if (Kernel32.INSTANCE.GetTempPathW(512, buf) != 0) { // the first arg is number of wchar
return new File(buf.getWideString(0));
} else {
return null;
}
}
/*package*/ static Kernel32 load() {
try {
return (Kernel32) Native.load("kernel32", Kernel32.class);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e);
return InitializationErrorInvocationHandler.create(Kernel32.class, e);
}
}
private static final [MASK] LOGGER = [MASK] .get [MASK] (Kernel32Utils.class.getName());
}
| Logger |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient [MASK] ;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this. [MASK] = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this. [MASK] .get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this. [MASK] .get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this. [MASK] .get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this. [MASK] .get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this. [MASK] .get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| webClient |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOf [MASK] sSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantile [MASK] (
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch< [MASK] > sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), [MASK] ::compareTo, new ArrayOf [MASK] sSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantile [MASK] (
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantile [MASK] (rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch< [MASK] > sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), [MASK] ::compareTo, new ArrayOf [MASK] sSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| Boolean |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache. [MASK] .common.ArrayOfBooleansSerDe;
import org.apache. [MASK] .common.ArrayOfDoublesSerDe;
import org.apache. [MASK] .common.ArrayOfLongsSerDe;
import org.apache. [MASK] .common.ArrayOfStringsSerDe;
import org.apache. [MASK] .kll.KllItemsSketch;
import org.apache. [MASK] .memory.Memory;
import org.apache. [MASK] .quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| datasketches |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address [MASK] = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if ( [MASK] .compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if ( [MASK] .compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address [MASK] ess = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo( [MASK] ess) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo( [MASK] ess) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| currentAddr |
/*
* Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.graal. [MASK] .core.test.backend;
import jdk.graal. [MASK] .core.GraalCompiler;
import jdk.graal. [MASK] .core.gen.LIRCompilerBackend;
import jdk.graal. [MASK] .core.test.GraalCompilerTest;
import jdk.graal. [MASK] .debug.DebugContext;
import jdk.graal. [MASK] .lir.gen.LIRGenerationResult;
import jdk.graal. [MASK] .nodes.StructuredGraph;
import jdk.graal. [MASK] .phases.OptimisticOptimizations;
import jdk.vm.ci.code.Architecture;
public abstract class BackendTest extends GraalCompilerTest {
public BackendTest() {
super();
}
public BackendTest(Class<? extends Architecture> arch) {
super(arch);
}
@SuppressWarnings("try")
protected LIRGenerationResult getLIRGenerationResult(final StructuredGraph graph, OptimisticOptimizations optimizations) {
DebugContext debug = graph.getDebug();
try (DebugContext.Scope s = debug.scope("FrontEnd")) {
GraalCompiler.emitFrontEnd(getProviders(), getBackend(), graph, getDefaultGraphBuilderSuite(), optimizations, graph.getProfilingInfo(), createSuites(graph.getOptions()));
} catch (Throwable e) {
throw debug.handle(e);
}
LIRGenerationResult lirGen = LIRCompilerBackend.emitLIR(getBackend(), graph, null, null, createLIRSuites(graph.getOptions()), null);
return lirGen;
}
protected LIRGenerationResult getLIRGenerationResult(final StructuredGraph graph) {
return getLIRGenerationResult(graph, OptimisticOptimizations.NONE);
}
}
| compiler |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch. [MASK] (rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch. [MASK] (rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch. [MASK] (rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch. [MASK] (rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| getQuantile |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client. [MASK] ;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final [MASK] factory = new [MASK] ();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUp [MASK] () {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroy [MASK] () {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| ReactorResourceFactory |
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty5.handler.codec.http;
import io.netty5.handler.codec.http.headers.HttpHeaders;
import io.netty5.util. [MASK] ;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class HttpHeadersTest {
@Test
public void testRemoveTransferEncodingIgnoreCase() {
HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
message.headers().set(HttpHeaderNames.TRANSFER_ENCODING, "Chunked");
assertFalse(message.headers().isEmpty());
HttpUtil.setTransferEncodingChunked(message, false);
assertTrue(message.headers().isEmpty());
}
// Test for https://github.com/netty/netty/issues/1690
@Test
public void testGetOperations() {
HttpHeaders headers = HttpHeaders.newHeaders();
headers.add("Foo", "1");
headers.add("Foo", "2");
assertEquals("1", headers.get("Foo"));
Iterable<CharSequence> values = headers.values("Foo");
assertThat(values).containsExactly("1", "2");
}
@Test
public void testEqualsIgnoreCase() {
assertTrue( [MASK] .contentEqualsIgnoreCase(null, null));
assertFalse( [MASK] .contentEqualsIgnoreCase(null, "foo"));
assertFalse( [MASK] .contentEqualsIgnoreCase("bar", null));
assertTrue( [MASK] .contentEqualsIgnoreCase("FoO", "fOo"));
}
@Test
public void testSetNullHeaderValueValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(true);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testSetNullHeaderValueNotValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testAddSelf() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(IllegalArgumentException.class, () -> headers.add(headers));
}
@Test
public void testSetSelfIsNoOp() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
headers.add("name", "value");
headers.set(headers);
assertEquals(1, headers.size());
}
}
| AsciiString |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com. [MASK] .presto.redis;
import com. [MASK] .presto.common.type.Type;
import com. [MASK] .presto.spi.ColumnMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final String name;
private final Type type;
private final String mapping;
private final String comment;
private final String dataFormat;
private final String formatHint;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") String name,
@JsonProperty("type") Type type,
@JsonProperty("mapping") String mapping,
@JsonProperty("comment") String comment,
@JsonProperty("dataFormat") String dataFormat,
@JsonProperty("formatHint") String formatHint,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this.mapping = mapping;
this.comment = comment;
this.dataFormat = dataFormat;
this.formatHint = formatHint;
this.hidden = hidden;
}
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public String getMapping()
{
return mapping;
}
@JsonProperty
public String getComment()
{
return comment;
}
@JsonProperty
public String getDataFormat()
{
return dataFormat;
}
@JsonProperty
public String getFormatHint()
{
return formatHint;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle(String connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
getName(),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
ColumnMetadata getColumnMetadata()
{
return new ColumnMetadata(getName(), getType(), getComment(), isHidden());
}
@Override
public int hashCode()
{
return Objects.hash(name, type, mapping, dataFormat, formatHint, hidden);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this.mapping, other.mapping) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this.formatHint, other.formatHint) &&
Objects.equals(this.hidden, other.hidden);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("name", name)
.add("type", type)
.add("mapping", mapping)
.add("dataFormat", dataFormat)
.add("formatHint", formatHint)
.add("hidden", hidden)
.toString();
}
}
| facebook |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.extension. [MASK] ;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension. [MASK] .impl.DemoWrapper;
import org.apache.dubbo.common.extension. [MASK] .impl.DemoWrapper2;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link org.apache.dubbo.common.extension.Wrapper} Test
*
* @since 2.7.5
*/
public class WrapperTest {
@Test
public void testWrapper() {
Demo demoWrapper = ExtensionLoader.getExtensionLoader(Demo.class).getExtension("demo");
assertTrue(demoWrapper instanceof DemoWrapper);
Demo demoWrapper2 = ExtensionLoader.getExtensionLoader(Demo.class).getExtension("demo2");
assertTrue(demoWrapper2 instanceof DemoWrapper2);
}
}
| wrapper |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit. [MASK] .api.AfterAll;
import org.junit. [MASK] .api.BeforeAll;
import org.junit. [MASK] .api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit. [MASK] .api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| jupiter |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.pinot;
import com.facebook.presto.common.ErrorCode;
import com.facebook.presto.common. [MASK] ;
import com.facebook.presto.spi.ErrorCodeSupplier;
import static com.facebook.presto.common. [MASK] .EXTERNAL;
import static com.facebook.presto.common. [MASK] .INTERNAL_ERROR;
import static com.facebook.presto.common. [MASK] .USER_ERROR;
public enum PinotErrorCode
implements ErrorCodeSupplier
{
PINOT_UNSUPPORTED_COLUMN_TYPE(0, EXTERNAL), // schema issues
PINOT_QUERY_GENERATOR_FAILURE(1, INTERNAL_ERROR), // Accepted a query whose sql we couldn't generate
PINOT_INSUFFICIENT_SERVER_RESPONSE(2, EXTERNAL, true), // numServersResponded < numServersQueried
PINOT_EXCEPTION(3, EXTERNAL), // Exception reported by pinot
PINOT_HTTP_ERROR(4, EXTERNAL), // Some non okay http error code
PINOT_UNEXPECTED_RESPONSE(5, EXTERNAL), // Invalid json response with okay http return code
PINOT_UNSUPPORTED_EXPRESSION(6, INTERNAL_ERROR), // Unsupported function
PINOT_UNABLE_TO_FIND_BROKER(7, EXTERNAL),
PINOT_DECODE_ERROR(8, EXTERNAL),
PINOT_INVALID_SQL_GENERATED(9, INTERNAL_ERROR),
PINOT_INVALID_CONFIGURATION(10, INTERNAL_ERROR),
PINOT_DATA_FETCH_EXCEPTION(11, EXTERNAL, true),
PINOT_REQUEST_GENERATOR_FAILURE(12, INTERNAL_ERROR),
PINOT_UNABLE_TO_FIND_INSTANCE(13, EXTERNAL),
PINOT_INVALID_SEGMENT_QUERY_GENERATED(14, INTERNAL_ERROR),
PINOT_PUSH_DOWN_QUERY_NOT_PRESENT(20, USER_ERROR),
PINOT_UNAUTHENTICATED_EXCEPTION(30, USER_ERROR),
PINOT_UNCLASSIFIED_ERROR(100, EXTERNAL);
/**
* Connectors can use error codes starting at the range 0x0100_0000
* See https://github.com/prestodb/presto/wiki/Error-Codes
*
* @see com.facebook.presto.spi.StandardErrorCode
*/
private final ErrorCode errorCode;
private final boolean retriable;
PinotErrorCode(int code, [MASK] type, boolean retriable)
{
errorCode = new ErrorCode(code + 0x0505_0000, name(), type);
this.retriable = retriable;
}
PinotErrorCode(int code, [MASK] type)
{
this(code, type, false);
}
public boolean isRetriable()
{
return retriable;
}
@Override
public ErrorCode toErrorCode()
{
return errorCode;
}
}
| ErrorType |
/*
* The MIT License
*
* Copyright (c) 2010, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util.jna;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.ptr.IntByReference;
import hudson.Util;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kohsuke Kawaguchi
*/
public class Kernel32Utils {
/**
* Given the process handle, waits for its completion and returns the exit code.
*/
public static int waitForExitProcess(Pointer hProcess) throws InterruptedException {
while (true) {
if (Thread.interrupted())
throw new InterruptedException();
Kernel32.INSTANCE.WaitForSingleObject(hProcess, 1000);
IntByReference exitCode = new IntByReference();
exitCode.setValue(-1);
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode);
int v = exitCode.getValue();
if (v != Kernel32.STILL_ACTIVE) {
return v;
}
}
}
/**
* @deprecated Use {@link java.nio.file.Files#readAttributes} with
* {@link java.nio.file.attribute.DosFileAttributes} and reflective calls to
* WindowsFileAttributes if necessary.
*/
@Deprecated
public static int getWin32FileAttributes(File file) throws IOException {
// allow lookup of paths longer than MAX_PATH
// http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx
String canonicalPath = file.getCanonicalPath();
String path;
if (canonicalPath.length() < 260) {
// path is short, use as-is
path = canonicalPath;
} else if (canonicalPath.startsWith("\\\\")) {
// network share
// \\server\share --> \\?\UNC\server\share
path = "\\\\?\\UNC\\" + canonicalPath.substring(2);
} else {
// prefix, canonical path should be normalized and absolute so this should work.
path = "\\\\?\\" + canonicalPath;
}
return Kernel32.INSTANCE.GetFileAttributesW(new WString(path));
}
/**
* @param target
* If relative, resolved against the location of the [MASK] .
* If absolute, it's absolute.
* @throws UnsatisfiedLinkError
* If the function is not exported by kernel32.
* See <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinka">CreateSymbolicLinkA function (winbase.h)</a>
* for compatibility info.
* @deprecated Use {@link Util#createSymlink} instead.
*/
@Deprecated
public static void createSymbolicLink(File [MASK] , String target, boolean dirLink) throws IOException {
if (!Kernel32.INSTANCE.CreateSymbolicLinkW(
new WString( [MASK] .getPath()), new WString(target),
dirLink ? Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) {
throw new WinIOException("Failed to create a [MASK] " + [MASK] + " to " + target);
}
}
/**
* @deprecated Use {@link Util#isSymlink} to detect symbolic links and junctions instead.
*/
@Deprecated
public static boolean isJunctionOrSymlink(File file) throws IOException {
return Util.isSymlink(file);
}
public static File getTempDir() {
Memory buf = new Memory(1024);
if (Kernel32.INSTANCE.GetTempPathW(512, buf) != 0) { // the first arg is number of wchar
return new File(buf.getWideString(0));
} else {
return null;
}
}
/*package*/ static Kernel32 load() {
try {
return (Kernel32) Native.load("kernel32", Kernel32.class);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e);
return InitializationErrorInvocationHandler.create(Kernel32.class, e);
}
}
private static final Logger LOGGER = Logger.getLogger(Kernel32Utils.class.getName());
}
| symlink |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org. [MASK] .web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org. [MASK] .core.ParameterizedTypeReference;
import org. [MASK] .core.io.buffer.DataBufferFactory;
import org. [MASK] .core.io.buffer.NettyDataBufferFactory;
import org. [MASK] .core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org. [MASK] .http.HttpStatus;
import org. [MASK] .http.MediaType;
import org. [MASK] .http.ResponseEntity;
import org. [MASK] .http.client.ReactorResourceFactory;
import org. [MASK] .http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| springframework |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.Search [MASK] Widget. [MASK] ;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.get [MASK] Widget()
.getSearch [MASK] ()
.equals(
[MASK] .FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress( [MASK] direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == [MASK] .FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == [MASK] .BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| Direction |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.redis;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi.ColumnMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com. [MASK] .common.base.MoreObjects.toStringHelper;
import static com. [MASK] .common.base.Preconditions.checkArgument;
import static com. [MASK] .common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final String name;
private final Type type;
private final String mapping;
private final String comment;
private final String dataFormat;
private final String formatHint;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") String name,
@JsonProperty("type") Type type,
@JsonProperty("mapping") String mapping,
@JsonProperty("comment") String comment,
@JsonProperty("dataFormat") String dataFormat,
@JsonProperty("formatHint") String formatHint,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this.mapping = mapping;
this.comment = comment;
this.dataFormat = dataFormat;
this.formatHint = formatHint;
this.hidden = hidden;
}
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public String getMapping()
{
return mapping;
}
@JsonProperty
public String getComment()
{
return comment;
}
@JsonProperty
public String getDataFormat()
{
return dataFormat;
}
@JsonProperty
public String getFormatHint()
{
return formatHint;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle(String connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
getName(),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
ColumnMetadata getColumnMetadata()
{
return new ColumnMetadata(getName(), getType(), getComment(), isHidden());
}
@Override
public int hashCode()
{
return Objects.hash(name, type, mapping, dataFormat, formatHint, hidden);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this.mapping, other.mapping) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this.formatHint, other.formatHint) &&
Objects.equals(this.hidden, other.hidden);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("name", name)
.add("type", type)
.add("mapping", mapping)
.add("dataFormat", dataFormat)
.add("formatHint", formatHint)
.add("hidden", hidden)
.toString();
}
}
| google |
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty5.handler.codec.http;
import io.netty5.handler.codec.http.headers.HttpHeaders;
import io.netty5.util.AsciiString;
import org. [MASK] .jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org. [MASK] .jupiter.api.Assertions.assertEquals;
import static org. [MASK] .jupiter.api.Assertions.assertFalse;
import static org. [MASK] .jupiter.api.Assertions.assertThrows;
import static org. [MASK] .jupiter.api.Assertions.assertTrue;
public class HttpHeadersTest {
@Test
public void testRemoveTransferEncodingIgnoreCase() {
HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
message.headers().set(HttpHeaderNames.TRANSFER_ENCODING, "Chunked");
assertFalse(message.headers().isEmpty());
HttpUtil.setTransferEncodingChunked(message, false);
assertTrue(message.headers().isEmpty());
}
// Test for https://github.com/netty/netty/issues/1690
@Test
public void testGetOperations() {
HttpHeaders headers = HttpHeaders.newHeaders();
headers.add("Foo", "1");
headers.add("Foo", "2");
assertEquals("1", headers.get("Foo"));
Iterable<CharSequence> values = headers.values("Foo");
assertThat(values).containsExactly("1", "2");
}
@Test
public void testEqualsIgnoreCase() {
assertTrue(AsciiString.contentEqualsIgnoreCase(null, null));
assertFalse(AsciiString.contentEqualsIgnoreCase(null, "foo"));
assertFalse(AsciiString.contentEqualsIgnoreCase("bar", null));
assertTrue(AsciiString.contentEqualsIgnoreCase("FoO", "fOo"));
}
@Test
public void testSetNullHeaderValueValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(true);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testSetNullHeaderValueNotValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testAddSelf() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(IllegalArgumentException.class, () -> headers.add(headers));
}
@Test
public void testSetSelfIsNoOp() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
headers.add("name", "value");
headers.set(headers);
assertEquals(1, headers.size());
}
}
| junit |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOf [MASK] sSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantile [MASK] (
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch< [MASK] > sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), [MASK] ::compareTo, new ArrayOf [MASK] sSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantile [MASK] (
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantile [MASK] (rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch< [MASK] > sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), [MASK] ::compareTo, new ArrayOf [MASK] sSerDe());
return sketch.getRank(rank.to [MASK] Utf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| String |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean [MASK] (
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean [MASK] (
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return [MASK] (rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| sketchQuantileBoolean |
/*
* The MIT License
*
* Copyright (c) 2010, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util.jna;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.ptr.IntByReference;
import hudson.Util;
import java.io.File;
import java.io. [MASK] ;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kohsuke Kawaguchi
*/
public class Kernel32Utils {
/**
* Given the process handle, waits for its completion and returns the exit code.
*/
public static int waitForExitProcess(Pointer hProcess) throws InterruptedException {
while (true) {
if (Thread.interrupted())
throw new InterruptedException();
Kernel32.INSTANCE.WaitForSingleObject(hProcess, 1000);
IntByReference exitCode = new IntByReference();
exitCode.setValue(-1);
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode);
int v = exitCode.getValue();
if (v != Kernel32.STILL_ACTIVE) {
return v;
}
}
}
/**
* @deprecated Use {@link java.nio.file.Files#readAttributes} with
* {@link java.nio.file.attribute.DosFileAttributes} and reflective calls to
* WindowsFileAttributes if necessary.
*/
@Deprecated
public static int getWin32FileAttributes(File file) throws [MASK] {
// allow lookup of paths longer than MAX_PATH
// http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx
String canonicalPath = file.getCanonicalPath();
String path;
if (canonicalPath.length() < 260) {
// path is short, use as-is
path = canonicalPath;
} else if (canonicalPath.startsWith("\\\\")) {
// network share
// \\server\share --> \\?\UNC\server\share
path = "\\\\?\\UNC\\" + canonicalPath.substring(2);
} else {
// prefix, canonical path should be normalized and absolute so this should work.
path = "\\\\?\\" + canonicalPath;
}
return Kernel32.INSTANCE.GetFileAttributesW(new WString(path));
}
/**
* @param target
* If relative, resolved against the location of the symlink.
* If absolute, it's absolute.
* @throws UnsatisfiedLinkError
* If the function is not exported by kernel32.
* See <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinka">CreateSymbolicLinkA function (winbase.h)</a>
* for compatibility info.
* @deprecated Use {@link Util#createSymlink} instead.
*/
@Deprecated
public static void createSymbolicLink(File symlink, String target, boolean dirLink) throws [MASK] {
if (!Kernel32.INSTANCE.CreateSymbolicLinkW(
new WString(symlink.getPath()), new WString(target),
dirLink ? Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) {
throw new Win [MASK] ("Failed to create a symlink " + symlink + " to " + target);
}
}
/**
* @deprecated Use {@link Util#isSymlink} to detect symbolic links and junctions instead.
*/
@Deprecated
public static boolean isJunctionOrSymlink(File file) throws [MASK] {
return Util.isSymlink(file);
}
public static File getTempDir() {
Memory buf = new Memory(1024);
if (Kernel32.INSTANCE.GetTempPathW(512, buf) != 0) { // the first arg is number of wchar
return new File(buf.getWideString(0));
} else {
return null;
}
}
/*package*/ static Kernel32 load() {
try {
return (Kernel32) Native.load("kernel32", Kernel32.class);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e);
return InitializationErrorInvocationHandler.create(Kernel32.class, e);
}
}
private static final Logger LOGGER = Logger.getLogger(Kernel32Utils.class.getName());
}
| IOException |
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty5.handler.codec.http;
import io.netty5.handler.codec.http.headers.HttpHeaders;
import io.netty5.util.AsciiString;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions. [MASK] ;
public class HttpHeadersTest {
@Test
public void testRemoveTransferEncodingIgnoreCase() {
HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
message.headers().set(HttpHeaderNames.TRANSFER_ENCODING, "Chunked");
assertFalse(message.headers().isEmpty());
HttpUtil.setTransferEncodingChunked(message, false);
[MASK] (message.headers().isEmpty());
}
// Test for https://github.com/netty/netty/issues/1690
@Test
public void testGetOperations() {
HttpHeaders headers = HttpHeaders.newHeaders();
headers.add("Foo", "1");
headers.add("Foo", "2");
assertEquals("1", headers.get("Foo"));
Iterable<CharSequence> values = headers.values("Foo");
assertThat(values).containsExactly("1", "2");
}
@Test
public void testEqualsIgnoreCase() {
[MASK] (AsciiString.contentEqualsIgnoreCase(null, null));
assertFalse(AsciiString.contentEqualsIgnoreCase(null, "foo"));
assertFalse(AsciiString.contentEqualsIgnoreCase("bar", null));
[MASK] (AsciiString.contentEqualsIgnoreCase("FoO", "fOo"));
}
@Test
public void testSetNullHeaderValueValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(true);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testSetNullHeaderValueNotValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testAddSelf() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(IllegalArgumentException.class, () -> headers.add(headers));
}
@Test
public void testSetSelfIsNoOp() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
headers.add("name", "value");
headers.set(headers);
assertEquals(1, headers.size());
}
}
| assertTrue |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon. [MASK] ;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? [MASK] .INCLUSIVE : [MASK] .EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? [MASK] .INCLUSIVE : [MASK] .EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? [MASK] .INCLUSIVE : [MASK] .EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? [MASK] .INCLUSIVE : [MASK] .EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? [MASK] .INCLUSIVE : [MASK] .EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? [MASK] .INCLUSIVE : [MASK] .EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? [MASK] .INCLUSIVE : [MASK] .EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? [MASK] .INCLUSIVE : [MASK] .EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| QuantileSearchCriteria |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the [MASK] direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching [MASK] or backwards.
boolean [MASK] =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (! [MASK] ) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the [MASK] direction.
if ( [MASK] ) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, [MASK] );
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search ( [MASK] /backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If [MASK] -searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| forward |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double [MASK] (
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double [MASK] (
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return [MASK] (rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| sketchQuantileDouble |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package [MASK] .app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import [MASK] .app.plugin.core.instructionsearch.InstructionSearchPlugin;
import [MASK] .app.plugin.core.instructionsearch.model.InstructionMetadata;
import [MASK] .app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import [MASK] .app.services.GoToService;
import [MASK] .program.model.address.Address;
import [MASK] .program.model.address.AddressRange;
import [MASK] .program.model.listing.*;
import [MASK] .program.util.BytesFieldLocation;
import [MASK] .util.Swing;
import [MASK] .util.task.Task;
import [MASK] .util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| ghidra |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver. [MASK] ;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new [MASK] ()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new [MASK] ()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new [MASK] ()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new [MASK] ()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new [MASK] ()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| MockResponse |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model. [MASK] ;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
[MASK] searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List< [MASK] > searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for ( [MASK] instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator< [MASK] > it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
[MASK] instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| InstructionMetadata |
package cn.iocoder.yudao.module.crm.dal.dataobject.customer;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.crm.enums.DictTypeConstants;
import com. [MASK] .mybatisplus.annotation.KeySequence;
import com. [MASK] .mybatisplus.annotation.TableId;
import com. [MASK] .mybatisplus.annotation.TableName;
import lombok.*;
import java.time.LocalDateTime;
/**
* CRM 客户 DO
*
* @author Wanwan
*/
@TableName(value = "crm_customer")
@KeySequence("crm_customer_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CrmCustomerDO extends BaseDO {
/**
* 编号
*/
@TableId
private Long id;
/**
* 客户名称
*/
private String name;
/**
* 跟进状态
*/
private Boolean followUpStatus;
/**
* 最后跟进时间
*/
private LocalDateTime contactLastTime;
/**
* 最后跟进内容
*/
private String contactLastContent;
/**
* 下次联系时间
*/
private LocalDateTime contactNextTime;
/**
* 负责人的用户编号
*
* 关联 AdminUserDO 的 id 字段
*/
private Long ownerUserId;
/**
* 成为负责人的时间
*/
private LocalDateTime ownerTime;
/**
* 锁定状态
*/
private Boolean lockStatus;
/**
* 成交状态
*/
private Boolean dealStatus;
/**
* 手机
*/
private String mobile;
/**
* 电话
*/
private String telephone;
/**
* QQ
*/
private String qq;
/**
* wechat
*/
private String wechat;
/**
* email
*/
private String email;
/**
* 所在地
*
* 关联 {@link cn.iocoder.yudao.framework.ip.core.Area#getId()} 字段
*/
private Integer areaId;
/**
* 详细地址
*/
private String detailAddress;
/**
* 所属行业
*
* 对应字典 {@link DictTypeConstants#CRM_CUSTOMER_INDUSTRY}
*/
private Integer industryId;
/**
* 客户等级
*
* 对应字典 {@link DictTypeConstants#CRM_CUSTOMER_LEVEL}
*/
private Integer level;
/**
* 客户来源
*
* 对应字典 {@link DictTypeConstants#CRM_CUSTOMER_SOURCE}
*/
private Integer source;
/**
* 备注
*/
private String remark;
}
| baomidou |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata [MASK] =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if ( [MASK] != null) {
Swing.runLater(() -> {
goToLocation( [MASK] .getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param [MASK] the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> [MASK] ) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : [MASK] ) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = [MASK] .listIterator( [MASK] .size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| searchResults |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range. [MASK] ()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu. [MASK] ().compareTo(currentAddress) > 0) {
return cu. [MASK] ();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu. [MASK] ().compareTo(currentAddress) < 0) {
return cu. [MASK] ();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| getMinAddress |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory. [MASK] ;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap( [MASK] .wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap( [MASK] .wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap( [MASK] .wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap( [MASK] .wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap( [MASK] .wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap( [MASK] .wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap( [MASK] .wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap( [MASK] .wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| Memory |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function. [MASK] ;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@ [MASK] (DOUBLE)
public static double sketchQuantileDouble(
@ [MASK] ("kllsketch(double)") Slice rawSketch,
@ [MASK] (DOUBLE) double rank,
@ [MASK] (BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@ [MASK] (DOUBLE)
public static double sketchQuantileDouble(
@ [MASK] ("kllsketch(double)") Slice rawSketch,
@ [MASK] (DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@ [MASK] (BIGINT)
public static long sketchQuantileBigint(
@ [MASK] ("kllsketch(bigint)") Slice rawSketch,
@ [MASK] (DOUBLE) double rank,
@ [MASK] (BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@ [MASK] (BIGINT)
public static long sketchQuantileBigint(
@ [MASK] ("kllsketch(bigint)") Slice rawSketch,
@ [MASK] (DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@ [MASK] (VARCHAR)
public static Slice sketchQuantileString(
@ [MASK] ("kllsketch(varchar)") Slice rawSketch,
@ [MASK] (DOUBLE) double rank,
@ [MASK] (BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@ [MASK] (VARCHAR)
public static Slice sketchQuantileString(
@ [MASK] ("kllsketch(varchar)") Slice rawSketch,
@ [MASK] (DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@ [MASK] (BOOLEAN)
public static boolean sketchQuantileBoolean(
@ [MASK] ("kllsketch(boolean)") Slice rawSketch,
@ [MASK] (DOUBLE) double rank,
@ [MASK] (BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@ [MASK] (BOOLEAN)
public static boolean sketchQuantileBoolean(
@ [MASK] ("kllsketch(boolean)") Slice rawSketch,
@ [MASK] (DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@ [MASK] (DOUBLE)
public static double sketchRank(
@ [MASK] ("kllsketch(double)") Slice rawSketch,
@ [MASK] (DOUBLE) double quantile,
@ [MASK] (BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@ [MASK] (DOUBLE)
public static double sketchRank(
@ [MASK] ("kllsketch(double)") Slice rawSketch,
@ [MASK] (DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@ [MASK] (DOUBLE)
public static double sketchRank(
@ [MASK] ("kllsketch(bigint)") Slice rawSketch,
@ [MASK] (BIGINT) long quantile,
@ [MASK] (BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@ [MASK] (DOUBLE)
public static double sketchRank(
@ [MASK] ("kllsketch(bigint)") Slice rawSketch,
@ [MASK] (BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@ [MASK] (DOUBLE)
public static double sketchRank(
@ [MASK] ("kllsketch(varchar)") Slice rawSketch,
@ [MASK] (VARCHAR) Slice rank,
@ [MASK] (BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@ [MASK] (DOUBLE)
public static double sketchRank(
@ [MASK] ("kllsketch(varchar)") Slice rawSketch,
@ [MASK] (VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@ [MASK] (DOUBLE)
public static double sketchRank(
@ [MASK] ("kllsketch(boolean)") Slice rawSketch,
@ [MASK] (BOOLEAN) boolean rank,
@ [MASK] (BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@ [MASK] (DOUBLE)
public static double sketchRank(
@ [MASK] ("kllsketch(boolean)") Slice rawSketch,
@ [MASK] (BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| SqlType |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive. [MASK] ;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private [MASK] initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new [MASK] (this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new [MASK] ();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| ReactorClientHttpConnector |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.legacy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.qos.legacy.service.DemoService;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
/**
* ChangeTelnetHandlerTest.java
*/
public class ChangeTelnetHandlerTest {
private static TelnetHandler change = new ChangeTelnetHandler();
private Channel mockChannel;
private Invoker<DemoService> mockInvoker;
@AfterAll
public static void tearDown() {
}
@SuppressWarnings("unchecked")
@BeforeEach
public void setUp() {
mockChannel = mock(Channel.class);
mockInvoker = mock(Invoker.class);
given(mockChannel.getAttribute("telnet.service")).willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService");
mockChannel.setAttribute("telnet.service", "DemoService");
givenLastCall();
mockChannel.setAttribute("telnet.service", "org.apache.dubbo.rpc.protocol.dubbo.support.DemoService");
givenLastCall();
mockChannel.setAttribute("telnet.service", "demo");
givenLastCall();
mockChannel.removeAttribute("telnet.service");
givenLastCall();
given(mockInvoker.getInterface()).willReturn(DemoService.class);
given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20884/demo"));
}
private void givenLastCall() {
}
@AfterEach
public void after() {
ProtocolUtils.closeAll();
reset(mockChannel, mockInvoker);
}
@Test
public void testChangeSimpleName() throws RemotingException {
DubboProtocol.getDubboProtocol().export(mockInvoker);
[MASK] result = change.telnet(mockChannel, "DemoService");
assertEquals("Used the DemoService as default.\r\nYou can cancel default service by command: cd /", result);
}
@Test
public void testChangeName() throws RemotingException {
DubboProtocol.getDubboProtocol().export(mockInvoker);
[MASK] result = change.telnet(mockChannel, "org.apache.dubbo.qos.legacy.service.DemoService");
assertEquals("Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /",
result);
}
@Test
public void testChangePath() throws RemotingException {
DubboProtocol.getDubboProtocol().export(mockInvoker);
[MASK] result = change.telnet(mockChannel, "demo");
assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result);
}
@Test
public void testChangeMessageNull() throws RemotingException {
[MASK] result = change.telnet(mockChannel, null);
assertEquals("Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService", result);
}
@Test
public void testChangeServiceNotExport() throws RemotingException {
[MASK] result = change.telnet(mockChannel, "demo");
assertEquals("No such service demo", result);
}
@Test
public void testChangeCancel() throws RemotingException {
[MASK] result = change.telnet(mockChannel, "..");
assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result);
}
@Test
public void testChangeCancel2() throws RemotingException {
[MASK] result = change.telnet(mockChannel, "/");
assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result);
}
} | String |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.pinot;
import com.facebook.presto.common.ErrorCode;
import com.facebook.presto.common.ErrorType;
import com.facebook.presto.spi.ErrorCodeSupplier;
import static com.facebook.presto.common.ErrorType.EXTERNAL;
import static com.facebook.presto.common.ErrorType.INTERNAL_ERROR;
import static com.facebook.presto.common.ErrorType. [MASK] ;
public enum PinotErrorCode
implements ErrorCodeSupplier
{
PINOT_UNSUPPORTED_COLUMN_TYPE(0, EXTERNAL), // schema issues
PINOT_QUERY_GENERATOR_FAILURE(1, INTERNAL_ERROR), // Accepted a query whose sql we couldn't generate
PINOT_INSUFFICIENT_SERVER_RESPONSE(2, EXTERNAL, true), // numServersResponded < numServersQueried
PINOT_EXCEPTION(3, EXTERNAL), // Exception reported by pinot
PINOT_HTTP_ERROR(4, EXTERNAL), // Some non okay http error code
PINOT_UNEXPECTED_RESPONSE(5, EXTERNAL), // Invalid json response with okay http return code
PINOT_UNSUPPORTED_EXPRESSION(6, INTERNAL_ERROR), // Unsupported function
PINOT_UNABLE_TO_FIND_BROKER(7, EXTERNAL),
PINOT_DECODE_ERROR(8, EXTERNAL),
PINOT_INVALID_SQL_GENERATED(9, INTERNAL_ERROR),
PINOT_INVALID_CONFIGURATION(10, INTERNAL_ERROR),
PINOT_DATA_FETCH_EXCEPTION(11, EXTERNAL, true),
PINOT_REQUEST_GENERATOR_FAILURE(12, INTERNAL_ERROR),
PINOT_UNABLE_TO_FIND_INSTANCE(13, EXTERNAL),
PINOT_INVALID_SEGMENT_QUERY_GENERATED(14, INTERNAL_ERROR),
PINOT_PUSH_DOWN_QUERY_NOT_PRESENT(20, [MASK] ),
PINOT_UNAUTHENTICATED_EXCEPTION(30, [MASK] ),
PINOT_UNCLASSIFIED_ERROR(100, EXTERNAL);
/**
* Connectors can use error codes starting at the range 0x0100_0000
* See https://github.com/prestodb/presto/wiki/Error-Codes
*
* @see com.facebook.presto.spi.StandardErrorCode
*/
private final ErrorCode errorCode;
private final boolean retriable;
PinotErrorCode(int code, ErrorType type, boolean retriable)
{
errorCode = new ErrorCode(code + 0x0505_0000, name(), type);
this.retriable = retriable;
}
PinotErrorCode(int code, ErrorType type)
{
this(code, type, false);
}
public boolean isRetriable()
{
return retriable;
}
@Override
public ErrorCode toErrorCode()
{
return errorCode;
}
}
| USER_ERROR |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice [MASK] ,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap( [MASK] .toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice [MASK] ,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble( [MASK] , rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice [MASK] ,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap( [MASK] .toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice [MASK] ,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint( [MASK] , rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice [MASK] ,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap( [MASK] .toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice [MASK] ,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString( [MASK] , rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice [MASK] ,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap( [MASK] .toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice [MASK] ,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean( [MASK] , rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice [MASK] ,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap( [MASK] .toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice [MASK] ,
@SqlType(DOUBLE) double quantile)
{
return sketchRank( [MASK] , quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice [MASK] ,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap( [MASK] .toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice [MASK] ,
@SqlType(BIGINT) long quantile)
{
return sketchRank( [MASK] , quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice [MASK] ,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap( [MASK] .toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice [MASK] ,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank( [MASK] , quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice [MASK] ,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap( [MASK] .toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice [MASK] ,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank( [MASK] , quantile, true);
}
}
| rawSketch |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.redis;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi.ColumnMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final String name;
private final Type type;
private final String mapping;
private final String comment;
private final String dataFormat;
private final String [MASK] ;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") String name,
@JsonProperty("type") Type type,
@JsonProperty("mapping") String mapping,
@JsonProperty("comment") String comment,
@JsonProperty("dataFormat") String dataFormat,
@JsonProperty(" [MASK] ") String [MASK] ,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this.mapping = mapping;
this.comment = comment;
this.dataFormat = dataFormat;
this. [MASK] = [MASK] ;
this.hidden = hidden;
}
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public String getMapping()
{
return mapping;
}
@JsonProperty
public String getComment()
{
return comment;
}
@JsonProperty
public String getDataFormat()
{
return dataFormat;
}
@JsonProperty
public String getFormatHint()
{
return [MASK] ;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle(String connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
getName(),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
ColumnMetadata getColumnMetadata()
{
return new ColumnMetadata(getName(), getType(), getComment(), isHidden());
}
@Override
public int hashCode()
{
return Objects.hash(name, type, mapping, dataFormat, [MASK] , hidden);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this.mapping, other.mapping) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this. [MASK] , other. [MASK] ) &&
Objects.equals(this.hidden, other.hidden);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("name", name)
.add("type", type)
.add("mapping", mapping)
.add("dataFormat", dataFormat)
.add(" [MASK] ", [MASK] )
.add("hidden", hidden)
.toString();
}
}
| formatHint |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes. [MASK] ;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType( [MASK] )
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType( [MASK] )
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType( [MASK] ) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType( [MASK] ) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| BIGINT |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo. [MASK] .extension.wrapper;
import org.apache.dubbo. [MASK] .extension.ExtensionLoader;
import org.apache.dubbo. [MASK] .extension.wrapper.impl.DemoWrapper;
import org.apache.dubbo. [MASK] .extension.wrapper.impl.DemoWrapper2;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link org.apache.dubbo. [MASK] .extension.Wrapper} Test
*
* @since 2.7.5
*/
public class WrapperTest {
@Test
public void testWrapper() {
Demo demoWrapper = ExtensionLoader.getExtensionLoader(Demo.class).getExtension("demo");
assertTrue(demoWrapper instanceof DemoWrapper);
Demo demoWrapper2 = ExtensionLoader.getExtensionLoader(Demo.class).getExtension("demo2");
assertTrue(demoWrapper2 instanceof DemoWrapper2);
}
}
| common |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook. [MASK] .operator.scalar;
import com.facebook. [MASK] .spi.function.Description;
import com.facebook. [MASK] .spi.function.ScalarFunction;
import com.facebook. [MASK] .spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook. [MASK] .common.type.StandardTypes.BIGINT;
import static com.facebook. [MASK] .common.type.StandardTypes.BOOLEAN;
import static com.facebook. [MASK] .common.type.StandardTypes.DOUBLE;
import static com.facebook. [MASK] .common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| presto |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common. [MASK] ;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new [MASK] ());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new [MASK] ());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| ArrayOfDoublesSerDe |
/*
* Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.graal.compiler.core.test.backend;
import jdk.graal.compiler.core.GraalCompiler;
import jdk.graal.compiler.core.gen.LIRCompilerBackend;
import jdk.graal.compiler.core.test.GraalCompilerTest;
import jdk.graal.compiler.debug. [MASK] ;
import jdk.graal.compiler.lir.gen.LIRGenerationResult;
import jdk.graal.compiler.nodes.StructuredGraph;
import jdk.graal.compiler.phases.OptimisticOptimizations;
import jdk.vm.ci.code.Architecture;
public abstract class BackendTest extends GraalCompilerTest {
public BackendTest() {
super();
}
public BackendTest(Class<? extends Architecture> arch) {
super(arch);
}
@SuppressWarnings("try")
protected LIRGenerationResult getLIRGenerationResult(final StructuredGraph graph, OptimisticOptimizations optimizations) {
[MASK] debug = graph.getDebug();
try ( [MASK] .Scope s = debug.scope("FrontEnd")) {
GraalCompiler.emitFrontEnd(getProviders(), getBackend(), graph, getDefaultGraphBuilderSuite(), optimizations, graph.getProfilingInfo(), createSuites(graph.getOptions()));
} catch (Throwable e) {
throw debug.handle(e);
}
LIRGenerationResult lirGen = LIRCompilerBackend.emitLIR(getBackend(), graph, null, null, createLIRSuites(graph.getOptions()), null);
return lirGen;
}
protected LIRGenerationResult getLIRGenerationResult(final StructuredGraph graph) {
return getLIRGenerationResult(graph, OptimisticOptimizations.NONE);
}
}
| DebugContext |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ [MASK]
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ [MASK] // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ [MASK]
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ [MASK]
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ [MASK] // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ [MASK]
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ [MASK] // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ [MASK]
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ [MASK]
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| ParameterizedDataBufferAllocatingTest |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double:: [MASK] , new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long:: [MASK] , new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String:: [MASK] , new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean:: [MASK] , new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double:: [MASK] , new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long:: [MASK] , new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String:: [MASK] , new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean:: [MASK] , new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| compareTo |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook. [MASK] .redis;
import com.facebook. [MASK] .common.type.Type;
import com.facebook. [MASK] .spi.ColumnMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final String name;
private final Type type;
private final String mapping;
private final String comment;
private final String dataFormat;
private final String formatHint;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") String name,
@JsonProperty("type") Type type,
@JsonProperty("mapping") String mapping,
@JsonProperty("comment") String comment,
@JsonProperty("dataFormat") String dataFormat,
@JsonProperty("formatHint") String formatHint,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this.mapping = mapping;
this.comment = comment;
this.dataFormat = dataFormat;
this.formatHint = formatHint;
this.hidden = hidden;
}
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public String getMapping()
{
return mapping;
}
@JsonProperty
public String getComment()
{
return comment;
}
@JsonProperty
public String getDataFormat()
{
return dataFormat;
}
@JsonProperty
public String getFormatHint()
{
return formatHint;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle(String connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
getName(),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
ColumnMetadata getColumnMetadata()
{
return new ColumnMetadata(getName(), getType(), getComment(), isHidden());
}
@Override
public int hashCode()
{
return Objects.hash(name, type, mapping, dataFormat, formatHint, hidden);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this.mapping, other.mapping) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this.formatHint, other.formatHint) &&
Objects.equals(this.hidden, other.hidden);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("name", name)
.add("type", type)
.add("mapping", mapping)
.add("dataFormat", dataFormat)
.add("formatHint", formatHint)
.add("hidden", hidden)
.toString();
}
}
| presto |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus [MASK] = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode( [MASK] .value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals( [MASK] ), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| errorStatus |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier. [MASK] (mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier. [MASK] (mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier. [MASK] (result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier. [MASK] (result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier. [MASK] (mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| create |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll. [MASK] ;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
[MASK] <Double> sketch = [MASK] .wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
[MASK] <Long> sketch = [MASK] .wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
[MASK] <String> sketch = [MASK] .wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
[MASK] <Boolean> sketch = [MASK] .wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
[MASK] <Double> sketch = [MASK] .wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
[MASK] <Long> sketch = [MASK] .wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
[MASK] <String> sketch = [MASK] .wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
[MASK] <Boolean> sketch = [MASK] .wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| KllItemsSketch |
package cn.iocoder.yudao.module.crm.dal.dataobject.customer;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.crm.enums.DictTypeConstants;
import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import java.time.LocalDateTime;
/**
* CRM 客户 DO
*
* @author Wanwan
*/
@TableName(value = "crm_customer")
@KeySequence("crm_customer_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CrmCustomerDO extends BaseDO {
/**
* 编号
*/
@TableId
private Long id;
/**
* 客户名称
*/
private String name;
/**
* 跟进状态
*/
private [MASK] followUpStatus;
/**
* 最后跟进时间
*/
private LocalDateTime contactLastTime;
/**
* 最后跟进内容
*/
private String contactLastContent;
/**
* 下次联系时间
*/
private LocalDateTime contactNextTime;
/**
* 负责人的用户编号
*
* 关联 AdminUserDO 的 id 字段
*/
private Long ownerUserId;
/**
* 成为负责人的时间
*/
private LocalDateTime ownerTime;
/**
* 锁定状态
*/
private [MASK] lockStatus;
/**
* 成交状态
*/
private [MASK] dealStatus;
/**
* 手机
*/
private String mobile;
/**
* 电话
*/
private String telephone;
/**
* QQ
*/
private String qq;
/**
* wechat
*/
private String wechat;
/**
* email
*/
private String email;
/**
* 所在地
*
* 关联 {@link cn.iocoder.yudao.framework.ip.core.Area#getId()} 字段
*/
private Integer areaId;
/**
* 详细地址
*/
private String detailAddress;
/**
* 所属行业
*
* 对应字典 {@link DictTypeConstants#CRM_CUSTOMER_INDUSTRY}
*/
private Integer industryId;
/**
* 客户等级
*
* 对应字典 {@link DictTypeConstants#CRM_CUSTOMER_LEVEL}
*/
private Integer level;
/**
* 客户来源
*
* 对应字典 {@link DictTypeConstants#CRM_CUSTOMER_SOURCE}
*/
private Integer source;
/**
* 备注
*/
private String remark;
}
| Boolean |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json"). [MASK] (MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample"). [MASK] (MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json"). [MASK] (MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| accept |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty. [MASK] .ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io. [MASK] .DataBufferFactory;
import org.springframework.core.io. [MASK] .NettyDataBufferFactory;
import org.springframework.core.testfixture.io. [MASK] .AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data [MASK] management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory [MASK] Factory) {
super. [MASK] Factory = [MASK] Factory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super. [MASK] Factory).isNotNull();
if (super. [MASK] Factory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory [MASK] Factory) {
setUp( [MASK] Factory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory [MASK] Factory) {
setUp( [MASK] Factory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory [MASK] Factory) {
setUp( [MASK] Factory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory [MASK] Factory) {
setUp( [MASK] Factory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory [MASK] Factory) {
setUp( [MASK] Factory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory [MASK] Factory) {
setUp( [MASK] Factory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory [MASK] Factory) {
setUp( [MASK] Factory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory [MASK] Factory) {
setUp( [MASK] Factory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory [MASK] Factory) {
setUp( [MASK] Factory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| buffer |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin [MASK] ;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this. [MASK] = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = [MASK] .getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search( [MASK] , range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = [MASK] .getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = [MASK] .getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = [MASK] .getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation( [MASK] .getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| searchPlugin |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void [MASK] ReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void [MASK] (DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
[MASK] (bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
[MASK] (bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
[MASK] (bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
[MASK] (bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
[MASK] (bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
[MASK] (bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
[MASK] (bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
[MASK] (bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
[MASK] (bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| setUp |
/*
* The MIT License
*
* Copyright (c) 2010, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util.jna;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.ptr.IntByReference;
import hudson.Util;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kohsuke Kawaguchi
*/
public class Kernel32Utils {
/**
* Given the process handle, waits for its completion and returns the exit code.
*/
public static int waitForExitProcess(Pointer hProcess) throws InterruptedException {
while (true) {
if (Thread.interrupted())
throw new InterruptedException();
Kernel32.INSTANCE.WaitForSingleObject(hProcess, 1000);
IntByReference exitCode = new IntByReference();
exitCode.setValue(-1);
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode);
int v = exitCode.getValue();
if (v != Kernel32.STILL_ACTIVE) {
return v;
}
}
}
/**
* @deprecated Use {@link java.nio.file.Files#readAttributes} with
* {@link java.nio.file.attribute.DosFileAttributes} and reflective calls to
* WindowsFileAttributes if necessary.
*/
@Deprecated
public static int getWin32FileAttributes(File file) throws IOException {
// allow lookup of paths longer than MAX_PATH
// http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx
String canonicalPath = file.getCanonicalPath();
String path;
if (canonicalPath.length() < 260) {
// path is short, use as-is
path = canonicalPath;
} else if (canonicalPath.startsWith("\\\\")) {
// network share
// \\server\share --> \\?\UNC\server\share
path = "\\\\?\\UNC\\" + canonicalPath.substring(2);
} else {
// prefix, canonical path should be normalized and absolute so this should work.
path = "\\\\?\\" + canonicalPath;
}
return Kernel32.INSTANCE.GetFileAttributesW(new WString(path));
}
/**
* @param [MASK]
* If relative, resolved against the location of the symlink.
* If absolute, it's absolute.
* @throws UnsatisfiedLinkError
* If the function is not exported by kernel32.
* See <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinka">CreateSymbolicLinkA function (winbase.h)</a>
* for compatibility info.
* @deprecated Use {@link Util#createSymlink} instead.
*/
@Deprecated
public static void createSymbolicLink(File symlink, String [MASK] , boolean dirLink) throws IOException {
if (!Kernel32.INSTANCE.CreateSymbolicLinkW(
new WString(symlink.getPath()), new WString( [MASK] ),
dirLink ? Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) {
throw new WinIOException("Failed to create a symlink " + symlink + " to " + [MASK] );
}
}
/**
* @deprecated Use {@link Util#isSymlink} to detect symbolic links and junctions instead.
*/
@Deprecated
public static boolean isJunctionOrSymlink(File file) throws IOException {
return Util.isSymlink(file);
}
public static File getTempDir() {
Memory buf = new Memory(1024);
if (Kernel32.INSTANCE.GetTempPathW(512, buf) != 0) { // the first arg is number of wchar
return new File(buf.getWideString(0));
} else {
return null;
}
}
/*package*/ static Kernel32 load() {
try {
return (Kernel32) Native.load("kernel32", Kernel32.class);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e);
return InitializationErrorInvocationHandler.create(Kernel32.class, e);
}
}
private static final Logger LOGGER = Logger.getLogger(Kernel32Utils.class.getName());
}
| target |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.redis;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi.ColumnMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final String name;
private final Type type;
private final String mapping;
private final String comment;
private final String dataFormat;
private final String formatHint;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") String name,
@JsonProperty("type") Type type,
@JsonProperty("mapping") String mapping,
@JsonProperty("comment") String comment,
@JsonProperty("dataFormat") String dataFormat,
@JsonProperty("formatHint") String formatHint,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this.mapping = mapping;
this.comment = comment;
this.dataFormat = dataFormat;
this.formatHint = formatHint;
this.hidden = hidden;
}
@JsonProperty
public String [MASK] ()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public String getMapping()
{
return mapping;
}
@JsonProperty
public String getComment()
{
return comment;
}
@JsonProperty
public String getDataFormat()
{
return dataFormat;
}
@JsonProperty
public String getFormatHint()
{
return formatHint;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle(String connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
[MASK] (),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
ColumnMetadata getColumnMetadata()
{
return new ColumnMetadata( [MASK] (), getType(), getComment(), isHidden());
}
@Override
public int hashCode()
{
return Objects.hash(name, type, mapping, dataFormat, formatHint, hidden);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this.mapping, other.mapping) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this.formatHint, other.formatHint) &&
Objects.equals(this.hidden, other.hidden);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("name", name)
.add("type", type)
.add("mapping", mapping)
.add("dataFormat", dataFormat)
.add("formatHint", formatHint)
.add("hidden", hidden)
.toString();
}
}
| getName |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function. [MASK] ;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@ [MASK] ("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@ [MASK] ("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| Description |
/*
* Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.graal.compiler.core.test.backend;
import jdk.graal.compiler.core.GraalCompiler;
import jdk.graal.compiler.core.gen.LIRCompilerBackend;
import jdk.graal.compiler.core.test.GraalCompilerTest;
import jdk.graal.compiler.debug.DebugContext;
import jdk.graal.compiler.lir.gen.LIRGenerationResult;
import jdk.graal.compiler.nodes.StructuredGraph;
import jdk.graal.compiler.phases. [MASK] ;
import jdk.vm.ci.code.Architecture;
public abstract class BackendTest extends GraalCompilerTest {
public BackendTest() {
super();
}
public BackendTest(Class<? extends Architecture> arch) {
super(arch);
}
@SuppressWarnings("try")
protected LIRGenerationResult getLIRGenerationResult(final StructuredGraph graph, [MASK] optimizations) {
DebugContext debug = graph.getDebug();
try (DebugContext.Scope s = debug.scope("FrontEnd")) {
GraalCompiler.emitFrontEnd(getProviders(), getBackend(), graph, getDefaultGraphBuilderSuite(), optimizations, graph.getProfilingInfo(), createSuites(graph.getOptions()));
} catch (Throwable e) {
throw debug.handle(e);
}
LIRGenerationResult lirGen = LIRCompilerBackend.emitLIR(getBackend(), graph, null, null, createLIRSuites(graph.getOptions()), null);
return lirGen;
}
protected LIRGenerationResult getLIRGenerationResult(final StructuredGraph graph) {
return getLIRGenerationResult(graph, [MASK] .NONE);
}
}
| OptimisticOptimizations |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory [MASK] = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this. [MASK] .setShutdownQuietPeriod(Duration.ofMillis(100));
this. [MASK] .afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this. [MASK] .destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this. [MASK] ,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| factory |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache. [MASK] .common.extension.wrapper;
import org.apache. [MASK] .common.extension.ExtensionLoader;
import org.apache. [MASK] .common.extension.wrapper.impl.DemoWrapper;
import org.apache. [MASK] .common.extension.wrapper.impl.DemoWrapper2;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link org.apache. [MASK] .common.extension.Wrapper} Test
*
* @since 2.7.5
*/
public class WrapperTest {
@Test
public void testWrapper() {
Demo demoWrapper = ExtensionLoader.getExtensionLoader(Demo.class).getExtension("demo");
assertTrue(demoWrapper instanceof DemoWrapper);
Demo demoWrapper2 = ExtensionLoader.getExtensionLoader(Demo.class).getExtension("demo2");
assertTrue(demoWrapper2 instanceof DemoWrapper2);
}
}
| dubbo |
/*
* The MIT License
*
* Copyright (c) 2010, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util.jna;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna. [MASK] ;
import com.sun.jna.ptr.IntByReference;
import hudson.Util;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kohsuke Kawaguchi
*/
public class Kernel32Utils {
/**
* Given the process handle, waits for its completion and returns the exit code.
*/
public static int waitForExitProcess(Pointer hProcess) throws InterruptedException {
while (true) {
if (Thread.interrupted())
throw new InterruptedException();
Kernel32.INSTANCE.WaitForSingleObject(hProcess, 1000);
IntByReference exitCode = new IntByReference();
exitCode.setValue(-1);
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode);
int v = exitCode.getValue();
if (v != Kernel32.STILL_ACTIVE) {
return v;
}
}
}
/**
* @deprecated Use {@link java.nio.file.Files#readAttributes} with
* {@link java.nio.file.attribute.DosFileAttributes} and reflective calls to
* WindowsFileAttributes if necessary.
*/
@Deprecated
public static int getWin32FileAttributes(File file) throws IOException {
// allow lookup of paths longer than MAX_PATH
// http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx
String canonicalPath = file.getCanonicalPath();
String path;
if (canonicalPath.length() < 260) {
// path is short, use as-is
path = canonicalPath;
} else if (canonicalPath.startsWith("\\\\")) {
// network share
// \\server\share --> \\?\UNC\server\share
path = "\\\\?\\UNC\\" + canonicalPath.substring(2);
} else {
// prefix, canonical path should be normalized and absolute so this should work.
path = "\\\\?\\" + canonicalPath;
}
return Kernel32.INSTANCE.GetFileAttributesW(new [MASK] (path));
}
/**
* @param target
* If relative, resolved against the location of the symlink.
* If absolute, it's absolute.
* @throws UnsatisfiedLinkError
* If the function is not exported by kernel32.
* See <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinka">CreateSymbolicLinkA function (winbase.h)</a>
* for compatibility info.
* @deprecated Use {@link Util#createSymlink} instead.
*/
@Deprecated
public static void createSymbolicLink(File symlink, String target, boolean dirLink) throws IOException {
if (!Kernel32.INSTANCE.CreateSymbolicLinkW(
new [MASK] (symlink.getPath()), new [MASK] (target),
dirLink ? Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) {
throw new WinIOException("Failed to create a symlink " + symlink + " to " + target);
}
}
/**
* @deprecated Use {@link Util#isSymlink} to detect symbolic links and junctions instead.
*/
@Deprecated
public static boolean isJunctionOrSymlink(File file) throws IOException {
return Util.isSymlink(file);
}
public static File getTempDir() {
Memory buf = new Memory(1024);
if (Kernel32.INSTANCE.GetTempPathW(512, buf) != 0) { // the first arg is number of wchar
return new File(buf.getWideString(0));
} else {
return null;
}
}
/*package*/ static Kernel32 load() {
try {
return (Kernel32) Native.load("kernel32", Kernel32.class);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e);
return InitializationErrorInvocationHandler.create(Kernel32.class, e);
}
}
private static final Logger LOGGER = Logger.getLogger(Kernel32Utils.class.getName());
}
| WString |
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty5.handler.codec.http;
import io.netty5.handler.codec.http.headers.HttpHeaders;
import io.netty5.util.AsciiString;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class HttpHeadersTest {
@Test
public void testRemoveTransferEncodingIgnoreCase() {
HttpMessage [MASK] = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
[MASK] .headers().set(HttpHeaderNames.TRANSFER_ENCODING, "Chunked");
assertFalse( [MASK] .headers().isEmpty());
HttpUtil.setTransferEncodingChunked( [MASK] , false);
assertTrue( [MASK] .headers().isEmpty());
}
// Test for https://github.com/netty/netty/issues/1690
@Test
public void testGetOperations() {
HttpHeaders headers = HttpHeaders.newHeaders();
headers.add("Foo", "1");
headers.add("Foo", "2");
assertEquals("1", headers.get("Foo"));
Iterable<CharSequence> values = headers.values("Foo");
assertThat(values).containsExactly("1", "2");
}
@Test
public void testEqualsIgnoreCase() {
assertTrue(AsciiString.contentEqualsIgnoreCase(null, null));
assertFalse(AsciiString.contentEqualsIgnoreCase(null, "foo"));
assertFalse(AsciiString.contentEqualsIgnoreCase("bar", null));
assertTrue(AsciiString.contentEqualsIgnoreCase("FoO", "fOo"));
}
@Test
public void testSetNullHeaderValueValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(true);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testSetNullHeaderValueNotValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testAddSelf() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(IllegalArgumentException.class, () -> headers.add(headers));
}
@Test
public void testSetSelfIsNoOp() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
headers.add("name", "value");
headers.set(headers);
assertEquals(1, headers.size());
}
}
| message |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes. [MASK] ;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType( [MASK] )
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType( [MASK] )
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType( [MASK] ) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType( [MASK] ) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| VARCHAR |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder. [MASK] ;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), [MASK] ), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), [MASK] ), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), [MASK] ), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), [MASK] ), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), [MASK] ), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), [MASK] ), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), [MASK] ), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), [MASK] ), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| LITTLE_ENDIAN |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function. [MASK] ;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ [MASK] ("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ [MASK] ("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ [MASK] ("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ [MASK] ("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ [MASK] ("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ [MASK] ("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ [MASK] ("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ [MASK] ("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ [MASK] ("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ [MASK] ("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ [MASK] ("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ [MASK] ("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ [MASK] ("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ [MASK] ("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ [MASK] ("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ [MASK] ("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| ScalarFunction |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type. [MASK] .BIGINT;
import static com.facebook.presto.common.type. [MASK] .BOOLEAN;
import static com.facebook.presto.common.type. [MASK] .DOUBLE;
import static com.facebook.presto.common.type. [MASK] .VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| StandardTypes |
package cn.iocoder. [MASK] .module.crm.dal.dataobject.customer;
import cn.iocoder. [MASK] .framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder. [MASK] .module.crm.enums.DictTypeConstants;
import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import java.time.LocalDateTime;
/**
* CRM 客户 DO
*
* @author Wanwan
*/
@TableName(value = "crm_customer")
@KeySequence("crm_customer_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CrmCustomerDO extends BaseDO {
/**
* 编号
*/
@TableId
private Long id;
/**
* 客户名称
*/
private String name;
/**
* 跟进状态
*/
private Boolean followUpStatus;
/**
* 最后跟进时间
*/
private LocalDateTime contactLastTime;
/**
* 最后跟进内容
*/
private String contactLastContent;
/**
* 下次联系时间
*/
private LocalDateTime contactNextTime;
/**
* 负责人的用户编号
*
* 关联 AdminUserDO 的 id 字段
*/
private Long ownerUserId;
/**
* 成为负责人的时间
*/
private LocalDateTime ownerTime;
/**
* 锁定状态
*/
private Boolean lockStatus;
/**
* 成交状态
*/
private Boolean dealStatus;
/**
* 手机
*/
private String mobile;
/**
* 电话
*/
private String telephone;
/**
* QQ
*/
private String qq;
/**
* wechat
*/
private String wechat;
/**
* email
*/
private String email;
/**
* 所在地
*
* 关联 {@link cn.iocoder. [MASK] .framework.ip.core.Area#getId()} 字段
*/
private Integer areaId;
/**
* 详细地址
*/
private String detailAddress;
/**
* 所属行业
*
* 对应字典 {@link DictTypeConstants#CRM_CUSTOMER_INDUSTRY}
*/
private Integer industryId;
/**
* 客户等级
*
* 对应字典 {@link DictTypeConstants#CRM_CUSTOMER_LEVEL}
*/
private Integer level;
/**
* 客户来源
*
* 对应字典 {@link DictTypeConstants#CRM_CUSTOMER_SOURCE}
*/
private Integer source;
/**
* 备注
*/
private String remark;
}
| yudao |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog [MASK] ;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this. [MASK] = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
[MASK] .getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
[MASK] .getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
[MASK] .getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
[MASK] .getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
[MASK] .getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| searchDialog |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address. [MASK] ;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List< [MASK] > searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for ( [MASK] range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| AddressRange |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app. [MASK] .core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app. [MASK] .core.instructionsearch.InstructionSearchPlugin;
import ghidra.app. [MASK] .core.instructionsearch.model.InstructionMetadata;
import ghidra.app. [MASK] .core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param [MASK] the parent [MASK]
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin [MASK] ) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = [MASK] ;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| plugin |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra. [MASK] .model.address.Address;
import ghidra. [MASK] .model.address.AddressRange;
import ghidra. [MASK] .model.listing.*;
import ghidra. [MASK] .util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* [MASK] if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| program |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> [MASK] =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse( [MASK] );
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : [MASK] ) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if ( [MASK] .size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + [MASK] .size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| searchRanges |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core. [MASK] .ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core. [MASK] .InstructionSearchPlugin;
import ghidra.app.plugin.core. [MASK] .model.InstructionMetadata;
import ghidra.app.plugin.core. [MASK] .ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| instructionsearch |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address. [MASK] ;
import ghidra.program.model.address. [MASK] Range;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List< [MASK] Range> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
[MASK] currentAddr = searchPlugin.getProgramLocation().getByte [MASK] ();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for ( [MASK] Range range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMax [MASK] ()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMin [MASK] ()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public [MASK] getNext [MASK] (Direction direction, List<InstructionMetadata> searchResults) {
[MASK] current [MASK] = searchPlugin.getProgramLocation().getByte [MASK] ();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMin [MASK] ().compareTo(current [MASK] ) > 0) {
return cu.getMin [MASK] ();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMin [MASK] ().compareTo(current [MASK] ) < 0) {
return cu.getMin [MASK] ();
}
}
}
return null;
}
private void goToLocation( [MASK] addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| Address |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http. [MASK] ;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode( [MASK] .ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo( [MASK] .CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
[MASK] errorStatus = [MASK] .BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| HttpStatus |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www. [MASK] .org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org. [MASK] .datasketches.common.ArrayOfBooleansSerDe;
import org. [MASK] .datasketches.common.ArrayOfDoublesSerDe;
import org. [MASK] .datasketches.common.ArrayOfLongsSerDe;
import org. [MASK] .datasketches.common.ArrayOfStringsSerDe;
import org. [MASK] .datasketches.kll.KllItemsSketch;
import org. [MASK] .datasketches.memory.Memory;
import org. [MASK] .datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria.INCLUSIVE : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| apache |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.redis;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi.ColumnMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final String name;
private final Type type;
private final String [MASK] ;
private final String comment;
private final String dataFormat;
private final String formatHint;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") String name,
@JsonProperty("type") Type type,
@JsonProperty(" [MASK] ") String [MASK] ,
@JsonProperty("comment") String comment,
@JsonProperty("dataFormat") String dataFormat,
@JsonProperty("formatHint") String formatHint,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this. [MASK] = [MASK] ;
this.comment = comment;
this.dataFormat = dataFormat;
this.formatHint = formatHint;
this.hidden = hidden;
}
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public String getMapping()
{
return [MASK] ;
}
@JsonProperty
public String getComment()
{
return comment;
}
@JsonProperty
public String getDataFormat()
{
return dataFormat;
}
@JsonProperty
public String getFormatHint()
{
return formatHint;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle(String connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
getName(),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
ColumnMetadata getColumnMetadata()
{
return new ColumnMetadata(getName(), getType(), getComment(), isHidden());
}
@Override
public int hashCode()
{
return Objects.hash(name, type, [MASK] , dataFormat, formatHint, hidden);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this. [MASK] , other. [MASK] ) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this.formatHint, other.formatHint) &&
Objects.equals(this.hidden, other.hidden);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("name", name)
.add("type", type)
.add(" [MASK] ", [MASK] )
.add("dataFormat", dataFormat)
.add("formatHint", formatHint)
.add("hidden", hidden)
.toString();
}
}
| mapping |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults. [MASK] ());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr. [MASK] ());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr. [MASK] ());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| getAddr |
/*
* Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.graal.compiler.core.test.backend;
import jdk.graal.compiler.core.GraalCompiler;
import jdk.graal.compiler.core.gen.LIRCompilerBackend;
import jdk.graal.compiler.core.test.GraalCompilerTest;
import jdk.graal.compiler.debug.DebugContext;
import jdk.graal.compiler.lir.gen.LIRGenerationResult;
import jdk.graal.compiler.nodes. [MASK] ;
import jdk.graal.compiler.phases.OptimisticOptimizations;
import jdk.vm.ci.code.Architecture;
public abstract class BackendTest extends GraalCompilerTest {
public BackendTest() {
super();
}
public BackendTest(Class<? extends Architecture> arch) {
super(arch);
}
@SuppressWarnings("try")
protected LIRGenerationResult getLIRGenerationResult(final [MASK] graph, OptimisticOptimizations optimizations) {
DebugContext debug = graph.getDebug();
try (DebugContext.Scope s = debug.scope("FrontEnd")) {
GraalCompiler.emitFrontEnd(getProviders(), getBackend(), graph, getDefaultGraphBuilderSuite(), optimizations, graph.getProfilingInfo(), createSuites(graph.getOptions()));
} catch (Throwable e) {
throw debug.handle(e);
}
LIRGenerationResult lirGen = LIRCompilerBackend.emitLIR(getBackend(), graph, null, null, createLIRSuites(graph.getOptions()), null);
return lirGen;
}
protected LIRGenerationResult getLIRGenerationResult(final [MASK] graph) {
return getLIRGenerationResult(graph, OptimisticOptimizations.NONE);
}
}
| StructuredGraph |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the listing to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address [MASK] = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing listing = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo( [MASK] ) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = listing.getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo( [MASK] ) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| currentAddress |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http. [MASK] ;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept( [MASK] .APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept( [MASK] .APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept( [MASK] .APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| MediaType |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.apache.datasketches.common.ArrayOfBooleansSerDe;
import org.apache.datasketches.common.ArrayOfDoublesSerDe;
import org.apache.datasketches.common.ArrayOfLongsSerDe;
import org.apache.datasketches.common.ArrayOfStringsSerDe;
import org.apache.datasketches.kll.KllItemsSketch;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.quantilescommon.QuantileSearchCriteria;
import static com.facebook.presto.common.type.StandardTypes.BIGINT;
import static com.facebook.presto.common.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.StandardTypes.VARCHAR;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
public class KllSketchFunctions
{
private KllSketchFunctions()
{
}
@ScalarFunction("sketch_kll_quantile")
@Description("Calculates the quantile for a given value with the provided inclusivity. If inclusive is true, the given rank includes all quantiles ≤ the quantile directly corresponding to the given rank. If false, the given rank includes all quantiles < the quantile directly corresponding to the given rank.")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria. [MASK] : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(DOUBLE)
public static double sketchQuantileDouble(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileDouble(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria. [MASK] : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BIGINT)
public static long sketchQuantileBigint(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBigint(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return Slices.utf8Slice(sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria. [MASK] : QuantileSearchCriteria.EXCLUSIVE));
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(VARCHAR)
public static Slice sketchQuantileString(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileString(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getQuantile(rank, inclusive ? QuantileSearchCriteria. [MASK] : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_quantile")
@SqlType(BOOLEAN)
public static boolean sketchQuantileBoolean(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(DOUBLE) double rank)
{
return sketchQuantileBoolean(rawSketch, rank, true);
}
@ScalarFunction("sketch_kll_rank")
@Description("Calculates the rank of a quantile; An estimate of the value which occurs at a particular quantile in the distribution")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Double> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Double::compareTo, new ArrayOfDoublesSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria. [MASK] : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(double)") Slice rawSketch,
@SqlType(DOUBLE) double quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Long> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Long::compareTo, new ArrayOfLongsSerDe());
return sketch.getRank(quantile, inclusive ? QuantileSearchCriteria. [MASK] : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(bigint)") Slice rawSketch,
@SqlType(BIGINT) long quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<String> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), String::compareTo, new ArrayOfStringsSerDe());
return sketch.getRank(rank.toStringUtf8(), inclusive ? QuantileSearchCriteria. [MASK] : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(varchar)") Slice rawSketch,
@SqlType(VARCHAR) Slice quantile)
{
return sketchRank(rawSketch, quantile, true);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean rank,
@SqlType(BOOLEAN) boolean inclusive)
{
KllItemsSketch<Boolean> sketch = KllItemsSketch.wrap(Memory.wrap(rawSketch.toByteBuffer(), LITTLE_ENDIAN), Boolean::compareTo, new ArrayOfBooleansSerDe());
return sketch.getRank(rank, inclusive ? QuantileSearchCriteria. [MASK] : QuantileSearchCriteria.EXCLUSIVE);
}
@ScalarFunction("sketch_kll_rank")
@SqlType(DOUBLE)
public static double sketchRank(
@SqlType("kllsketch(boolean)") Slice rawSketch,
@SqlType(BOOLEAN) boolean quantile)
{
return sketchRank(rawSketch, quantile, true);
}
}
| INCLUSIVE |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.redis;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi. [MASK] ;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final String name;
private final Type type;
private final String mapping;
private final String comment;
private final String dataFormat;
private final String formatHint;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") String name,
@JsonProperty("type") Type type,
@JsonProperty("mapping") String mapping,
@JsonProperty("comment") String comment,
@JsonProperty("dataFormat") String dataFormat,
@JsonProperty("formatHint") String formatHint,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this.mapping = mapping;
this.comment = comment;
this.dataFormat = dataFormat;
this.formatHint = formatHint;
this.hidden = hidden;
}
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public String getMapping()
{
return mapping;
}
@JsonProperty
public String getComment()
{
return comment;
}
@JsonProperty
public String getDataFormat()
{
return dataFormat;
}
@JsonProperty
public String getFormatHint()
{
return formatHint;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle(String connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
getName(),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
[MASK] get [MASK] ()
{
return new [MASK] (getName(), getType(), getComment(), isHidden());
}
@Override
public int hashCode()
{
return Objects.hash(name, type, mapping, dataFormat, formatHint, hidden);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this.mapping, other.mapping) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this.formatHint, other.formatHint) &&
Objects.equals(this.hidden, other.hidden);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("name", name)
.add("type", type)
.add("mapping", mapping)
.add("dataFormat", dataFormat)
.add("formatHint", formatHint)
.add("hidden", hidden)
.toString();
}
}
| ColumnMetadata |
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty5.handler.codec.http;
import io.netty5.handler.codec.http.headers.HttpHeaders;
import io.netty5.util.AsciiString;
import org.junit. [MASK] .api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit. [MASK] .api.Assertions.assertEquals;
import static org.junit. [MASK] .api.Assertions.assertFalse;
import static org.junit. [MASK] .api.Assertions.assertThrows;
import static org.junit. [MASK] .api.Assertions.assertTrue;
public class HttpHeadersTest {
@Test
public void testRemoveTransferEncodingIgnoreCase() {
HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
message.headers().set(HttpHeaderNames.TRANSFER_ENCODING, "Chunked");
assertFalse(message.headers().isEmpty());
HttpUtil.setTransferEncodingChunked(message, false);
assertTrue(message.headers().isEmpty());
}
// Test for https://github.com/netty/netty/issues/1690
@Test
public void testGetOperations() {
HttpHeaders headers = HttpHeaders.newHeaders();
headers.add("Foo", "1");
headers.add("Foo", "2");
assertEquals("1", headers.get("Foo"));
Iterable<CharSequence> values = headers.values("Foo");
assertThat(values).containsExactly("1", "2");
}
@Test
public void testEqualsIgnoreCase() {
assertTrue(AsciiString.contentEqualsIgnoreCase(null, null));
assertFalse(AsciiString.contentEqualsIgnoreCase(null, "foo"));
assertFalse(AsciiString.contentEqualsIgnoreCase("bar", null));
assertTrue(AsciiString.contentEqualsIgnoreCase("FoO", "fOo"));
}
@Test
public void testSetNullHeaderValueValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(true);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testSetNullHeaderValueNotValidate() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(NullPointerException.class, () -> headers.set("test", (CharSequence) null));
}
@Test
public void testAddSelf() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
assertThrows(IllegalArgumentException.class, () -> headers.add(headers));
}
@Test
public void testSetSelfIsNoOp() {
HttpHeaders headers = HttpHeaders.newHeaders(false);
headers.add("name", "value");
headers.set(headers);
assertEquals(1, headers.size());
}
}
| jupiter |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.redis;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi.ColumnMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final String name;
private final Type type;
private final String mapping;
private final String [MASK] ;
private final String dataFormat;
private final String formatHint;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") String name,
@JsonProperty("type") Type type,
@JsonProperty("mapping") String mapping,
@JsonProperty(" [MASK] ") String [MASK] ,
@JsonProperty("dataFormat") String dataFormat,
@JsonProperty("formatHint") String formatHint,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this.mapping = mapping;
this. [MASK] = [MASK] ;
this.dataFormat = dataFormat;
this.formatHint = formatHint;
this.hidden = hidden;
}
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public String getMapping()
{
return mapping;
}
@JsonProperty
public String getComment()
{
return [MASK] ;
}
@JsonProperty
public String getDataFormat()
{
return dataFormat;
}
@JsonProperty
public String getFormatHint()
{
return formatHint;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle(String connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
getName(),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
ColumnMetadata getColumnMetadata()
{
return new ColumnMetadata(getName(), getType(), getComment(), isHidden());
}
@Override
public int hashCode()
{
return Objects.hash(name, type, mapping, dataFormat, formatHint, hidden);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this.mapping, other.mapping) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this.formatHint, other.formatHint) &&
Objects.equals(this.hidden, other.hidden);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("name", name)
.add("type", type)
.add("mapping", mapping)
.add("dataFormat", dataFormat)
.add("formatHint", formatHint)
.add("hidden", hidden)
.toString();
}
}
| comment |
/**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.redisson.liveobject.misc;
import jodd.bean.BeanUtil;
import jodd.bean.BeanUtilBean;
import jodd.bean.BeanVisitor;
import java.util.List;
/**
*
* @author Nikita Koksharov
*
*/
public final class AdvBeanCopy {
private final Object [MASK] ;
private final Object destination;
public AdvBeanCopy(Object [MASK] , Object destination) {
this. [MASK] = [MASK] ;
this.destination = destination;
}
public void copy(List<String> excludedFields) {
BeanUtil beanUtil = new BeanUtilBean();
new BeanVisitor( [MASK] )
.ignoreNulls(true)
.visit((name, value) -> {
if (excludedFields.contains(name)) {
return;
}
beanUtil.setProperty(destination, name, value);
});
}
}
| source |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory [MASK] ) {
super. [MASK] = [MASK] ;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super. [MASK] ).isNotNull();
if (super. [MASK] instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory [MASK] ) {
setUp( [MASK] );
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory [MASK] ) {
setUp( [MASK] );
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory [MASK] ) {
setUp( [MASK] );
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory [MASK] ) {
setUp( [MASK] );
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory [MASK] ) {
setUp( [MASK] );
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory [MASK] ) {
setUp( [MASK] );
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory [MASK] ) {
setUp( [MASK] );
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory [MASK] ) {
setUp( [MASK] );
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono(ClientResponse::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory [MASK] ) {
setUp( [MASK] );
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| bufferFactory |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.instructionsearch.ui;
import java.util.*;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.plugin.core.instructionsearch.InstructionSearchPlugin;
import ghidra.app.plugin.core.instructionsearch.model.InstructionMetadata;
import ghidra.app.plugin.core.instructionsearch.ui.SearchDirectionWidget.Direction;
import ghidra.app.services.GoToService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model. [MASK] .*;
import ghidra.program.util.BytesFieldLocation;
import ghidra.util.Swing;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Task to perform a search from the {@link InstructionSearchDialog}, returning the NEXT or
* PREVIOUS result found, depending on the search direction.
* <p>
* This class searches for a single result within the appropriate search ranges (or the entire
* program if that option is selected). It's optimized to ignore ranges that are "out of scope";
* ie: if searching in the forward direction from a certain address, any ranges prior to that
* address will be ignored.
*
*/
class SearchInstructionsTask extends Task {
private InstructionSearchDialog searchDialog;
private InstructionSearchPlugin searchPlugin;
/**
* Constructor.
*
* @param dialog the parent dialog
* @param plugin the parent plugin
*/
SearchInstructionsTask(InstructionSearchDialog dialog, InstructionSearchPlugin plugin) {
super("Searching Program Text", true, true, false);
this.searchDialog = dialog;
this.searchPlugin = plugin;
}
@Override
public void run(TaskMonitor taskMonitor) {
if (taskMonitor == null) {
return;
}
// First get all the search ranges we have to search.
List<AddressRange> searchRanges =
searchDialog.getControlPanel().getRangeWidget().getSearchRange();
// Get the current cursor location - we'll always start searching from here.
Address currentAddr = searchPlugin.getProgramLocation().getByteAddress();
// See if we're searching forward or backwards.
boolean forward =
searchDialog.getControlPanel()
.getDirectionWidget()
.getSearchDirection()
.equals(
Direction.FORWARD);
// If we're searching backwards we need to process address ranges in reverse so reverse
// the list.
if (!forward) {
Collections.reverse(searchRanges);
}
// Keep track of the range number we're processing, just for display purposes.
int rangeNum = 0;
// Now loop over the ranges, searching each in turn.
for (AddressRange range : searchRanges) {
rangeNum++;
// Now, depending on our current cursor location, we may not have to search all of the
// ranges. ie: if our cursor is beyond the bounds of a range and we're searching in
// the forward direction.
if (forward) {
if (currentAddr.compareTo(range.getMaxAddress()) >= 0) {
continue;
}
}
else {
if (currentAddr.compareTo(range.getMinAddress()) <= 0) {
continue;
}
}
if (searchRanges.size() > 1) {
taskMonitor.setMessage(
"Searching range " + rangeNum + " of " + searchRanges.size());
}
else {
taskMonitor.setMessage("Searching...");
}
// And SEARCH.
InstructionMetadata searchResults =
searchDialog.getSearchData().search(searchPlugin, range, taskMonitor, forward);
// If there are results, move the cursor there, otherwise keep looping and check
// the next range.
//
// Note we put these on the swing thread or it will throw off the task monitor display.
if (searchResults != null) {
Swing.runLater(() -> {
goToLocation(searchResults.getAddr());
searchDialog.getMessagePanel().clear();
});
return;
}
continue;
}
// If we've gone through all the ranges and there are still no results, show an
// error message.
searchDialog.getMessagePanel()
.setMessageText("No results found", Messages.NORMAL);
return;
}
/**
* Moves the cursor in the [MASK] to the next search result past, or before (depending on
* the given direction) the current address.
*
* @param direction the direction to search (forward/backward)
* @param searchResults the list of instructions to search
* @return the address of the next result found
*/
public Address getNextAddress(Direction direction, List<InstructionMetadata> searchResults) {
Address currentAddress = searchPlugin.getProgramLocation().getByteAddress();
// If forward-searching, just find the first address in the given result set that is
// greater than the current address.
//
// The reason for the getting the CodeUnit is that the instruction might be an off-cut,
// and if that's the case, then we can't navigate directly to it. What we have to do
// is find the CodeUnit containing the instruction and navigate to that.
Program currentProgram = searchPlugin.getCurrentProgram();
Listing [MASK] = currentProgram.getListing();
if (direction == Direction.FORWARD) {
for (InstructionMetadata instr : searchResults) {
CodeUnit cu = [MASK] .getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) > 0) {
return cu.getMinAddress();
}
}
}
// If backwards, iterate over the list in reverse order and find the first address in
// the result set that is one less than the current address.
//
// See above for an explanation for why we need to get the CodeUnit in this block.
if (direction == Direction.BACKWARD) {
ListIterator<InstructionMetadata> it = searchResults.listIterator(searchResults.size());
while (it.hasPrevious()) {
InstructionMetadata instr = it.previous();
CodeUnit cu = [MASK] .getCodeUnitContaining(instr.getAddr());
if (cu.getMinAddress().compareTo(currentAddress) < 0) {
return cu.getMinAddress();
}
}
}
return null;
}
private void goToLocation(Address addr) {
GoToService gs = searchPlugin.getTool().getService(GoToService.class);
BytesFieldLocation bloc = new BytesFieldLocation(searchPlugin.getCurrentProgram(), addr);
gs.goTo(bloc);
}
}
| listing |
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.client;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
/**
* WebClient integration tests focusing on data buffer management.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@TestInstance(PER_CLASS)
class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests {
private static final Duration DELAY = Duration.ofSeconds(5);
private final ReactorResourceFactory factory = new ReactorResourceFactory();
private MockWebServer server;
private WebClient webClient;
@BeforeAll
void setUpReactorResourceFactory() {
this.factory.setShutdownQuietPeriod(Duration.ofMillis(100));
this.factory.afterPropertiesSet();
}
@AfterAll
void destroyReactorResourceFactory() {
this.factory.destroy();
}
private void setUp(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory;
this.server = new MockWebServer();
this.webClient = WebClient
.builder()
.clientConnector(initConnector())
.baseUrl(this.server.url("/").toString())
.build();
}
private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator));
}
else {
return new ReactorClientHttpConnector();
}
}
@ParameterizedDataBufferAllocatingTest
void bodyToMonoVoid(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5));
Mono<Void> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest // SPR-17482
void bodyToMonoVoidWithoutContentType(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.ACCEPTED.value())
.setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5));
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(Web [MASK] Exception.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.just(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex));
}
@ParameterizedDataBufferAllocatingTest // SPR-17473
void onStatusWithMonoErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> Mono.error(ex));
}
@ParameterizedDataBufferAllocatingTest
void onStatusWithMonoErrorAndBodyConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex)));
}
@ParameterizedDataBufferAllocatingTest // gh-23230
void onStatusWithImmediateErrorAndBodyNotConsumed(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
RuntimeException ex = new RuntimeException("response error");
testOnStatus(ex, response -> {
throw ex;
});
}
@ParameterizedDataBufferAllocatingTest
void releaseBody(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/plain")
.setBody("foo bar"));
Mono<Void> result = this.webClient.get()
.exchangeToMono( [MASK] ::releaseBody);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(3));
}
@ParameterizedDataBufferAllocatingTest
void exchangeToBodilessEntity(DataBufferFactory bufferFactory) {
setUp(bufferFactory);
this.server.enqueue(new MockResponse()
.setResponseCode(201)
.setHeader("Foo", "bar")
.setBody("foo bar"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.exchangeToMono( [MASK] ::toBodilessEntity);
StepVerifier.create(result)
.assertNext(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(entity.getHeaders().hasHeaderValues("Foo", Collections.singletonList("bar"))).isTrue();
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private void testOnStatus(Throwable expected,
Function< [MASK] , Mono<? extends Throwable>> exceptionFunction) {
HttpStatus errorStatus = HttpStatus.BAD_GATEWAY;
this.server.enqueue(new MockResponse()
.setResponseCode(errorStatus.value())
.setHeader("Content-Type", "application/json")
.setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5));
Mono<String> mono = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status -> status.equals(errorStatus), exceptionFunction)
.bodyToMono(String.class);
StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY);
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
}
| ClientResponse |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.qos.legacy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.qos.legacy.service.DemoService;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
/**
* ChangeTelnetHandlerTest.java
*/
public class ChangeTelnetHandlerTest {
private static TelnetHandler change = new ChangeTelnetHandler();
private Channel mockChannel;
private Invoker<DemoService> [MASK] ;
@AfterAll
public static void tearDown() {
}
@SuppressWarnings("unchecked")
@BeforeEach
public void setUp() {
mockChannel = mock(Channel.class);
[MASK] = mock(Invoker.class);
given(mockChannel.getAttribute("telnet.service")).willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService");
mockChannel.setAttribute("telnet.service", "DemoService");
givenLastCall();
mockChannel.setAttribute("telnet.service", "org.apache.dubbo.rpc.protocol.dubbo.support.DemoService");
givenLastCall();
mockChannel.setAttribute("telnet.service", "demo");
givenLastCall();
mockChannel.removeAttribute("telnet.service");
givenLastCall();
given( [MASK] .getInterface()).willReturn(DemoService.class);
given( [MASK] .getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20884/demo"));
}
private void givenLastCall() {
}
@AfterEach
public void after() {
ProtocolUtils.closeAll();
reset(mockChannel, [MASK] );
}
@Test
public void testChangeSimpleName() throws RemotingException {
DubboProtocol.getDubboProtocol().export( [MASK] );
String result = change.telnet(mockChannel, "DemoService");
assertEquals("Used the DemoService as default.\r\nYou can cancel default service by command: cd /", result);
}
@Test
public void testChangeName() throws RemotingException {
DubboProtocol.getDubboProtocol().export( [MASK] );
String result = change.telnet(mockChannel, "org.apache.dubbo.qos.legacy.service.DemoService");
assertEquals("Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /",
result);
}
@Test
public void testChangePath() throws RemotingException {
DubboProtocol.getDubboProtocol().export( [MASK] );
String result = change.telnet(mockChannel, "demo");
assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result);
}
@Test
public void testChangeMessageNull() throws RemotingException {
String result = change.telnet(mockChannel, null);
assertEquals("Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService", result);
}
@Test
public void testChangeServiceNotExport() throws RemotingException {
String result = change.telnet(mockChannel, "demo");
assertEquals("No such service demo", result);
}
@Test
public void testChangeCancel() throws RemotingException {
String result = change.telnet(mockChannel, "..");
assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result);
}
@Test
public void testChangeCancel2() throws RemotingException {
String result = change.telnet(mockChannel, "/");
assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result);
}
} | mockInvoker |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.redis;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi.ColumnMetadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
/**
* Json description to parse a single field from a Redis key/value row. See {@link RedisTableDescription} for more details.
*/
public final class RedisTableFieldDescription
{
private final String name;
private final Type type;
private final String mapping;
private final String comment;
private final String dataFormat;
private final String formatHint;
private final boolean hidden;
@JsonCreator
public RedisTableFieldDescription(
@JsonProperty("name") String name,
@JsonProperty("type") Type type,
@JsonProperty("mapping") String mapping,
@JsonProperty("comment") String comment,
@JsonProperty("dataFormat") String dataFormat,
@JsonProperty("formatHint") String formatHint,
@JsonProperty("hidden") boolean hidden)
{
checkArgument(!isNullOrEmpty(name), "name is null or is empty");
this.name = name;
this.type = requireNonNull(type, "type is null");
this.mapping = mapping;
this.comment = comment;
this.dataFormat = dataFormat;
this.formatHint = formatHint;
this.hidden = hidden;
}
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public Type getType()
{
return type;
}
@JsonProperty
public String getMapping()
{
return mapping;
}
@JsonProperty
public String getComment()
{
return comment;
}
@JsonProperty
public String getDataFormat()
{
return dataFormat;
}
@JsonProperty
public String getFormatHint()
{
return formatHint;
}
@JsonProperty
public boolean isHidden()
{
return hidden;
}
RedisColumnHandle getColumnHandle(String connectorId, boolean keyDecoder, int index)
{
return new RedisColumnHandle(
connectorId,
index,
getName(),
getType(),
getMapping(),
getDataFormat(),
getFormatHint(),
keyDecoder,
isHidden(),
false);
}
ColumnMetadata getColumnMetadata()
{
return new ColumnMetadata(getName(), getType(), getComment(), isHidden());
}
@ [MASK]
public int hashCode()
{
return Objects.hash(name, type, mapping, dataFormat, formatHint, hidden);
}
@ [MASK]
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RedisTableFieldDescription other = (RedisTableFieldDescription) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.type, other.type) &&
Objects.equals(this.mapping, other.mapping) &&
Objects.equals(this.dataFormat, other.dataFormat) &&
Objects.equals(this.formatHint, other.formatHint) &&
Objects.equals(this.hidden, other.hidden);
}
@ [MASK]
public String toString()
{
return toStringHelper(this)
.add("name", name)
.add("type", type)
.add("mapping", mapping)
.add("dataFormat", dataFormat)
.add("formatHint", formatHint)
.add("hidden", hidden)
.toString();
}
}
| Override |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.pinot;
import com.facebook.presto. [MASK] .ErrorCode;
import com.facebook.presto. [MASK] .ErrorType;
import com.facebook.presto.spi.ErrorCodeSupplier;
import static com.facebook.presto. [MASK] .ErrorType.EXTERNAL;
import static com.facebook.presto. [MASK] .ErrorType.INTERNAL_ERROR;
import static com.facebook.presto. [MASK] .ErrorType.USER_ERROR;
public enum PinotErrorCode
implements ErrorCodeSupplier
{
PINOT_UNSUPPORTED_COLUMN_TYPE(0, EXTERNAL), // schema issues
PINOT_QUERY_GENERATOR_FAILURE(1, INTERNAL_ERROR), // Accepted a query whose sql we couldn't generate
PINOT_INSUFFICIENT_SERVER_RESPONSE(2, EXTERNAL, true), // numServersResponded < numServersQueried
PINOT_EXCEPTION(3, EXTERNAL), // Exception reported by pinot
PINOT_HTTP_ERROR(4, EXTERNAL), // Some non okay http error code
PINOT_UNEXPECTED_RESPONSE(5, EXTERNAL), // Invalid json response with okay http return code
PINOT_UNSUPPORTED_EXPRESSION(6, INTERNAL_ERROR), // Unsupported function
PINOT_UNABLE_TO_FIND_BROKER(7, EXTERNAL),
PINOT_DECODE_ERROR(8, EXTERNAL),
PINOT_INVALID_SQL_GENERATED(9, INTERNAL_ERROR),
PINOT_INVALID_CONFIGURATION(10, INTERNAL_ERROR),
PINOT_DATA_FETCH_EXCEPTION(11, EXTERNAL, true),
PINOT_REQUEST_GENERATOR_FAILURE(12, INTERNAL_ERROR),
PINOT_UNABLE_TO_FIND_INSTANCE(13, EXTERNAL),
PINOT_INVALID_SEGMENT_QUERY_GENERATED(14, INTERNAL_ERROR),
PINOT_PUSH_DOWN_QUERY_NOT_PRESENT(20, USER_ERROR),
PINOT_UNAUTHENTICATED_EXCEPTION(30, USER_ERROR),
PINOT_UNCLASSIFIED_ERROR(100, EXTERNAL);
/**
* Connectors can use error codes starting at the range 0x0100_0000
* See https://github.com/prestodb/presto/wiki/Error-Codes
*
* @see com.facebook.presto.spi.StandardErrorCode
*/
private final ErrorCode errorCode;
private final boolean retriable;
PinotErrorCode(int code, ErrorType type, boolean retriable)
{
errorCode = new ErrorCode(code + 0x0505_0000, name(), type);
this.retriable = retriable;
}
PinotErrorCode(int code, ErrorType type)
{
this(code, type, false);
}
public boolean isRetriable()
{
return retriable;
}
@Override
public ErrorCode toErrorCode()
{
return errorCode;
}
}
| common |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.