Example usage for com.squareup.okhttp RequestBody create

List of usage examples for com.squareup.okhttp RequestBody create

Introduction

In this page you can find the example usage for com.squareup.okhttp RequestBody create.

Prototype

public static RequestBody create(final MediaType contentType, final File file) 

Source Link

Document

Returns a new request body that transmits the content of file .

Usage

From source file:org.graylog2.alarmcallbacks.HTTPAlarmCallback.java

License:Open Source License

@Override
public void call(final Stream stream, final AlertCondition.CheckResult result) throws AlarmCallbackException {
    final Map<String, Object> event = Maps.newHashMap();
    event.put("stream", stream);
    event.put("check_result", result);

    final Response r;
    try {//from   ww  w . j  av  a  2  s  .  c om
        final byte[] body = objectMapper.writeValueAsBytes(event);
        final URL url = new URL(configuration.getString(CK_URL));
        final Request request = new Request.Builder().url(url).post(RequestBody.create(CONTENT_TYPE, body))
                .build();
        r = httpClient.newCall(request).execute();
    } catch (JsonProcessingException e) {
        throw new AlarmCallbackException("Unable to serialize alarm", e);
    } catch (MalformedURLException e) {
        throw new AlarmCallbackException("Malformed URL", e);
    } catch (IOException e) {
        throw new AlarmCallbackException(e.getMessage(), e);
    }

    if (!r.isSuccessful()) {
        throw new AlarmCallbackException("Expected successful HTTP response [2xx] but got [" + r.code() + "].");
    }
}

From source file:org.graylog2.radio.cluster.InputService.java

License:Open Source License

public RegisterInputResponse registerInCluster(MessageInput input)
        throws ExecutionException, InterruptedException, IOException {
    final URI uri = UriBuilder.fromUri(serverUrl).path("/system/radios/{radioId}/inputs")
            .build(nodeId.toString());/*w ww.j a va2 s .  c  om*/

    final RegisterInputRequest rir = RegisterInputRequest.create(input.getId(), input.getTitle(),
            input.getType(), input.getConfiguration().getSource(), nodeId.toString(), input.getCreatorUserId());

    final Request request = new Request.Builder()
            .post(RequestBody.create(MediaType.parse(APPLICATION_JSON), mapper.writeValueAsBytes(rir)))
            .url(uri.toString()).build();

    final Response r = httpclient.newCall(request).execute();
    final RegisterInputResponse registerInputResponse = mapper.readValue(r.body().byteStream(),
            RegisterInputResponse.class);

    // Set the ID that was generated in the server as persist ID of this input.
    input.setPersistId(registerInputResponse.persistId());

    if (!r.isSuccessful()) {
        throw new RuntimeException(
                "Expected HTTP response [2xx] for input registration but got [" + r.code() + "].");
    }

    return registerInputResponse;
}

From source file:org.graylog2.radio.cluster.Ping.java

License:Open Source License

public void ping() throws IOException {
    final PingRequest pingRequest = PingRequest.create(ourUri.toString());

    final URI uri = serverUri.resolve("/system/radios/" + nodeId + "/ping");
    final Request request = new Request.Builder().url(uri.toURL())
            .put(RequestBody.create(CONTENT_TYPE, objectMapper.writeValueAsBytes(pingRequest))).build();

    final Response r = httpClient.newCall(request).execute();

    // fail on a non-ok status
    if (!r.isSuccessful()) {
        throw new RuntimeException("Expected successful HTTP response [2xx] but got [" + r.code()
                + "]. Request was " + request.urlString());
    }/*from  w ww.j a va  2s. c o m*/
}

From source file:org.hawkular.agent.monitor.cmd.FeedCommProcessor.java

License:Apache License

/**
 * Sends a message to the server asynchronously. This method returns immediately; the message may not go out until
 * some time in the future.//from  w ww  .  j av a2  s .  c om
 *
 * @param messageWithData the message to send
 */
public void sendAsync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) {
    if (webSocket == null) {
        throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages");
    }

    BasicMessage message = messageWithData.getBasicMessage();
    configurationAuthentication(message);

    sendExecutor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                if (messageWithData.getBinaryData() == null) {
                    String messageString = ApiDeserializer.toHawkularFormat(message);
                    Buffer buffer = new Buffer();
                    buffer.writeUtf8(messageString);
                    RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray());
                    FeedCommProcessor.this.webSocket.sendMessage(requestBody);
                } else {
                    BinaryData messageData = ApiDeserializer.toHawkularFormat(message,
                            messageWithData.getBinaryData());

                    RequestBody requestBody = new RequestBody() {
                        @Override
                        public MediaType contentType() {
                            return WebSocket.BINARY;
                        }

                        @Override
                        public void writeTo(BufferedSink bufferedSink) throws IOException {
                            emitToSink(messageData, bufferedSink);
                        }
                    };

                    FeedCommProcessor.this.webSocket.sendMessage(requestBody);
                }
            } catch (Throwable t) {
                log.errorFailedToSendOverFeedComm(message.getClass().getName(), t);
            }
        }
    });
}

From source file:org.hawkular.agent.monitor.cmd.FeedCommProcessor.java

License:Apache License

/**
 * Sends a message to the server synchronously. This will return only when the message has been sent.
 *
 * @param messageWithData the message to send
 * @throws IOException if the message failed to be sent
 *///from www . j  av  a  2 s .  c o  m
public void sendSync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) throws Exception {
    if (webSocket == null) {
        throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages");
    }

    BasicMessage message = messageWithData.getBasicMessage();
    configurationAuthentication(message);

    if (messageWithData.getBinaryData() == null) {
        String messageString = ApiDeserializer.toHawkularFormat(message);
        Buffer buffer = new Buffer();
        buffer.writeUtf8(messageString);
        RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray());
        FeedCommProcessor.this.webSocket.sendMessage(requestBody);
    } else {
        BinaryData messageData = ApiDeserializer.toHawkularFormat(message, messageWithData.getBinaryData());

        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return WebSocket.BINARY;
            }

            @Override
            public void writeTo(BufferedSink bufferedSink) throws IOException {
                emitToSink(messageData, bufferedSink);
            }
        };

        FeedCommProcessor.this.webSocket.sendMessage(requestBody);

    }
}

From source file:org.hawkular.agent.monitor.scheduler.OpsGroupRunnable.java

License:Apache License

private void submitResult(String operationId, String tenantId, OpsResult result) throws Exception {

    Request request;/*  ww  w.ja  va 2  s. c o m*/

    String uri = baseuri + "/" + selfIdentifiers.getFullIdentifier() + "/" + operationId;
    String json = Util.toJson(result);
    RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, json);

    request = new Request.Builder().url(uri).post(body).addHeader("Hawkular-Tenant", tenantId).build();

    // Asynchronous POST
    httpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            LOG.warn("Sending of response failed: " + e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.code() != 200) {
                LOG.warn("Send failed : " + response.message());
            }

        }
    });
}

From source file:org.hawkular.apm.tests.dist.AbstractITest.java

License:Apache License

protected Response post(Server server, String path, String tenant, Object payload) throws IOException {
    Request.Builder request = new Request.Builder()
            .post(RequestBody.create(MEDIA_TYPE_JSON, serialize(server, payload))).url(server.getURL() + path);

    if (tenant != null) {
        request.addHeader(HAWKULAR_TENANT_HEADER, tenant);
    }//from  w ww .j  a va  2s.co m

    Response response = execute(request.build(), server);

    switch (server) {
    case Zipkin: {
        Assert.assertEquals(202, response.code());
    }
    }

    return response;
}

From source file:org.hawkular.client.android.util.OperationManager.java

License:Apache License

public void sendRequest(String messageString) {
    messageString = "ExecuteOperationRequest=" + messageString;
    if (webSocket == null) {
        callback.onFailure(new IllegalStateException(context.getString(R.string.error_websocket_close)));
    } else {/*from  w w  w.j  av  a  2s  .co  m*/
        Buffer buffer = new Buffer();
        buffer.writeUtf8(messageString);
        RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray());
        try {
            webSocket.sendMessage(requestBody);
        } catch (IOException e) {
            callback.onFailure(e);
        }
    }
}

From source file:org.hawkular.datamining.itest.AbstractITest.java

License:Apache License

protected Response post(String path, String tenant, String payload) throws Throwable {
    Request request = new Request.Builder().post(RequestBody.create(MEDIA_TYPE_JSON, payload))
            .url(baseURI + path).addHeader(Constants.TENANT_HEADER_NAME, tenant).build();

    return execute(request);
}

From source file:org.hawkular.datamining.itest.AbstractITest.java

License:Apache License

protected Response post(String path, String tenant, Object payload) throws Throwable {
    String json = mapper.writeValueAsString(payload);

    Request request = new Request.Builder().post(RequestBody.create(MEDIA_TYPE_JSON, json)).url(baseURI + path)
            .addHeader(Constants.TENANT_HEADER_NAME, tenant).build();

    return execute(request);
}