method2testcases stringlengths 118 6.63k |
|---|
### Question:
Requests { public static LiveHttpRequest doOnComplete(LiveHttpRequest request, Runnable action) { return request.newBuilder() .body(it -> it.doOnEnd(ifSuccessful(action))) .build(); } private Requests(); static LiveHttpRequest doFinally(LiveHttpRequest request, Consumer<Optional<Throwable>> action); stat... |
### Question:
Requests { public static LiveHttpRequest doOnError(LiveHttpRequest request, Consumer<Throwable> action) { return request.newBuilder() .body(it -> it.doOnEnd(ifError(action))) .build(); } private Requests(); static LiveHttpRequest doFinally(LiveHttpRequest request, Consumer<Optional<Throwable>> action); s... |
### Question:
PluginsMetadata implements Iterable<SpiExtension> { public List<Pair<String, SpiExtension>> activePlugins() { return activePluginsNames.stream() .map(name -> pair(name, plugins.get(name))) .collect(toList()); } PluginsMetadata(@JsonProperty("active") String active,
@JsonProperty("all")... |
### Question:
SlidingWindowHistogram { public synchronized void recordValue(long msValue) { checkArgument(msValue >= 0, "Recorded value must be a positive number."); long currentTime = clock.tickMillis(); purgeOldHistograms(currentTime); int bucket = bucketFromTime(currentTime); window[bucket].recordValue(msValue); las... |
### Question:
SlidingWindowHistogramReservoir implements Reservoir { @Override public synchronized Snapshot getSnapshot() { if (updated || snapshotExpired(clock.tickMillis())) { snapshot = new HistogramSnapshot(histogram); updated = false; snapshotCreationTime = clock.tickMillis(); } return snapshot; } SlidingWindowHis... |
### Question:
CodaHaleMetricRegistry implements MetricRegistry { @Override public Timer timer(String name) { Map<String, Metric> metrics = metricRegistry.getMetrics(); Metric metric = metrics.get(name); if (metric instanceof Timer) { return (Timer) metric; } if (metric == null) { try { return register(name, newTimer())... |
### Question:
Announcer { public static <T extends EventListener> Announcer<T> to(Class<? extends T> listenerType) { return new Announcer<>(listenerType); } Announcer(Class<? extends T> listenerType); static Announcer<T> to(Class<? extends T> listenerType); void addListener(T listener); void removeListener(T listener);... |
### Question:
DocumentFormat { public static Builder newDocument() { return new Builder(); } private DocumentFormat(Builder builder); void validateObject(JsonNode tree); static Builder newDocument(); }### Answer:
@Test public void discriminatedUnionSelectorMustBeString() { Exception e = assertThrows(InvalidSchemaExce... |
### Question:
FileSystemPluginFactoryLoader implements PluginFactoryLoader { @Override public PluginFactory load(SpiExtension spiExtension) { return newPluginFactory(spiExtension); } @Override PluginFactory load(SpiExtension spiExtension); }### Answer:
@Test public void pluginLoaderLoadsPluginFromJarFile() { SpiExten... |
### Question:
Schema { private Schema(Builder builder) { this.fieldNames = builder.fields.stream().map(Field::name).collect(toList()); this.fields = ImmutableList.copyOf(builder.fields); this.optionalFields = ImmutableSet.copyOf(builder.optionalFields); this.constraints = ImmutableList.copyOf(builder.constraints); this... |
### Question:
AtLeastOneFieldPresenceConstraint implements Constraint { @Override public String describe() { return description; } AtLeastOneFieldPresenceConstraint(String... fieldNames); @Override boolean evaluate(Schema schema, JsonNode node); @Override String describe(); }### Answer:
@Test public void describesItsB... |
### Question:
AtLeastOneFieldPresenceConstraint implements Constraint { @Override public boolean evaluate(Schema schema, JsonNode node) { long fieldsPresent = ImmutableList.copyOf(node.fieldNames()) .stream() .filter(fieldNames::contains) .count(); return fieldsPresent >= 1; } AtLeastOneFieldPresenceConstraint(String..... |
### Question:
HttpAggregator implements HttpHandler { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { return request.aggregate(bytes) .flatMap(aggregated -> this.delegate.handle(aggregated, context)) .map(HttpResponse::stream); } HttpAggregator(int bytes, W... |
### Question:
HttpStreamer implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { return delegate.handle(request.stream(), context) .flatMap(live -> live.aggregate(maxContentBytes)); } HttpStreamer(int maxContentBytes, HttpHandler delegate);... |
### Question:
HttpMethodFilteringHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { if (!method.equals(request.method())) { return Eventual.of( HttpResponse.response(METHOD_NOT_ALLOWED) .body(errorBody, StandardCharsets.UTF_8) .b... |
### Question:
FsmEventProcessor implements EventProcessor { @Override public void submit(Object event) { requireNonNull(event); try { stateMachine.handle(event, loggingPrefix); } catch (Throwable cause) { String eventName = event.getClass().getSimpleName(); LOGGER.error("{} {} -> ???: Exception occurred while processin... |
### Question:
FileResourceIndex implements ResourceIndex { @Override public Iterable<Resource> list(String path, String suffix) { ArrayList<Resource> list = new ArrayList<>(); new FileResourceIterator(new File(path), new File(path), suffix).forEachRemaining(list::add); return list; } @Override Iterable<Resource> list(... |
### Question:
ClasspathResourceIndex implements ResourceIndex { @Override public Iterable<Resource> list(String path, String suffix) { String classpath = path.replace("classpath:", ""); ResourceIteratorFactory resourceIteratorFactory = new DelegatingResourceIteratorFactory(); try { Enumeration<URL> resources = classLoa... |
### Question:
FileResource implements Resource { @Override public InputStream inputStream() throws IOException { return new FileInputStream(file); } FileResource(File file); FileResource(File root, File file); FileResource(String path); @Override String path(); @Override URL url(); @Override String absolutePath(); @O... |
### Question:
ClasspathResource implements Resource { @Override public URL url() { URL url = this.classLoader.getResource(this.path); if (url == null) { throw new RuntimeException(new FileNotFoundException(this.path)); } return url; } ClasspathResource(String path, Class<?> clazz); ClasspathResource(String path, Class... |
### Question:
ClasspathResource implements Resource { @Override public InputStream inputStream() throws FileNotFoundException { InputStream stream = classLoader.getResourceAsStream(this.path); if (stream == null) { throw new FileNotFoundException(CLASSPATH_SCHEME + path); } return stream; } ClasspathResource(String pat... |
### Question:
ResourceFactory { public static Resource newResource(String path, ClassLoader classLoader) { if (path.startsWith(CLASSPATH_SCHEME)) { return new ClasspathResource(path, classLoader); } return new FileResource(path); } static Resource newResource(String path, ClassLoader classLoader); static Resource newR... |
### Question:
ClassFactories { public static <T> T newInstance(String className, Class<T> type) { try { Object instance = classForName(className).newInstance(); return type.cast(instance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(format("No such class '%s'", className)); } catch (Instanti... |
### Question:
Preconditions { public static String checkNotEmpty(String value) { if (value == null || value.length() == 0) { throw new IllegalArgumentException(); } return value; } private Preconditions(); static String checkNotEmpty(String value); static T checkArgument(T reference, boolean expression); static void c... |
### Question:
Preconditions { public static <T> T checkArgument(T reference, boolean expression) { if (!expression) { throw new IllegalArgumentException(); } return reference; } private Preconditions(); static String checkNotEmpty(String value); static T checkArgument(T reference, boolean expression); static void chec... |
### Question:
QueueDrainingEventProcessor implements EventProcessor { @Override public void submit(Object event) { events.add(event); if (eventCount.getAndIncrement() == 0) { do { Object e = events.poll(); try { eventProcessor.submit(e); } catch (RuntimeException cause) { if (logErrors) { LOGGER.warn("Event {} threw an... |
### Question:
SanitisedHttpMessageFormatter implements HttpMessageFormatter { @Override public String formatRequest(HttpRequest request) { return request == null ? NULL : formatRequest( request.version(), request.method(), request.url(), request.id(), request.headers()); } SanitisedHttpMessageFormatter(SanitisedHttpHea... |
### Question:
SanitisedHttpMessageFormatter implements HttpMessageFormatter { @Override public String formatResponse(HttpResponse response) { return response == null ? NULL : formatResponse( response.version(), response.status(), response.headers()); } SanitisedHttpMessageFormatter(SanitisedHttpHeaderFormatter sanitise... |
### Question:
SanitisedHttpHeaderFormatter { public String format(HttpHeaders headers) { return StreamSupport.stream(headers.spliterator(), false) .map(this::hideOrFormatHeader) .collect(joining(", ")); } SanitisedHttpHeaderFormatter(List<String> headersToHide, List<String> cookiesToHide); List<String> cookiesToHide();... |
### Question:
StateMachine { public S currentState() { return currentState; } private StateMachine(S initialState, Map<Key<S>, Function<Object, S>> transitions,
BiFunction<S, Object, S> inappropriateEventHandler, StateChangeListener<S> stateChangeListener); S currentState(); void handle(Object event, Strin... |
### Question:
FlowControllingHttpContentProducer { public void newChunk(ByteBuf content) { stateMachine.handle(new ContentChunkEvent(content)); } FlowControllingHttpContentProducer(
Runnable askForMore,
Runnable onCompleteAction,
Consumer<Throwable> onTerminateAction,
Str... |
### Question:
Logging { public static String sanitise(String input) { return input.replaceAll("\\n", "\\\\n"); } private Logging(); static String sanitise(String input); }### Answer:
@Test public void sanitiseRemovesNewlines() throws Exception { assertThat(Logging.sanitise("first line\nsecond line"), is("first line\\... |
### Question:
ConfigurableUnwiseCharsEncoder implements UnwiseCharsEncoder { @Override public String encode(String value) { String escaped = escaper.escape(value); if (!Objects.equals(escaped, value)) { logger.warn("Value contains unwise chars. you should fix this. raw={}, escaped={}: ", value, escaped); } return escap... |
### Question:
FunctionResolver { PartialFunction resolveFunction(String name, List<String> arguments) { int argumentSize = arguments.size(); String argumentsRepresentation = join(", ", arguments); switch (argumentSize) { case 0: Function0 function0 = ensureNotNull( zeroArgumentFunctions.get(name), "No such function=[%s... |
### Question:
NettyToStyxRequestDecoder extends MessageToMessageDecoder<HttpObject> { @Override protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception { if (msg.getDecoderResult().isFailure()) { String formattedHttpObject = httpMessageFormatter.formatNettyMessage(msg); throw... |
### Question:
NettyToStyxRequestDecoder extends MessageToMessageDecoder<HttpObject> { @VisibleForTesting LiveHttpRequest.Builder makeAStyxRequestFrom(HttpRequest request, Publisher<Buffer> content) { Url url = UrlDecoder.decodeUrl(unwiseCharEncoder, request); LiveHttpRequest.Builder requestBuilder = new LiveHttpRequest... |
### Question:
UrlDecoder { static Url decodeUrl(UnwiseCharsEncoder unwiseCharEncoder, HttpRequest request) { String host = request.headers().get(HOST); if (request.uri().startsWith("/") && host != null) { URI uri = URI.create("http: return new Url.Builder() .path(uri.getRawPath()) .rawQuery(uri.getRawQuery()) .fragment... |
### Question:
ChannelStatisticsHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { receivedBytesCount.inc(((ByteBuf) msg).readableBytes()); } else if (msg instanceof ByteBufHolder) { receivedBytesCount.inc(((Byt... |
### Question:
ChannelStatisticsHandler extends ChannelDuplexHandler { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof ByteBuf) { sentBytesCount.inc(((ByteBuf) msg).readableBytes()); } else if (msg instanceof ByteBufHolder) { sentBytesCount... |
### Question:
HttpPipelineHandler extends SimpleChannelInboundHandler<LiveHttpRequest> { private static HttpResponseStatus status(Throwable exception) { return EXCEPTION_STATUSES.statusFor(exception) .orElseGet(() -> { if (exception instanceof DecoderException) { Throwable cause = exception.getCause(); if (cause instan... |
### Question:
HttpPipelineHandler extends SimpleChannelInboundHandler<LiveHttpRequest> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { eventProcessor.submit(new ChannelExceptionEvent(ctx, cause)); } private HttpPipelineHandler(Builder builder, RequestTracker tracker); @Override vo... |
### Question:
HttpPipelineHandler extends SimpleChannelInboundHandler<LiveHttpRequest> { @VisibleForTesting State state() { return this.stateMachine.currentState(); } private HttpPipelineHandler(Builder builder, RequestTracker tracker); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelIna... |
### Question:
StyxToNettyResponseTranslator implements ResponseTranslator { public HttpResponse toNettyResponse(LiveHttpResponse httpResponse) { io.netty.handler.codec.http.HttpVersion version = toNettyVersion(httpResponse.version()); HttpResponseStatus httpResponseStatus = HttpResponseStatus.valueOf(httpResponse.statu... |
### Question:
ExceptionStatusMapper { Optional<HttpResponseStatus> statusFor(Throwable throwable) { List<HttpResponseStatus> matchingStatuses = this.multimap.entries().stream() .filter(entry -> entry.getValue().isInstance(throwable)) .sorted(comparing(entry -> entry.getKey().code())) .map(Map.Entry::getKey) .collect(to... |
### Question:
StaticFileHandler implements HttpHandler { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { try { return resolveFile(request.path()) .map(ResolvedFile::new) .map(resolvedFile -> HttpResponse.response() .addHeader(CONTENT_TYPE, resolvedFile.medi... |
### Question:
CurrentRequestTracker implements RequestTracker { public void trackRequest(LiveHttpRequest request, Supplier<String> state) { if (currentRequests.containsKey(request.id())) { currentRequests.get(request.id()).setCurrentThread(Thread.currentThread()); } else { currentRequests.put(request.id(), new CurrentR... |
### Question:
CurrentRequestTracker implements RequestTracker { public void endTrack(LiveHttpRequest request) { currentRequests.remove(request.id()); } void trackRequest(LiveHttpRequest request, Supplier<String> state); void trackRequest(LiveHttpRequest request); void markRequestAsSent(LiveHttpRequest request); void e... |
### Question:
RequestStatsCollector implements RequestProgressListener { @Override public void onRequest(Object requestId) { Long previous = this.ongoingRequests.putIfAbsent(requestId, nanoClock.nanoTime()); if (previous == null) { this.outstandingRequests.inc(); this.requestsIncoming.mark(); } } RequestStatsCollector(... |
### Question:
PathTrie { public void put(String path, T value) { checkNotEmpty(path); requireNonNull(value); List<String> components = pathToComponents(Paths.get(removeAsterisk(path))); if (path.endsWith("/") || path.endsWith("/*")) { components.add("/"); } T existing = tree.getExactMatch(components); if (existing != n... |
### Question:
CompositeHttpErrorStatusListener implements HttpErrorStatusListener { @Override public void proxyErrorOccurred(Throwable cause) { listeners.forEach(listener -> listener.proxyErrorOccurred(cause)); } CompositeHttpErrorStatusListener(List<HttpErrorStatusListener> listeners); @Override void proxyErrorOccurre... |
### Question:
CompositeHttpErrorStatusListener implements HttpErrorStatusListener { @Override public void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause) { listeners.forEach(listener -> listener.proxyWriteFailure(request, response, cause)); } CompositeHttpErrorStatusListener(List<... |
### Question:
CompositeHttpErrorStatusListener implements HttpErrorStatusListener { @Override public void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause) { listeners.forEach(listener -> listener.proxyingFailure(request, response, cause)); } CompositeHttpErrorStatusListener(List<Http... |
### Question:
AggregateRequestBodyExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return request.aggregate(10000) .map(fullRequest -> { String body = fullRequest.bodyAs(UTF_8); return fullRequest.newBuilder() .body(body + config.extraText()... |
### Question:
ReplaceLiveContentExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(request) .map(response -> response.newBuilder() .body(body -> body.replaceWith(ByteStream.from(config.replacement(), UTF_8))) .build()); } ... |
### Question:
ModifyHeadersExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { LiveHttpRequest newRequest = request.newBuilder() .header("myRequestHeader", config.requestHeaderValue()) .build(); return chain.proceed(newRequest).map(response -> ... |
### Question:
ModifyContentByAggregationExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(request) .flatMap(response -> response.aggregate(10000)) .map(response -> { String body = response.bodyAs(UTF_8); return response.n... |
### Question:
EarlyReturnExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { if (request.header("X-Respond").isPresent()) { return Eventual.of(HttpResponse.response(OK) .header(CONTENT_TYPE, "text/plain; charset=utf-8") .body("Responding from p... |
### Question:
HttpErrorStatusCauseLogger implements HttpErrorStatusListener { @Override public void proxyErrorOccurred(HttpResponseStatus status, Throwable cause) { if (status.code() > 500) { LOG.error("Failure status=\"{}\", exception=\"{}\"", status, withoutStackTrace(cause)); } else { LOG.error("Failure status=\"{}\... |
### Question:
InterceptorPipelineBuilder { public RoutingObject build() { List<HttpInterceptor> interceptors = ImmutableList.copyOf(instrument(plugins, environment)); return new HttpInterceptorPipeline(interceptors, handler, trackRequests); } InterceptorPipelineBuilder(Environment environment, Iterable<NamedPlugin> plu... |
### Question:
HttpErrorStatusMetrics implements HttpErrorStatusListener { @Override public void proxyErrorOccurred(HttpResponseStatus status, Throwable cause) { record(status); if (isError(status)) { incrementExceptionCounter(cause, status); } } HttpErrorStatusMetrics(MetricRegistry metricRegistry); @Override void prox... |
### Question:
ViaHeaderAppendingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { LiveHttpRequest newRequest = request.newBuilder() .header(VIA, viaHeader(request)) .build(); return chain.proceed(newRequest) .map(response -> response.n... |
### Question:
RequestEnrichingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(enrich(request, chain.context())); } RequestEnrichingInterceptor(StyxHeaderConfig styxHeaderConfig); @Override Eventual<LiveHttpRespon... |
### Question:
HttpMessageLoggingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { boolean secure = chain.context().isSecure(); logger.logRequest(request, null, secure); return chain.proceed(request).map(response -> { logger.logResponse... |
### Question:
ConfigurationContextResolverInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { Configuration.Context context = configurationContextResolver.resolve(request); chain.context().add("config.context", context); return chain.pro... |
### Question:
HopByHopHeadersRemovingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(removeHopByHopHeaders(request)) .map(HopByHopHeadersRemovingInterceptor::removeHopByHopHeaders); } @Override Eventual<LiveHttp... |
### Question:
FileBackedBackendServicesRegistry extends AbstractStyxService implements Registry<BackendService>, FileChangeMonitor.Listener { @Override public CompletableFuture<ReloadResult> reload() { return this.fileBackedRegistry.reload() .thenApply(outcome -> logReloadAttempt("Admin Interface", outcome)); } @Visibl... |
### Question:
FileBackedBackendServicesRegistry extends AbstractStyxService implements Registry<BackendService>, FileChangeMonitor.Listener { @Override public Registry<BackendService> addListener(ChangeListener<BackendService> changeListener) { return this.fileBackedRegistry.addListener(changeListener); } @VisibleForTe... |
### Question:
FileBackedBackendServicesRegistry extends AbstractStyxService implements Registry<BackendService>, FileChangeMonitor.Listener { @Override public Iterable<BackendService> get() { return this.fileBackedRegistry.get(); } @VisibleForTesting FileBackedBackendServicesRegistry(FileBackedRegistry<BackendService>... |
### Question:
FileChangeMonitor implements FileMonitor { @Override public void start(Listener listener) { LOGGER.debug("start, initialDelay={}, pollPeriod={}", new Object[] {initialDelay, pollPeriod}); synchronized (this) { if (monitoredTask != null) { String message = format("File monitor for '%s' is already started",... |
### Question:
HealthCheckTimestamp extends HealthCheck { @Override protected Result check() { ZonedDateTime now = Instant.ofEpochMilli(clock.tickMillis()).atZone(UTC); return healthy(DATE_TIME_FORMATTER.format(now)); } HealthCheckTimestamp(); HealthCheckTimestamp(Clock clock); static final String NAME; }### Answer:
@... |
### Question:
PathPrefixRouter implements RoutingObject { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { String path = request.path(); for (PrefixRoute route : routes) { if (path.startsWith(route.prefix)) { return route.routingObject.handle(request, contex... |
### Question:
StandardHttpPipeline implements HttpHandler { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { HttpInterceptorChain interceptorsChain = new HttpInterceptorChain(interceptors, 0, handler, context, requestTracker); return interceptorsChain.procee... |
### Question:
StyxServerComponents { public List<NamedPlugin> plugins() { return plugins; } private StyxServerComponents(Builder builder); boolean showBanner(); Environment environment(); Map<String, StyxService> services(); List<NamedPlugin> plugins(); StyxObjectStore<RoutingObjectRecord> routeDatabase(); StyxObjectS... |
### Question:
StyxServerComponents { public Map<String, StyxService> services() { return services; } private StyxServerComponents(Builder builder); boolean showBanner(); Environment environment(); Map<String, StyxService> services(); List<NamedPlugin> plugins(); StyxObjectStore<RoutingObjectRecord> routeDatabase(); St... |
### Question:
StyxServerComponents { public Environment environment() { return environment; } private StyxServerComponents(Builder builder); boolean showBanner(); Environment environment(); Map<String, StyxService> services(); List<NamedPlugin> plugins(); StyxObjectStore<RoutingObjectRecord> routeDatabase(); StyxObjec... |
### Question:
CoreMetrics { public static void registerCoreMetrics(Version buildInfo, MetricRegistry metrics) { registerVersionMetric(buildInfo, metrics); registerJvmMetrics(metrics); metrics.register("os", new OperatingSystemMetricSet()); } private CoreMetrics(); static void registerCoreMetrics(Version buildInfo, Met... |
### Question:
WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiv... |
### Question:
ProcessStartedEventConverter extends BaseEventToEntityConverter { @Override protected ProcessStartedAuditEventEntity createEventEntity(CloudRuntimeEvent cloudRuntimeEvent) { return new ProcessStartedAuditEventEntity((CloudProcessStartedEvent) cloudRuntimeEvent); } ProcessStartedEventConverter(EventContext... |
### Question:
ProcessStartedEventConverter extends BaseEventToEntityConverter { @Override protected CloudRuntimeEventImpl<?, ?> createAPIEvent(AuditEventEntity auditEventEntity) { ProcessStartedAuditEventEntity processStartedAuditEventEntity = (ProcessStartedAuditEventEntity) auditEventEntity; return new CloudProcessSt... |
### Question:
AuditConsumerChannelHandlerImpl implements AuditConsumerChannelHandler { @SuppressWarnings("unchecked") @Override @StreamListener(AuditConsumerChannels.AUDIT_CONSUMER) public void receiveCloudRuntimeEvent(@Headers Map<String, Object> headers, CloudRuntimeEvent<?, ?>... events) { if (events != null) { Atom... |
### Question:
MemCacheTemplate implements CacheAble<T> { @Override public T get(String key) { T value = null; MemcacheClient oneL1 = null; if (masterL1List != null && masterL1List.size() > 0) { oneL1 = chooseOneL1Client(); if (oneL1 != null) { value = get(key, oneL1); } } if (value == null) { value = get(key, master); ... |
### Question:
ApacheHttpClient implements ApiHttpClient { public String getAsync(final String url){ return getAsync(url, soTimeOut); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int max... |
### Question:
ApacheHttpClient implements ApiHttpClient { public RequestBuilder buildGet(String url){ HttpMethod get=new GetMethod(url); HttpClientRequestBuilder ret=new HttpClientRequestBuilder(url,get,HttpManager.isBlockResource(url)); return ret; } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTime... |
### Question:
ApacheHttpClient implements ApiHttpClient { public RequestBuilder buildPost(String url){ PostMethod post = new PostMethod(url); HttpClientRequestBuilder ret=new HttpClientRequestBuilder(url,post,HttpManager.isBlockResource(url)); return ret; } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int c... |
### Question:
ApacheHttpClient implements ApiHttpClient { public String postMulti(String url, Map<String, Object> nameValues){ return postMulti(url,nameValues,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost... |
### Question:
McqBaseManager { public static String status() { StringBuilder sb = new StringBuilder(512); sb.append("\r\nreading_mcq(yangwm,true):\t"); sb.append(IS_ALL_READ.get()); return sb.toString(); } static void stopReadAll(); static void startReadAll(); static String status(); static AtomicBoolean IS_ALL_READ; ... |
### Question:
ShardingUtil { public static<T> Map<Integer, T> parseClients(Map<String, T> clientsConfig){ Map<Integer, T> shardingClients = new HashMap<Integer, T>(); for(Map.Entry<String, T> entry : clientsConfig.entrySet()){ List<Integer> dbIdxs = parseDbIdx(entry.getKey()); T client = entry.getValue(); for(Integer d... |
### Question:
PageWrapperUtil { public static <T> String toJson(PageWrapper<T> pageWrapper, String name, long[] values) { JsonBuilder json = new JsonBuilder(); if (values == null) { json.append(name, "[]"); } else { json.appendStrArr(name, values); } appendJson(json, pageWrapper); json.flip(); return json.toString(); }... |
### Question:
PageWrapperUtil { public static PageWrapper<long[]> wrap(long[] ids, int count) { PageWrapper<long[]> wrapper = new PageWrapper<long[]>(0, 0, ids); wrapper.totalNumber = ids.length; if (ids.length > 1) { wrapper.nextCursor = ids[ids.length - 1] + MAX_ID_ADJECT; } wrapper.result = Arrays.copyOf(ids, Math.m... |
### Question:
DaoUtil { public static String createMutiGetSql(String sql, int paramsSize){ StringBuilder sqlBuf = new StringBuilder().append(sql).append("( ?"); for(int i = 1; i < paramsSize; i++){ sqlBuf.append(", ?"); } return sqlBuf.append(")").toString(); } static String createMutiGetEncodedSql(String sql, int par... |
### Question:
DaoUtil { public static String createMultiInsertSql(String sqlPrefix, String sqlSuffix, int valuesSize) { StringBuilder sb = new StringBuilder(sqlPrefix).append(sqlSuffix); for (int i = 1; i < valuesSize; i++) { sb.append(", "); sb.append(sqlSuffix); } return sb.toString(); } static String createMutiGetE... |
### Question:
MemCacheTemplate implements CacheAble<T> { @Override public Map<String, T> getMulti(String[] keys) { Map<String, T> values = new HashMap<String, T>(); MemcacheClient oneL1 = null; if (masterL1List != null && masterL1List.size() > 0) { oneL1 = chooseOneL1Client(); if (oneL1 != null) { values = getMulti(key... |
### Question:
DaoUtil { public static String expendMultiGetSql(String sql, Object[] params) { int lastQuoteIndex = -1; for (int i = 0; i < params.length; i++) { lastQuoteIndex = sql.indexOf('?', lastQuoteIndex + 1); Object param = params[i]; if (param instanceof Object[]) { Object[] nestArrayParam = (Object[]) param; S... |
### Question:
IdCreator implements IdCreate { public long generateId(int bizFlagValue){ return getNextId(bizFlagValue); } long generateId(int bizFlagValue); NaiveMemcacheClient getIdGenerateClient(); void setIdGenerateClient(NaiveMemcacheClient idGenerateClient); }### Answer:
@Test public void testGenerateIdForUuid()... |
### Question:
WebExceptionFormat { public static String formatException(WebApiException e, String path, String type) { if (path == null) { throw new IllegalArgumentException(" path argument is null"); } ExcepFactor factor = e.getFactor(); if (type == null) { } String result; if ("xml".equals(type)) { result = String.fo... |
### Question:
TopN { public static long[] top(Collection<? extends VectorInterface> vectorItems, int n) { VectorInterface[] vectors = getVectors(vectorItems); return top(vectors, n); } static long[] top(Collection<? extends VectorInterface> vectorItems, int n); }### Answer:
@Test public void testTopN() { Map<String, ... |
### Question:
TopNObject { public static Object[] top(Collection<? extends VectorInterface> vectorItems, int n) { return top(vectorItems, n, CommonConst.EMPTY_OBJECT_ARRAY); } static Object[] top(Collection<? extends VectorInterface> vectorItems, int n); static Object[] top(Collection<? extends VectorInterface> vector... |
### Question:
JsonUtil { public static String toJsonStr(String value) { if (value == null) return null; StringBuilder buf = new StringBuilder(value.length()); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); switch(c) { case '"': buf.append("\\\""); break; case '\\': buf.append("\\\\"); break; case ... |
### Question:
JsonUtil { public static boolean isValidJsonObject(String json){ return isValidJsonObject(json, false); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); ... |
### Question:
JsonUtil { public static boolean isValidJsonArray(String json){ return isValidJsonArray(json, false); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.