Java Code Examples for org.apache.http.entity.ContentType#APPLICATION_OCTET_STREAM

The following examples show how to use org.apache.http.entity.ContentType#APPLICATION_OCTET_STREAM . 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: OTATest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testAuthorizationFailed() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString("123:123".getBytes()));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(403, response.getStatusLine().getStatusCode());
        String error = TestUtil.consumeText(response);

        assertNotNull(error);
        assertEquals("Authentication failed.", error);
    }
}
 
Example 2
Source File: GalaxyFDSClient.java    From galaxy-fds-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public PutObjectResult completeMultipartUpload(String bucketName, String objectName,
    String uploadId, FDSObjectMetadata metadata, UploadPartResultList uploadPartResultList)
        throws GalaxyFDSClientException {
  URI uri = formatUri(fdsConfig.getBaseUri(), bucketName + "/" + objectName, null);
  ContentType contentType = ContentType.APPLICATION_OCTET_STREAM;
  if (metadata != null && metadata.getContentType() != null) {
    contentType = ContentType.create(metadata.getContentType());
  }
  HashMap<String, String> params = new HashMap<String, String>();
  params.put("uploadId", uploadId);
  StringEntity requestEntity = getJsonStringEntity(uploadPartResultList,
    ContentType.APPLICATION_JSON);
  HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, HttpMethod.PUT,
    contentType, metadata, params, null, requestEntity);

  HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest,
    Action.CompleteMultiPartUpload);

  PutObjectResult putObjectResult = (PutObjectResult) fdsHttpClient.processResponse(response,
    PutObjectResult.class, "complete multipart upload of object [" + objectName + "] to bucket ["
        + bucketName + "]" + "; upload id [" + uploadId + "]");
  return putObjectResult;
}
 
Example 3
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void basicOTAForNonExistingSingleUser() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/[email protected]");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        String er = TestUtil.consumeText(response);
        assertNotNull(er);
        assertEquals("Requested user not found.", er);
    }
}
 
Example 4
Source File: HttpResourceUploader.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void upload(Factory<InputStream> source, Long contentLength, URI destination) throws IOException {
    HttpPut method = new HttpPut(destination);
    final RepeatableInputStreamEntity entity = new RepeatableInputStreamEntity(source, contentLength, ContentType.APPLICATION_OCTET_STREAM);
    method.setEntity(entity);
    HttpResponse response = http.performHttpRequest(method);
    EntityUtils.consume(response.getEntity());
    if (!http.wasSuccessful(response)) {
        throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s",
                destination, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
    }

}
 
Example 5
Source File: HttpResourceUploader.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void upload(Factory<InputStream> source, Long contentLength, URI destination) throws IOException {
    HttpPut method = new HttpPut(destination);
    final RepeatableInputStreamEntity entity = new RepeatableInputStreamEntity(source, contentLength, ContentType.APPLICATION_OCTET_STREAM);
    method.setEntity(entity);
    HttpResponse response = http.performHttpRequest(method);
    EntityUtils.consume(response.getEntity());
    if (!http.wasSuccessful(response)) {
        throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s",
                destination, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
    }

}
 
Example 6
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void basicOTAForSingleUser() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName());
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort());
    newHardwareClient.start();
    newHardwareClient.login(clientPair.token);
    verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1)));
    newHardwareClient.reset();

    newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1)));
    verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
}
 
Example 7
Source File: HttpResourceUploader.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void upload(Factory<InputStream> source, Long contentLength, String destination) throws IOException {
    HttpPut method = new HttpPut(destination);
    final RepeatableInputStreamEntity entity = new RepeatableInputStreamEntity(source, contentLength, ContentType.APPLICATION_OCTET_STREAM);
    method.setEntity(entity);
    HttpResponse response = http.performHttpRequest(method);
    EntityUtils.consume(response.getEntity());
    if (!http.wasSuccessful(response)) {
        throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s",
                destination, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
    }

}
 
Example 8
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testStopOTA() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }
    String responseUrl = "http://127.0.0.1:18080" + path;

    HttpGet stopOta = new HttpGet(httpsAdminServerUrl + "/ota/stop");
    stopOta.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    try (CloseableHttpResponse response = httpclient.execute(stopOta)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    clientPair.hardwareClient.verifyResult(ok(1));
    verify(clientPair.hardwareClient.responseMock, never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
}
 
Example 9
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void basicOTAForAllDevices() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    HttpGet index = new HttpGet("http://localhost:" + properties.getHttpPort() + path);

    try (CloseableHttpResponse response = httpclient.execute(index)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
    }
}
 
Example 10
Source File: GalaxyFDSClient.java    From galaxy-fds-sdk-java with Apache License 2.0 5 votes vote down vote up
private PutObjectResult uploadWithInputStream(String bucketName, String objectName,
    InputStream input, long contentLength, FDSObjectMetadata metadata, String storageClass)
        throws GalaxyFDSClientException {
  if (metadata == null) {
    metadata = new FDSObjectMetadata();
  }
  checkAndSetStorageClass(metadata, storageClass);
  ContentType contentType = ContentType.APPLICATION_OCTET_STREAM;
  if (metadata != null && metadata.getContentType() != null) {
    contentType = ContentType.create(metadata.getContentType());
  }
  if (fdsConfig.isMd5CalculateEnabled()) {
    if (metadata == null) {
      metadata = new FDSObjectMetadata();
    }
    metadata.addHeader(XiaomiHeader.MD5_ATTACHED_STREAM.getName(), "1");
    try {
      input = new FDSMd5InputStream(input);
    } catch (NoSuchAlgorithmException e) {
      throw new GalaxyFDSClientException("Cannot init md5", e);
    }
  }
  URI uri = formatUri(fdsConfig.getUploadBaseUri(),
    bucketName + "/" + (objectName == null ? "" : objectName), (SubResource[]) null);
  AbstractHttpEntity requestEntity = getRequestEntity(input, contentType, contentLength);

  HttpMethod m = objectName == null ? HttpMethod.POST : HttpMethod.PUT;
  HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, m, contentType, metadata,
    null, null, requestEntity);

  HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest,
    objectName == null ? Action.PostObject : Action.PutObject);

  return (PutObjectResult) fdsHttpClient.processResponse(response, PutObjectResult.class,
    m.name() + " object [" + objectName + "] to bucket [" + bucketName + "]");
}
 
Example 11
Source File: WechatPayUploadHttpPost.java    From wechatpay-apache-httpclient with Apache License 2.0 5 votes vote down vote up
public Builder withImage(String fileName, String fileSha256, InputStream inputStream) {
  this.fileName = fileName;
  this.fileSha256 = fileSha256;
  this.fileInputStream = inputStream;

  String mimeType = URLConnection.guessContentTypeFromName(fileName);
  if (mimeType == null) {
    // guess this is a video uploading
    this.fileContentType = ContentType.APPLICATION_OCTET_STREAM;
  } else {
    this.fileContentType = ContentType.create(mimeType);
  }
  return this;
}
 
Example 12
Source File: Notification.java    From azure-notificationhubs-java-backend with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to set up a native notification for WNS. Sets the
 * X-WNS-Type header to "wns/raw" in order of sending of raw notification.
 * 
 * @param body
 * @return
 */
public static Notification createWindowsRawNotification(String body) {
	Notification n = new Notification();
	n.body = body;
	n.headers.put("ServiceBusNotification-Format", "windows");
	n.headers.put("X-WNS-Type", "wns/raw");
	n.contentType = ContentType.APPLICATION_OCTET_STREAM;
	return n;
}
 
Example 13
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testOTAFailedWhenNoDevice() throws Exception {
    clientPair.hardwareClient.stop();

    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        String error = TestUtil.consumeText(response);

        assertNotNull(error);
        assertEquals("No device in session.", error);
    }
}
 
Example 14
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testImprovedUploadMethod() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    HttpGet index = new HttpGet("http://localhost:" + properties.getHttpPort() + path);

    try (CloseableHttpResponse response = httpclient.execute(index)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
    }
}
 
Example 15
Source File: UploadAPITest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private String upload(String filename) throws Exception {
    InputStream logoStream = UploadAPITest.class.getResourceAsStream("/" + filename);

    HttpPost post = new HttpPost("http://localhost:" + properties.getHttpPort() + "/upload");
    ContentBody fileBody = new InputStreamBody(logoStream, ContentType.APPLICATION_OCTET_STREAM, filename);
    StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    builder.addPart("text1", stringBody1);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String staticPath;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        staticPath = TestUtil.consumeText(response);

        assertNotNull(staticPath);
        assertTrue(staticPath.startsWith("/static"));
        assertTrue(staticPath.endsWith("bin"));
    }

    return staticPath;
}
 
Example 16
Source File: HttpResourceUploader.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void upload(Factory<InputStream> source, Long contentLength, String destination) throws IOException {
    HttpPut method = new HttpPut(destination);
    final RepeatableInputStreamEntity entity = new RepeatableInputStreamEntity(source, contentLength, ContentType.APPLICATION_OCTET_STREAM);
    method.setEntity(entity);
    HttpResponse response = http.performHttpRequest(method);
    EntityUtils.consume(response.getEntity());
    if (!http.wasSuccessful(response)) {
        throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s",
                destination, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
    }

}
 
Example 17
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testImprovedUploadMethodAndCheckOTAStatusForDeviceThatNeverWasOnline() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    clientPair.appClient.getDevice(1, 0);

    Device device = clientPair.appClient.parseDevice(1);
    assertNotNull(device);
    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000);

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));

    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000);
}
 
Example 18
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testConnectedDeviceGotOTACommand() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 123"));
    clientPair.hardwareClient.verifyResult(ok(1));
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
    clientPair.hardwareClient.reset();

    clientPair.appClient.getDevice(1, 0);
    Device device = clientPair.appClient.parseDevice();

    assertNotNull(device);
    assertNotNull(device.deviceOtaInfo);
    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertNotEquals(device.deviceOtaInfo.otaInitiatedAt, device.deviceOtaInfo.otaUpdateAt);
    assertEquals("123", device.hardwareInfo.build);

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build ") + "Aug 14 2017 20:31:49");
    clientPair.hardwareClient.verifyResult(ok(1));
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

}
 
Example 19
Source File: VmApiProxyDelegate.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
/**
 * Create an HTTP post request suitable for sending to the API server.
 *
 * @param environment The current VMApiProxyEnvironment
 * @param packageName The API call package
 * @param methodName The API call method
 * @param requestData The POST payload.
 * @param timeoutMs The timeout for this request
 * @return an HttpPost object to send to the API.
 */
// 
static HttpPost createRequest(VmApiProxyEnvironment environment, String packageName,
    String methodName, byte[] requestData, int timeoutMs) {
  // Wrap the payload in a RemoteApi Request.
  RemoteApiPb.Request remoteRequest = new RemoteApiPb.Request();
  remoteRequest.setServiceName(packageName);
  remoteRequest.setMethod(methodName);
  remoteRequest.setRequestId(environment.getTicket());
  remoteRequest.setRequestAsBytes(requestData);

  HttpPost request = new HttpPost("http://" + environment.getServer() + REQUEST_ENDPOINT);
  request.setHeader(RPC_STUB_ID_HEADER, REQUEST_STUB_ID);
  request.setHeader(RPC_METHOD_HEADER, REQUEST_STUB_METHOD);

  // Set TCP connection timeouts.
  HttpParams params = new BasicHttpParams();
  params.setLongParameter(ConnManagerPNames.TIMEOUT,
      timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);
  params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
      timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);
  params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
      timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);

  // Performance tweaks.
  params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.TRUE);
  params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, Boolean.FALSE);
  request.setParams(params);

  // The request deadline can be overwritten by the environment, read deadline if available.
  Double deadline = (Double) (environment.getAttributes().get(API_DEADLINE_KEY));
  if (deadline == null) {
    request.setHeader(RPC_DEADLINE_HEADER,
        Double.toString(TimeUnit.SECONDS.convert(timeoutMs, TimeUnit.MILLISECONDS)));
  } else {
    request.setHeader(RPC_DEADLINE_HEADER, Double.toString(deadline));
  }

  // If the incoming request has a dapper trace header: set it on outgoing API calls
  // so they are tied to the original request.
  Object dapperHeader = environment.getAttributes()
      .get(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey);
  if (dapperHeader instanceof String) {
    request.setHeader(
        VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey, (String) dapperHeader);
  }

  // If the incoming request has a Cloud trace header: set it on outgoing API calls
  // so they are tied to the original request.
  // TODO(user): For now, this uses the incoming span id - use the one from the active span.
  Object traceHeader = environment.getAttributes()
      .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey);
  if (traceHeader instanceof String) {
    request.setHeader(
        VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.headerKey,
        (String) traceHeader);
  }

  ByteArrayEntity postPayload = new ByteArrayEntity(remoteRequest.toByteArray(),
      ContentType.APPLICATION_OCTET_STREAM);
  postPayload.setChunked(false);
  request.setEntity(postPayload);

  return request;
}
 
Example 20
Source File: PostSlack.java    From nifi with Apache License 2.0 4 votes vote down vote up
private HttpEntity createFileMessageRequestBody(ProcessContext context, ProcessSession session, FlowFile flowFile) throws PostSlackException {
    MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();

    String channel = context.getProperty(CHANNEL).evaluateAttributeExpressions(flowFile).getValue();
    if (channel == null || channel.isEmpty()) {
        throw new PostSlackException("The channel must be specified.");
    }
    multipartBuilder.addTextBody("channels", channel, MIME_TYPE_PLAINTEXT_UTF8);

    String text = context.getProperty(TEXT).evaluateAttributeExpressions(flowFile).getValue();
    if (text != null && !text.isEmpty()) {
        multipartBuilder.addTextBody("initial_comment", text, MIME_TYPE_PLAINTEXT_UTF8);
    }

    String title = context.getProperty(FILE_TITLE).evaluateAttributeExpressions(flowFile).getValue();
    if (title != null && !title.isEmpty()) {
        multipartBuilder.addTextBody("title", title, MIME_TYPE_PLAINTEXT_UTF8);
    }

    String fileName = context.getProperty(FILE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    if (fileName == null || fileName.isEmpty()) {
        fileName = "file";
        getLogger().warn("File name not specified, has been set to {}.", new Object[]{ fileName });
    }
    multipartBuilder.addTextBody("filename", fileName, MIME_TYPE_PLAINTEXT_UTF8);

    ContentType mimeType;
    String mimeTypeStr = context.getProperty(FILE_MIME_TYPE).evaluateAttributeExpressions(flowFile).getValue();
    if (mimeTypeStr == null || mimeTypeStr.isEmpty()) {
        mimeType = ContentType.APPLICATION_OCTET_STREAM;
        getLogger().warn("Mime type not specified, has been set to {}.", new Object[]{ mimeType.getMimeType() });
    } else {
        mimeType = ContentType.getByMimeType(mimeTypeStr);
        if (mimeType == null) {
            mimeType = ContentType.APPLICATION_OCTET_STREAM;
            getLogger().warn("Unknown mime type specified ({}), has been set to {}.", new Object[]{ mimeTypeStr, mimeType.getMimeType() });
        }
    }

    multipartBuilder.addBinaryBody("file", session.read(flowFile), mimeType, fileName);

    return multipartBuilder.build();
}