org.eclipse.jetty.util.Callback Java Examples

The following examples show how to use org.eclipse.jetty.util.Callback. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RulesControllerTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Test(timeout = 5000)
@Category({UnitTest.class})
public void provideRuleById() {

    // Arrange
    CompletionStage<RuleServiceModel> ruleResult =
        Callback.Completable.completedFuture(null);

    IRules rules = mock(IRules.class);
    RulesController controller = new RulesController(rules);
    when(rules.getAsync("1")).thenReturn(ruleResult);

    // Act
    controller.getAsync("1").thenApply(response -> {
        // Assert
        assertThat(response.body().isKnownEmpty(), is(false));
        return null;
    });
}
 
Example #2
Source File: RulesControllerTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Test(timeout = 5000)
@Category({UnitTest.class})
public void deleteRule() {

    // Arrange
    CompletionStage<Boolean> result =
        Callback.Completable.completedFuture(null);

    IRules rules = mock(IRules.class);
    RulesController controller = new RulesController(rules);
    when(rules.deleteAsync("1")).thenReturn(result);

    // Act
    controller.deleteAsync("1").thenApply(response -> {
        // Assert
        assertThat(response.body().isKnownEmpty(), is(false));
        return null;
    });
}
 
Example #3
Source File: ReverseProxyServlet.java    From logbook with MIT License 6 votes vote down vote up
@Override
protected void onResponseContent(HttpServletRequest request, HttpServletResponse response, Response proxyResponse,
        byte[] buffer, int offset, int length, Callback callback) {
    // フィルタークラスで必要かどうかを判別後、必要であれば内容をキャプチャする
    // 注意: 1回のリクエストで複数回の応答が帰ってくるので全ての応答をキャプチャする必要がある
    if (Filter.isNeed(request.getServerName(), response.getContentType())) {
        ByteArrayOutputStream stream = (ByteArrayOutputStream) request.getAttribute(Filter.RESPONSE_BODY);
        if (stream == null) {
            stream = new ByteArrayOutputStream();
            request.setAttribute(Filter.RESPONSE_BODY, stream);
        }
        // ストリームに書き込む
        stream.write(buffer, offset, length);
    }
    super.onResponseContent(request, response, proxyResponse, buffer, offset, length, callback);
}
 
Example #4
Source File: StreamEchoProcessor.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
    LOG.info("onData {}", stream.getId());
    try {
        boolean endStream = frame.isEndStream();
        byte[] bytes = new byte[frame.getData().remaining()];
        frame.getData().get(bytes);
        EchoMessage echoMessage = objectMapper.readValue(bytes, EchoMessage.class);
        LOG.info("got echo {}", echoMessage.getMessage());
        String response = echoService.ping(echoMessage.getMessage());
        EchoMessage echoResponse = new EchoMessage(response);
        LOG.info("echo response {}", echoResponse.getMessage());
        DataFrame responseFrame = new DataFrame(stream.getId(),
                ByteBuffer.wrap(objectMapper.writeValueAsBytes(echoResponse)), endStream);
        stream.data(responseFrame, new Callback() {});
        callback.succeeded();
        LOG.info("echo done");
    } catch (IOException e) {
        LOG.error("IOException: ", e);
    }
}
 
Example #5
Source File: SystemInfoServiceClient.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Override
public SystemInfo getSystemInfo() {
    try {
        Session session = createSession();
        HttpFields requestFields = new HttpFields();
        requestFields.put(USER_AGENT, USER_AGENT_VERSION);
        MetaData.Request request = new MetaData.Request("GET", getSystemInfoURI, HttpVersion.HTTP_2, requestFields);
        HeadersFrame headersFrame = new HeadersFrame(request, null, true);
        GetListener getListener = new GetListener();
        session.newStream(headersFrame, new FuturePromise<>(), getListener);
        SystemInfo response = getListener.get(SystemInfo.class);
        session.close(0, null, new Callback() {});
        return response;
    } catch (Exception e) {
        throw new HttpAccessException(e);
    }
}
 
Example #6
Source File: JettyClientHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
private ContentChunk toContentChunk(DataBuffer buffer) {
	return new ContentChunk(buffer.asByteBuffer(), new Callback() {
		@Override
		public void succeeded() {
			DataBufferUtils.release(buffer);
		}

		@Override
		public void failed(Throwable x) {
			DataBufferUtils.release(buffer);
			throw Exceptions.propagate(x);
		}
	});
}
 
Example #7
Source File: CommandProxyServlet.java    From Scribengin with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onContent(final Response proxyResponse, ByteBuffer content, final Callback callback){
    byte[] buffer;
    int offset;
    int length = content.remaining();
    if (content.hasArray())
    {
        buffer = content.array();
        offset = content.arrayOffset();
    }
    else
    {
        buffer = new byte[length];
        content.get(buffer);
        offset = 0;
    }

    onResponseContent(request, response, proxyResponse, buffer, offset, length, new Callback(){
        @Override
        public void succeeded()
        {
            callback.succeeded();
        }

        @Override
        public void failed(Throwable x)
        {
            callback.failed(x);
            proxyResponse.abort(x);
        }
    });
}
 
Example #8
Source File: JettyService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void send(@Nullable MetaData.Response info, boolean head,
                 ByteBuffer content, boolean lastContent, Callback callback) {

    if (info != null) {
        this.info = info;
    }

    final int length = content.remaining();
    if (length == 0) {
        callback.succeeded();
        return;
    }

    if (content.hasArray()) {
        final int from = content.arrayOffset() + content.position();
        out.add(HttpData.wrap(Arrays.copyOfRange(content.array(), from, from + length)));
        content.position(content.position() + length);
    } else {
        final byte[] data = new byte[length];
        content.get(data);
        out.add(HttpData.wrap(data));
    }

    contentLength += length;
    callback.succeeded();
}
 
Example #9
Source File: CustomSessionListener.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void onReset(Stream stream, ResetFrame frame) {
    LOG.info("onReset");
    ErrorCode error = ErrorCode.from(frame.getError());
    if (error == null) {
        error = ErrorCode.CANCEL_STREAM_ERROR;
    }
    getConnection().onStreamFailure((IStream)stream, new EofException("HTTP/2 " + error), Callback.NOOP);
}
 
Example #10
Source File: CustomSessionListener.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void onClose(Session session, GoAwayFrame frame, Callback callback) {
    LOG.info("onClose");
    ErrorCode error = ErrorCode.from(frame.getError());
    if (error == null) {
        error = ErrorCode.STREAM_CLOSED_ERROR;
    }
    String reason = frame.tryConvertPayload();
    if (reason != null && !reason.isEmpty()) {
        reason = " (" + reason + ")";
    }
    getConnection().onSessionFailure(new EofException("HTTP/2 " + error + reason), callback);
}
 
Example #11
Source File: JettyClientHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private ContentChunk toContentChunk(DataBuffer buffer) {
	return new ContentChunk(buffer.asByteBuffer(), new Callback() {
		@Override
		public void succeeded() {
			DataBufferUtils.release(buffer);
		}

		@Override
		public void failed(Throwable x) {
			DataBufferUtils.release(buffer);
			throw Exceptions.propagate(x);
		}
	});
}
 
Example #12
Source File: GetListener.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
    LOG.info("onData");
    bytes = new byte[frame.getData().remaining()];
    frame.getData().get(bytes);
    countDownLatch.countDown();
    callback.succeeded();
}
 
Example #13
Source File: RulesControllerTest.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Test(timeout = 5000)
@Category({UnitTest.class})
public void provideRulesList() {

    // Arrange
    CompletionStage<List<RuleServiceModel>> ruleListResult =
        Callback.Completable.completedFuture(null);

    IRules rules = mock(IRules.class);
    RulesController controller = new RulesController(rules);
    when(rules.getListAsync(
        "asc",
        0,
        1000,
        null,
        false))
        .thenReturn(ruleListResult);

    // Act
    controller.listAsync(
        "asc",
        0,
        1000,
        null,
        false)
        .thenApply(response -> {
            // Assert
            assertThat(response.body().isKnownEmpty(), is(false));
            return null;
        });
}
 
Example #14
Source File: RulesControllerTest.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Test(timeout = 5000)
@Category({UnitTest.class})
public void itPostNewRuleWithNoEtagResultHasAllFields() throws Exception {
    CompletionStage<RuleServiceModel> ruleResult =
        Callback.Completable.completedFuture(null);

    IRules rules = mock(IRules.class);

    RulesController controller = new RulesController(rules);
    when(rules.postAsync(any())).thenReturn(ruleResult);

    mockHttpContext(new RuleApiModel(this.sampleNewRuleServiceModel, false));

    // Act
    controller.postAsync().thenApply(response -> {
        // Assert - that body is not null
        assertThat(response.body().isKnownEmpty(), is(false));

        // Assert - that body contains all fields
        JsonNode responseBody = Json.parse(response.body().toString());
        assertTrue(responseBody.hasNonNull("ETag"));
        assertTrue(responseBody.hasNonNull("Id"));
        assertTrue(responseBody.hasNonNull("Name"));
        assertTrue(responseBody.hasNonNull("DateCreated"));
        assertTrue(responseBody.hasNonNull("DateModified"));
        assertTrue(responseBody.hasNonNull("Enabled"));
        assertTrue(responseBody.hasNonNull("Description"));
        assertTrue(responseBody.hasNonNull("GroupId"));
        assertTrue(responseBody.hasNonNull("Severity"));
        assertTrue(responseBody.hasNonNull("Conditions"));
        assertTrue(responseBody.hasNonNull("Actions"));

        return null;
    });
}
 
Example #15
Source File: RulesControllerTest.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Test(timeout = 5000)
@Category({UnitTest.class})
public void itPutNewRuleWithNoEtagResultHasAllFields() throws Exception {
    CompletionStage<RuleServiceModel> ruleResult =
        Callback.Completable.completedFuture(null);

    IRules rules = mock(IRules.class);

    RulesController controller = new RulesController(rules);
    when(rules.upsertIfNotDeletedAsync(any())).thenReturn(ruleResult);

    mockHttpContext(new RuleApiModel(this.sampleNewRuleServiceModel, false));

    // Act
    controller.putAsync(this.sampleNewRuleServiceModel.getId()).thenApply(response -> {
        // Assert - that body is not null
        assertThat(response.body().isKnownEmpty(), is(false));

        // Assert - that body contains all fields
        JsonNode responseBody = Json.parse(response.body().toString());
        assertTrue(responseBody.hasNonNull("ETag"));
        assertTrue(responseBody.hasNonNull("Id"));
        assertTrue(responseBody.hasNonNull("Name"));
        assertTrue(responseBody.hasNonNull("DateCreated"));
        assertTrue(responseBody.hasNonNull("DateModified"));
        assertTrue(responseBody.hasNonNull("Enabled"));
        assertTrue(responseBody.hasNonNull("Description"));
        assertTrue(responseBody.hasNonNull("GroupId"));
        assertTrue(responseBody.hasNonNull("Severity"));
        assertTrue(responseBody.hasNonNull("Conditions"));
        assertTrue(responseBody.hasNonNull("Actions"));

        return null;
    });
}
 
Example #16
Source File: EchoServiceClient.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
private String sendMessage(GetListener getListener, Stream stream, String message, boolean endStream) throws JsonProcessingException {
    EchoMessage echoMessage = new EchoMessage(message);
    DataFrame dataFrame = new DataFrame(stream.getId(),
            ByteBuffer.wrap(objectMapper.writeValueAsBytes(echoMessage)), endStream);
    stream.data(dataFrame , new Callback() {});
    EchoMessage echoResponse = getListener.get(EchoMessage.class);
    getListener.restart();
    return echoResponse.getMessage();
}
 
Example #17
Source File: MarkableEndPoint.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
public void fillInterested(final Callback callback) throws ReadPendingException
{
    _underlying.fillInterested(callback);
}
 
Example #18
Source File: MockRemoteRepository.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public static MockRemoteRepository create(final String tupleQueryResponse, final String graphQueryResponse) {
	// pojo to retrieve values from mock service
	final Data data = new Data();

	String serviceURL = "http://localhost";
	HttpClient httpClient = new HttpClient() {
		@Override
		protected void send(HttpRequest request,
				List<ResponseListener> listeners) {
			// Store HTTP request
			data.request = request;
			data.listeners = listeners;
			for (ResponseListener listener: listeners) {
				if (listener instanceof JettyResponseListener) {
					HttpResponse response = new HttpResponse(request, null){
						@Override
						public int getStatus() {
							return 200;
						};
						
					};
					String requestMimeType = request.getHeaders().get(HttpHeader.ACCEPT).split(";")[0];
					TupleQueryResultFormat tupleQueryMimeType = TupleQueryResultFormat.forMIMEType(requestMimeType);
					String responseMimeType;
					String responseContent;
					if (tupleQueryMimeType!=null) {
						responseMimeType = TupleQueryResultFormat.TSV.getDefaultMIMEType();
						responseContent = tupleQueryResponse;
					} else {
						responseMimeType = RDFFormat.NTRIPLES.getDefaultMIMEType();
						responseContent = graphQueryResponse;
					}
					response.getHeaders().add(HttpHeader.CONTENT_TYPE, responseMimeType);
					((JettyResponseListener)listener).onHeaders(response);
					java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(responseContent.length());
					buf.put(responseContent.getBytes(Charset.forName(StandardCharsets.UTF_8.name())));
					buf.flip();
					((JettyResponseListener)listener).onContent(response, buf, Callback.NOOP);
					((JettyResponseListener)listener).onSuccess(response);
					((JettyResponseListener)listener).onComplete(new Result(request, response));
				}
			}
		}
		@Override
		public boolean isStopped() {
			return false;
		}
	};
	Executor executor = Executors.newCachedThreadPool();
	RemoteRepositoryManager mgr = new RemoteRepositoryManager(serviceURL,
			httpClient, executor) {
		@Override
		public JettyResponseListener doConnect(ConnectOptions opts) throws Exception {
			// Store connection options
			data.opts = opts;
			return super.doConnect(opts);
		}
	};

	return new MockRemoteRepository(mgr, serviceURL, null, data);
}
 
Example #19
Source File: HttpResponseStatisticsCollectorTest.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public void send(Response info, boolean head, ByteBuffer content, boolean lastContent, Callback callback) {
    callback.succeeded();
}
 
Example #20
Source File: TlsOrPlainConnectionFactoryTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void testOnFillableForTLS() throws Exception
{
    AtomicBoolean firstPart = new AtomicBoolean(true);
    Answer<Object> answer = (InvocationOnMock invocation) ->
    {
        ByteBuffer dst =
                (ByteBuffer) invocation.getArguments()[0];
        if (firstPart.get())
        {
            firstPart.set(false);
            return writeBytes(dst,
                              (byte) 22,
                              (byte) 3,
                              (byte) 1);
        }
        return writeBytes(dst,
                          (byte) 0,
                          (byte) 0,
                          (byte) 1);
    };
    when(_endPoint.fill(any(ByteBuffer.class))).thenAnswer(answer);

    TlsOrPlainConnectionFactory.PlainOrTlsConnection connection = _factory.newConnection(_connector, _endPoint);

    connection.onFillable();

    verify(_endPoint).fillInterested(any(Callback.class));

    connection.onFillable();

    verify(_actualConnection).onOpen();
    verify(_sslContextFactory).newSSLEngine(any());

    ByteBuffer buffer = BufferUtil.allocate(4);
    int result = connection.getEndPoint().fill(buffer);
    assertEquals((long) 4, (long) result);

    assertTrue(Arrays.equals(new byte[]{(byte) 22, (byte) 3, (byte) 1, (byte) 0}, buffer.array()));
    buffer = BufferUtil.allocate(2);

    result = connection.getEndPoint().fill(buffer);
    assertEquals((long) 2, (long) result);
    assertTrue(Arrays.equals(new byte[]{(byte) 0, (byte) 1}, buffer.array()));
    verify(_endPoint, times(3)).fill(any());
}
 
Example #21
Source File: MarkableEndPoint.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
public void write(final Callback callback, final ByteBuffer... buffers) throws WritePendingException
{
    _underlying.write(callback, buffers);
}
 
Example #22
Source File: MarkableEndPoint.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
public boolean tryFillInterested(final Callback callback)
{
    return _underlying.tryFillInterested(callback);
}
 
Example #23
Source File: CustomSessionListener.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
private void close(Stream stream, String reason) {
    LOG.info("close");
    stream.getSession().close(ErrorCode.PROTOCOL_ERROR.code, reason, Callback.NOOP);
}
 
Example #24
Source File: Response.java    From onedev with MIT License 4 votes vote down vote up
public void closeOutput(Callback callback)
{
    _out.close((_outputType == OutputType.WRITER) ? _writer : _out, callback);
}
 
Example #25
Source File: CustomSessionListener.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
    LOG.info("onData");
    getConnection().onData((IStream)stream, frame, callback);
}
 
Example #26
Source File: CustomSessionListener.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
@Override
public void onFailure(Session session, Throwable failure, Callback callback) {
    LOG.info("onFailure");
    getConnection().onSessionFailure(failure, callback);
}
 
Example #27
Source File: EchoServiceClient.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
@Override
public void close() throws Exception {
    session.close(0, null, new Callback() {});
    super.close();
}
 
Example #28
Source File: JettyClientExample.java    From http2-examples with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws Exception {
    long startTime = System.nanoTime();

    // Create and start HTTP2Client.
    HTTP2Client client = new HTTP2Client();
    SslContextFactory sslContextFactory = new SslContextFactory(true);
    client.addBean(sslContextFactory);
    client.start();

    // Connect to host.
    String host = "localhost";
    int port = 8443;

    FuturePromise<Session> sessionPromise = new FuturePromise<>();
    client.connect(sslContextFactory, new InetSocketAddress(host, port), new ServerSessionListener.Adapter(), sessionPromise);

    // Obtain the client Session object.
    Session session = sessionPromise.get(5, TimeUnit.SECONDS);

    // Prepare the HTTP request headers.
    HttpFields requestFields = new HttpFields();
    requestFields.put("User-Agent", client.getClass().getName() + "/" + Jetty.VERSION);
    // Prepare the HTTP request object.
    MetaData.Request request = new MetaData.Request("GET", new HttpURI("https://" + host + ":" + port + "/"), HttpVersion.HTTP_2, requestFields);
    // Create the HTTP/2 HEADERS frame representing the HTTP request.
    HeadersFrame headersFrame = new HeadersFrame(request, null, true);

    // Prepare the listener to receive the HTTP response frames.
    Stream.Listener responseListener = new Stream.Listener.Adapter()
    {
        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback)
        {
            byte[] bytes = new byte[frame.getData().remaining()];
            frame.getData().get(bytes);
            int duration = (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
            System.out.println("After " + duration + " seconds: " + new String(bytes));
            callback.succeeded();
        }
    };

    session.newStream(headersFrame, new FuturePromise<>(), responseListener);
    session.newStream(headersFrame, new FuturePromise<>(), responseListener);
    session.newStream(headersFrame, new FuturePromise<>(), responseListener);

    Thread.sleep(TimeUnit.SECONDS.toMillis(20));

    client.stop();
}
 
Example #29
Source File: StreamMessageProcessor.java    From java-11-examples with Apache License 2.0 2 votes vote down vote up
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {

}