예제 #1
0
  /**
   * Submit a job to this worker.
   *
   * @param jobId The job that this partition is part of
   * @param partition The partition fot the worker to do
   * @return true if the partition was successfully submitted
   */
  public boolean submitPartition(UUID jobId, Partition partition) {
    String submitUri = "http://" + metadata.getHostAndPort() + "/job/" + jobId + "/partition";
    HttpPut httpPut = new HttpPut(submitUri);

    StringEntity stringEntity = null;
    try {
      stringEntity = new StringEntity(objectWriter.writeValueAsString(partition));
      stringEntity.setContentType(MediaType.APPLICATION_JSON);
    } catch (IOException e) {
      logger.warn(
          "Unable to JSONify partition <"
              + partition.getPartitionId()
              + "> for jobId <"
              + jobId
              + ">");
    }
    httpPut.setEntity(stringEntity);

    logger.info(
        "Sending partition <"
            + partition.getPartitionId()
            + "> of jobId <"
            + jobId
            + "> to <"
            + metadata.getWorkerId()
            + ">");
    return tellWorker(httpPut, Response.Status.ACCEPTED);
  }
  @Test
  public void testKeepAlive() throws Exception {
    String url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/pin/a14";

    HttpPut request = new HttpPut(url);
    request.setHeader("Connection", "keep-alive");

    HttpGet getRequest = new HttpGet(url);
    getRequest.setHeader("Connection", "keep-alive");

    for (int i = 0; i < 100; i++) {
      request.setEntity(new StringEntity("[\"" + i + "\"]", ContentType.APPLICATION_JSON));

      try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());
      }

      try (CloseableHttpResponse response2 = httpclient.execute(getRequest)) {
        assertEquals(200, response2.getStatusLine().getStatusCode());
        List<String> values = consumeJsonPinValues(response2);
        assertEquals(1, values.size());
        assertEquals(String.valueOf(i), values.get(0));
      }
    }
  }
예제 #3
0
파일: Cosm.java 프로젝트: nuest/JCosmAPI
  // update datapoint
  // Cosm documentation says, it's a post. It is in fact a PUT
  public void updateDatapoint(Integer feedid, String datastreamid, Datapoint datapoint)
      throws CosmException {
    try {
      HttpPut request =
          new HttpPut(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams/"
                  + datastreamid
                  + "/datapoints/"
                  + datapoint.getAt()
                  + JSON_FILE_EXTENSION);
      JSONObject jo = new JSONObject();
      jo.put("value", datapoint.getValue());
      request.setEntity(new StringEntity(jo.toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      String body = this.client.getBody(response);
      if (statusLine.getStatusCode() != 200) {
        if (body.length() > 0) {
          JSONObject ej = new JSONObject(body);
          throw new CosmException(ej.getString("errors"));
        }

        throw new CosmException(statusLine.toString());
      }
    } catch (Exception e) {
      throw new CosmException("Caught exception in update datapoint: " + e.getMessage());
    }
  }
 public void sendJson(Object jsonData) throws Log4AllException {
   HttpPut addLogPut;
   if (jsonData instanceof JSONArray) {
     addLogPut = new HttpPut(url + "/api/logs");
   } else {
     addLogPut = new HttpPut(url + "/api/log");
   }
   String rawResponse = "";
   JSONObject jsonResp;
   try {
     JSONObject jsonReq;
     if (jsonData instanceof JSONArray) {
       jsonReq = new JSONObject();
       jsonReq.put("logs", jsonData);
     } else {
       jsonReq = (JSONObject) jsonData;
     }
     jsonReq.put("application", this.application);
     if (token != null) {
       jsonReq.put("application_token", this.token);
     }
     HttpEntity postData = new StringEntity(jsonReq.toString());
     addLogPut.setEntity(postData);
     HttpResponse resp = getHttpClient().execute(addLogPut);
     rawResponse = IOUtils.toString(resp.getEntity().getContent());
     jsonResp = new JSONObject(rawResponse);
     if (!jsonResp.getBoolean("success")) {
       throw new Log4AllException(jsonResp.getString("message"));
     }
   } catch (IOException e) {
     throw new Log4AllException(e.getMessage() + "httpResp:" + rawResponse, e);
   } catch (JSONException e) {
     throw new Log4AllException(e.getMessage() + "httpResp:" + rawResponse, e);
   }
 }
예제 #5
0
  /**
   * Uploads a {@code File} with PRIVATE read access.
   *
   * @param uri upload {@link URI}
   * @param contentTypeString content type
   * @param contentFile the file to upload
   * @throws IOException
   */
  public static void uploadPrivateContent(
      final URI uri, final String contentTypeString, final File contentFile) throws IOException {

    LOGGER.info(
        "uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    FileEntity fileEntity = new FileEntity(contentFile, contentType);
    httpPut.setEntity(fileEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
      throw new IOException(
          String.format(
              "An error occurred while trying to upload private file - %d: %s",
              statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info(
        "uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});
  }
예제 #6
0
  @Test
  public void testUpdate() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/001");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    OperationOutcome oo =
        ourCtx.newXmlParser().parseResource(OperationOutcome.class, responseContent);
    assertEquals("OODETAILS", oo.getIssueFirstRep().getDetails().getValue());

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());
  }
  @Test
  public void testUpdateLocation() throws Exception {
    LocationRepository repository = container.getInjector().getInstance(LocationRepository.class);

    String id = repository.create(new Location("foo", 0, 0)).getId();

    Map<String, Object> location = new HashMap<String, Object>();
    location.put("id", id);
    location.put("name", "test-location");
    location.put("longitude", -122.4d);
    location.put("latitude", 48.5d);

    ObjectMapper om = new ObjectMapper();
    HttpPut updateRequest = new HttpPut("/location/" + id);
    updateRequest.setEntity(
        new ByteArrayEntity(om.writeValueAsBytes(location), ContentType.APPLICATION_JSON));

    HttpResponse httpResponse = container.execute(updateRequest);
    assertEquals(HttpURLConnection.HTTP_OK, httpResponse.getStatusLine().getStatusCode());

    Map<String, ?> response =
        om.readValue(
            EntityUtils.toString(httpResponse.getEntity()), new TypeReference<Map<String, ?>>() {});
    assertEquals("test-location", response.get("name"));
    assertEquals(-122.4d, response.get("longitude"));
    assertEquals(48.5d, response.get("latitude"));
  }
예제 #8
0
 protected HttpUriRequest constructHttpMethod(String methodName, String url, Object data)
     throws UnsupportedEncodingException {
   if (methodName.equalsIgnoreCase("POST")) {
     HttpPost httpPost = new HttpPost(url);
     log.debug("POST method created based on client request");
     if (data != null) httpPost.setEntity(new StringEntity(createJsonStringEntity(data), "UTF-8"));
     return httpPost;
   } else if (methodName.equalsIgnoreCase("PUT")) {
     HttpPut httpPut = new HttpPut(url);
     log.debug("PUT method created based on client request");
     if (data != null) httpPut.setEntity(new StringEntity(createJsonStringEntity(data), "UTF-8"));
     return httpPut;
   } else if (methodName.equalsIgnoreCase("DELETE")) {
     log.debug("DELETE method created based on client request");
     return new HttpDelete(url);
   } else if (methodName.equalsIgnoreCase("GET")) {
     log.debug("GET method created based on client request");
     HttpGetWithEntity httpGet = new HttpGetWithEntity(url);
     if (data != null) httpGet.setEntity(new StringEntity(createJsonStringEntity(data), "UTF-8"));
     return httpGet;
   } else if (methodName.equalsIgnoreCase("HEAD")) {
     log.debug("HEAD method created based on client request");
     return new HttpHead(url);
   } else {
     return null;
   }
 }
  /** 构造HttpPut */
  protected HttpUriRequest generateHttpRequest() {
    // 生成Http请求
    String resource =
        httpTool.generateCanonicalizedResource(
            "/" + objectGroup.getBucketName() + "/" + objectGroup.getName());
    String requestUri = OSS_END_POINT + resource;
    HttpPut httpPut = new HttpPut(requestUri);

    // 构造HttpPut
    String authorization =
        OSSHttpTool.generateAuthorization(
            accessId,
            accessKey,
            httpMethod.toString(),
            "",
            objectGroupMetaData.getContentType(),
            Helper.getGMTDate(),
            OSSHttpTool.generateCanonicalizedHeader(objectGroupMetaData.getAttrs()),
            resource);

    httpPut.setHeader(AUTHORIZATION, authorization);
    httpPut.setHeader(DATE, Helper.getGMTDate());
    httpPut.setHeader(HOST, OSS_HOST);

    try {
      httpPut.setEntity(new StringEntity(generateHttpEntity()));
    } catch (UnsupportedEncodingException e) {
      //            Log.e(this.getClass().getName(), e.getMessage());
    }

    return httpPut;
  }
 /** Executes the request against the appliance API (Should not be called directly). */
 @Override
 public MuteCheckResponse executeRequest() throws MorpheusApiRequestException {
   CloseableHttpClient client = null;
   try {
     URIBuilder uriBuilder = new URIBuilder(endpointUrl);
     uriBuilder.setPath("/api/monitoring/checks/" + this.getCheckId() + "/quarantine");
     HttpPut request = new HttpPut(uriBuilder.build());
     this.applyHeaders(request);
     HttpClientBuilder clientBuilder = HttpClients.custom();
     clientBuilder.setDefaultRequestConfig(this.getRequestConfig());
     client = clientBuilder.build();
     request.addHeader("Content-Type", "application/json");
     request.setEntity(new StringEntity(generateRequestBody()));
     CloseableHttpResponse response = client.execute(request);
     return MuteCheckResponse.createFromStream(response.getEntity().getContent());
   } catch (Exception ex) {
     // Throw custom exception
     throw new MorpheusApiRequestException(
         "Error Performing API Request for muting/unmuting a Check", ex);
   } finally {
     if (client != null) {
       try {
         client.close();
       } catch (IOException io) {
         // ignore
       }
     }
   }
 }
예제 #11
0
  public static String sendhttpByPut(String url, String params) {

    // ////billy-debugSystem.out.println("params:" + params);

    HttpPut httpRequest = new HttpPut(url);
    String strResult = null;
    try {
      // 发出HTTP request
      System.out.println("put发送的params是:" + params);
      httpRequest.setEntity(new StringEntity(params, "UTF-8"));
      // 取得HTTP response
      HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

      // 若状态码为200 ok
      if (httpResponse.getStatusLine().getStatusCode() == 200) {
        // 取出回应字串
        strResult = EntityUtils.toString(httpResponse.getEntity());

      } else {
        return null;
      }

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

    return strResult;
  }
예제 #12
0
  protected void putContent(String path, String content) throws Exception {
    String url = formatUrl(CONTENT_MGMT_PATH, path);
    HttpPut put = new HttpPut(url);
    put.setEntity(new StringEntity(content));

    CloseableHttpClient client = null;
    try {
      client = factory.createClient();
      CloseableHttpResponse response = client.execute(put);
      int code = response.getStatusLine().getStatusCode();
      if (code != 200 && code != 201) {
        String extra = "";
        if (response.getEntity() != null) {
          String body = IOUtils.toString(response.getEntity().getContent());
          extra = "\nBody:\n\n" + body;
        }

        Assert.fail(
            "Failed to put content to: "
                + path
                + ".\nURL: "
                + url
                + "\nStatus: "
                + response.getStatusLine()
                + extra);
      }
    } finally {
      IOUtils.closeQuietly(client);
    }
  }
  @Test
  public void testAddUserByAdminInvalidMessage() throws Exception {

    IRODSAccount irodsAccount =
        testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);

    StringBuilder sb = new StringBuilder();
    sb.append("http://localhost:");
    sb.append(
        testingPropertiesHelper.getPropertyValueAsInt(
            testingProperties, RestTestingProperties.REST_PORT_PROPERTY));
    sb.append("/user/");

    DefaultHttpClientAndContext clientAndContext =
        RestAuthUtils.httpClientSetup(irodsAccount, testingProperties);
    try {

      HttpPut httpPut = new HttpPut(sb.toString());
      httpPut.addHeader("accept", "application/json");
      httpPut.addHeader("Content-Type", "application/json");
      String body = "I am not valid json";
      httpPut.setEntity(new StringEntity(body));

      HttpResponse response =
          clientAndContext.getHttpClient().execute(httpPut, clientAndContext.getHttpContext());
      Assert.assertEquals(400, response.getStatusLine().getStatusCode());

    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      clientAndContext.getHttpClient().getConnectionManager().shutdown();
    }
  }
  public Object updateApplication(String appName, String absolutePath, IProgressMonitor monitor)
      throws APIException {
    try {
      final File file = new File(absolutePath);
      final FileBody fileBody = new FileBody(file);

      final MultipartEntity entity = new MultipartEntity();
      entity.addPart(file.getName(), fileBody);

      final HttpPut httpPut = new HttpPut();
      httpPut.setEntity(entity);

      Object response = httpJSONAPI(httpPut, getUpdateURI(appName));

      if (response instanceof JSONObject) {
        JSONObject json = (JSONObject) response;

        if (isSuccess(json)) {
          System.out.println("updateApplication: success."); // $NON-NLS-1$
        } else {
          return "updateApplication: error " + getUpdateURI(appName); // $NON-NLS-1$
        }
      }

      httpPut.releaseConnection();
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    return null;
  }
예제 #15
0
  @Test
  public void testUpdateWithTagWithSchemeAndLabel() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.addCodedDiagnosis().addCoding().setCode("AAA");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\"");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    CloseableHttpResponse status = ourClient.execute(httpPost);
    assertEquals(1, ourReportProvider.getLastTags().size());
    assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0));
    IOUtils.closeQuietly(status.getEntity().getContent());

    httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\";   ");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    status = ourClient.execute(httpPost);
    IOUtils.closeQuietly(status.getEntity().getContent());

    assertEquals(1, ourReportProvider.getLastTags().size());
    assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0));
  }
예제 #16
0
  /**
   * Takes the extracted base URI and parameters from the {@link RequestConfig} consolidated
   * parameter type and creates a {@link HttpRequestBase} of the designated method type.
   *
   * @param uri the {@link URI} whose parameters should be populated
   * @param annotatedParams the list of {@link Param}s and the parameter objects which were
   *     annotated with them; <b>Complex objects should supply a formatted version of their String
   *     representation via {@link Object#toString()}</b>
   * @param staticParams the list of {@link Request.Param}s and the parameter objects which were
   *     annotated with them <br>
   *     <br>
   * @return the created {@link HttpRequestBase} which is an instance of {@link HttpPost} <br>
   *     <br>
   * @throws Exception when the {@link HttpRequestBase} could not be created due to an exception
   *     <br>
   *     <br>
   * @since 1.1.3
   */
  private static HttpRequestBase populatePutParameters(
      URI uri, Map<Object, Param> annotatedParams, List<Request.Param> staticParams)
      throws Exception {

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    for (Request.Param param : staticParams)
      nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));

    Set<Entry<Object, Param>> methodParams = annotatedParams.entrySet();

    for (Entry<Object, Param> entry : methodParams)
      nameValuePairs.add(
          new BasicNameValuePair(entry.getValue().value(), entry.getKey().toString()));

    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
    urlEncodedFormEntity.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType());

    HttpPut httpPut = new HttpPut(uri);

    httpPut.setHeader(
        HttpHeaders.CONTENT_TYPE.getHeaderName(),
        ContentType.APPLICATION_FORM_URLENCODED.getMimeType());

    httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    return httpPut;
  }
예제 #17
0
  @Test
  public void testUpdateWithVersion() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.getIdentifier().setValue("001");

    HttpPut httpPut = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPut.addHeader("Content-Location", "/DiagnosticReport/001/_history/004");
    httpPut.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPut);
    IOUtils.closeQuietly(status.getEntity().getContent());

    // String responseContent =
    // IOUtils.toString(status.getEntity().getContent());
    // ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/DiagnosticReport/001/_history/002",
        status.getFirstHeader("Location").getValue());
  }
  @Test
  public void testBasicAuthenticationSuccessOnNonRepeatablePutExpectContinue() throws Exception {
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());
    httpproc.addInterceptor(new RequestBasicAuth());
    httpproc.addInterceptor(new ResponseBasicUnauthorized());
    this.localServer =
        new LocalTestServer(httpproc, null, null, new AuthExpectationVerifier(), null, null);
    this.localServer.register("*", new AuthHandler());
    this.localServer.start();

    TestCredentialsProvider credsProvider =
        new TestCredentialsProvider(new UsernamePasswordCredentials("test", "test"));

    this.httpclient.setCredentialsProvider(credsProvider);

    HttpPut httpput = new HttpPut("/");
    httpput.setEntity(
        new InputStreamEntity(
            new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}), -1));
    httpput.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

    HttpResponse response = this.httpclient.execute(getServerHttp(), httpput);
    HttpEntity entity = response.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity);
  }
예제 #19
0
  @Test
  public void testUpdateWithWrongResourceType() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/AAAAAA");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    assertEquals(400, status.getStatusLine().getStatusCode());

    String expected =
        "<OperationOutcome xmlns=\"http://hl7.org/fhir\"><issue><severity value=\"error\"/><details value=\"Failed to parse request body as XML resource. Error was: DataFormatException at [[row,col {unknown-source}]: [1,1]]: Incorrect resource type found, expected &quot;DiagnosticReport&quot; but found &quot;Patient&quot;\"/></issue></OperationOutcome>";
    assertEquals(expected, responseContent);
  }
  @Test(expected = ClientProtocolException.class)
  public void testBasicAuthenticationFailureOnNonRepeatablePutDontExpectContinue()
      throws Exception {
    this.localServer.register("*", new AuthHandler());
    this.localServer.start();

    TestCredentialsProvider credsProvider =
        new TestCredentialsProvider(new UsernamePasswordCredentials("test", "test"));

    this.httpclient.setCredentialsProvider(credsProvider);

    HttpPut httpput = new HttpPut("/");
    httpput.setEntity(
        new InputStreamEntity(
            new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}), -1));
    httpput.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    try {
      this.httpclient.execute(getServerHttp(), httpput);
      Assert.fail("ClientProtocolException should have been thrown");
    } catch (ClientProtocolException ex) {
      Throwable cause = ex.getCause();
      Assert.assertNotNull(cause);
      Assert.assertTrue(cause instanceof NonRepeatableRequestException);
      throw ex;
    }
  }
예제 #21
0
 protected static void put(HttpClient httpClient, String url, File file, String mimeType) {
   logger.debug("Doing PUT request on " + url);
   HttpPut put = new HttpPut(url);
   HttpEntity entity = null;
   try {
     if (mimeType == null || mimeType.trim().length() == 0) {
       mimeType = "application/octet-stream";
     }
     put.setEntity(new FileEntity(file, mimeType));
     HttpResponse response = httpClient.execute(put);
     entity = response.getEntity();
     int responseCode = response.getStatusLine().getStatusCode();
     if (responseCode != 200 && responseCode != 201 && responseCode != 204) {
       throw new RuntimeException(
           "Unexpected response code (" + responseCode + ") putting " + url);
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     if (entity != null) {
       try {
         entity.consumeContent();
       } catch (Exception e) {
       }
     }
   }
 }
예제 #22
0
  public String put(String url, Map<String, String> headers, byte[] data)
      throws ClientProtocolException, IOException, AuthorizationDeniedException {
    // create request
    HttpPut request = new HttpPut(url);

    // add data to request if necessary
    if (data != null) {
      ByteArrayEntity entity = new ByteArrayEntity(data);
      entity.setChunked(true);
      entity.setContentType("text/xml");
      request.setEntity(entity);
    }

    if (logger.isDebugEnabled()) {
      logger.debug("getting url: " + url);
    }

    // add headers to request if necessary
    if (headers != null && headers.size() > 0) {
      for (String header : headers.keySet()) {
        String value = headers.get(header);
        request.addHeader(header, value);

        if (logger.isDebugEnabled()) {
          logger.debug("adding header: " + header + " = " + value);
        }
      }
    }

    return process(request);
  }
 protected final String invoke_put_string(String url, Bundle params) throws IOException {
   DefaultHttpClient dhc = new DefaultHttpClient();
   try {
     set_basic_auth(dhc);
     Log.i(_module_name, "PUT: " + url);
     HttpPut put = new HttpPut(url);
     sign_auth(put);
     if (params != null) {
       ArrayList<NameValuePair> nvps = new ArrayList<NameValuePair>();
       for (String key : params.keySet()) {
         nvps.add(new BasicNameValuePair(key, params.getString(key)));
       }
       UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
       put.setEntity(reqEntity);
     }
     HttpResponse httpResponse = dhc.execute(put);
     int statusCode = httpResponse.getStatusLine().getStatusCode();
     String res = UHttpComponents.loadStringFromHttpResponse(httpResponse);
     if (!is_ok_status(statusCode)) {
       String phrase = httpResponse.getStatusLine().getReasonPhrase();
       String msg = String.format("PUT*STATUS: [%s:%s] %s <= %s", statusCode, phrase, res, url);
       throw new HttpIOException(msg, put, statusCode, phrase, res);
     }
     Log.i(_module_name, String.format("PUT-OK: %s <= %s", make_log_message(res.toString()), url));
     return res;
   } catch (IOException e) {
     Log.w(_module_name, String.format("PUT*IO: %s <= %s", e.getMessage(), url), e);
     throw e;
   } catch (Throwable e) {
     Log.w(_module_name, String.format("PUT*Throwable: %s <= %s", e.getMessage(), url), e);
     throw new InvocationTargetIOException(e);
   } finally {
     dhc.getConnectionManager().shutdown();
   }
 }
 /**
  * this class takes in the new edited interest and puts the edited interest's description into the
  * user profile. The Http Client sends an HTTP PUT request to the API to update a new interest.
  * The API sends information which is stored in Android via JSON to the webserver. Here new
  * interests belonged to the user are created.
  *
  * @param type
  * @param description
  * @throws JSONException
  * @throws ClientProtocolException
  * @throws IOException
  */
 public void editInterest(String type, String description)
     throws JSONException, ClientProtocolException, IOException {
   HttpClient client = new DefaultHttpClient();
   HttpPut put =
       new HttpPut(
           "http://myapp-gosuninjas.dotcloud.com/api/v1/createinterest/"
               + UserProfile.interestpoint
               + "/");
   put.setHeader("Content-type", "application/json");
   put.setHeader("Accept", "application/json");
   JSONObject obj = new JSONObject();
   obj.put("type_interest", type);
   obj.put("description", description);
   obj.put("user", UserProfile.myuserid);
   try {
     put.setEntity(new StringEntity(obj.toString(), "UTF-8"));
   } catch (UnsupportedEncodingException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   try {
     HttpResponse response = client.execute(put);
   } catch (ClientProtocolException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   } catch (IOException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
 }
예제 #25
0
  /**
   * 通过put方式发送请求 退出农场
   *
   * @param url URL地址
   * @param params 参数 user_serial, password, farm_serial
   * @return
   * @throws Exception
   */
  public String httpdelete(String url, String tokenAuth) throws Exception {
    // 拼接请求URL
    int timeoutConnection = YunTongXun.httpclienttime;
    int timeoutSocket = YunTongXun.httpclienttime;
    HttpParams httpParameters =
        new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(
        httpParameters,
        timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which
                            // is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    // 构造HttpClient的实例
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    // 创建GET方法的实例
    HttpPut httpexit = new HttpPut(url);
    httpexit.setHeader("Authorization", tokenAuth);
    try {
      HttpResponse httpResponse = httpClient.execute(httpexit);
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      return "{status_code:" + statusCode + "}";

    } catch (Exception e) {
      return null;
    }
  }
  private void putUrlFile(String url, DefaultHttpClient httpClient, String content)
      throws NotFoundException, ReportableError {
    try {
      HttpPut httpPut = new HttpPut(url);
      httpPut.setEntity(new StringEntity(content, "UTF-8"));
      HttpResponse response = httpClient.execute(httpPut);
      StatusLine statResp = response.getStatusLine();
      int statCode = statResp.getStatusCode();
      if (statCode >= 400) {
        this.pushedStageFile = false;
        throw new ReportableError(
            r.getString(
                R.string.error_url_put_detail,
                url,
                "Server returned code: " + Integer.toString(statCode)),
            null);
      } else {
        this.pushedStageFile = true;
      }

      httpClient.getConnectionManager().shutdown();
    } catch (UnsupportedEncodingException e) {
      throw new ReportableError(
          r.getString(R.string.error_unsupported_encoding, "mobileorg.org"), e);
    } catch (IOException e) {
      throw new ReportableError(r.getString(R.string.error_url_put, url), e);
    }
  }
예제 #27
0
파일: Cosm.java 프로젝트: nuest/JCosmAPI
  // update datastream
  public void updateDatastream(Integer feedid, String datastreamid, Datastream datastream)
      throws CosmException {
    try {
      HttpPut request =
          new HttpPut(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams/"
                  + datastreamid
                  + JSON_FILE_EXTENSION);
      request.setEntity(new StringEntity(datastream.toJSONObject().toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == 200) {
        this.client.getBody(response);
        return;
      }

      throw new HttpException(statusLine.toString());
    } catch (Exception e) {
      throw new CosmException(e.getMessage());
    }
  }
예제 #28
0
  @Test
  public void testUpdateNoResponse() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.addCodedDiagnosis().addCoding().setCode("AAA");

    String encoded = ourCtx.newXmlParser().encodeResourceToString(dr);
    ourLog.info("OUT: {}", encoded);

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.setEntity(
        new StringEntity(encoded, ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);
    try {
      ourLog.info(IOUtils.toString(status.getEntity().getContent()));
      assertEquals(200, status.getStatusLine().getStatusCode());
      assertEquals(
          "http://localhost:" + ourPort + "/DiagnosticReport/001/_history/002",
          status.getFirstHeader("location").getValue());
    } finally {
      IOUtils.closeQuietly(status.getEntity().getContent());
    }
  }
  @Test
  public void testUpdateWithoutConditionalUrl() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());

    assertEquals("Patient/2", new IdType(ourLastId).toUnqualified().getValue());
    assertEquals("Patient/2", ourLastIdParam.toUnqualified().getValue());
    assertNull(ourLastConditionalUrl);
  }
예제 #30
0
  public String unTag(NewTagModel untag) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      HttpGet oldTagGet = new HttpGet(cloudantURI + "/tag/" + untag.get_id());
      oldTagGet.addHeader(authHeaderKey, authHeaderValue);
      oldTagGet.addHeader(acceptHeaderKey, acceptHeaderValue);
      oldTagGet.addHeader(contentHeaderKey, contentHeaderValue);
      HttpResponse oldTagResp = httpclient.execute(oldTagGet);
      Gson gson = new Gson();
      TagModel updatedtag =
          gson.fromJson(EntityUtils.toString(oldTagResp.getEntity()), TagModel.class);
      httpclient.close();

      updatedtag.getTagged().remove(untag.getUsername());
      LOGGER.info(untag.get_id() + " is untagging " + untag.getUsername());
      HttpPut updatedTagPut = new HttpPut(cloudantURI + "/tag/" + untag.get_id());
      updatedTagPut.addHeader(authHeaderKey, authHeaderValue);
      updatedTagPut.addHeader(acceptHeaderKey, acceptHeaderValue);
      updatedTagPut.addHeader(contentHeaderKey, contentHeaderValue);
      updatedTagPut.setEntity(new StringEntity(gson.toJson(updatedtag)));
      httpclient = HttpClients.createDefault();
      HttpResponse updatedTagResp = httpclient.execute(updatedTagPut);
      if (!(updatedTagResp.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)) {
        String updatedTagEntity = EntityUtils.toString(updatedTagResp.getEntity());
        httpclient.close();
        return updatedTagEntity;
      }
      httpclient.close();
      return successJson;
    } catch (Exception e) {
      e.printStackTrace();
      return failJson;
    }
  }