/**
   * 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});
  }
Beispiel #2
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;
    }
  }
  @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();
    }
  }
  @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));
  }
 @Test
 public void testUpdateCustomerBodyAndHeaders() throws Exception {
   HttpPut put =
       new HttpPut("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/123");
   StringWriter sw = new StringWriter();
   jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
   put.setEntity(new StringEntity(sw.toString()));
   put.addHeader("Content-Type", "text/xml");
   put.addHeader("Accept", "text/xml");
   HttpResponse response = httpclient.execute(put);
   assertEquals(200, response.getStatusLine().getStatusCode());
 }
  @Override
  public void uploadToFile(URI document, File file) throws IOException {
    HttpPut httpPut = new HttpPut(document);
    httpPut.addHeader("Authorization", "OAuth2 " + tokenClient.getAccessToken());
    httpPut.addHeader("Content-Type", "multipart/form-data");

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("filename", new FileBody(file));
    httpPut.setEntity(entity);

    httpClient.execute(httpPut);
  }
Beispiel #7
0
  public String updateTagged(NewTagModel newtag) {

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      // get old tagged from cloudant
      // in NewTagModel - get_id() returns person initiating tag - getUsername() returns person to
      // tag
      HttpGet oldTagGet = new HttpGet(cloudantURI + "/tag/" + newtag.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();

      // check for and don't allow retagging - currently front-end design shouldn't allow for this
      // but needs to be checked on server side as well
      if (updatedtag.getTagged().contains(newtag.getUsername())) {
        LOGGER.info(
            newtag.getUsername() + " already exists in tagged list for " + updatedtag.get_id());
        return alreadyTaggedJson;
      }

      // update array of tagged in updatedtag and update entry in cloudant
      updatedtag.getTagged().add(newtag.getUsername());
      HttpPut updatedTagPut = new HttpPut(cloudantURI + "/tag/" + newtag.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();
      LOGGER.info(newtag.get_id() + " tagged " + newtag.getUsername());
      return successJson;
    } catch (Exception e) {
      try {
        httpclient.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      e.printStackTrace();
      return failJson;
    }
  }
  @Test
  public void testAddUserByAdminBlankPassword() throws Exception {

    String testUserName = "******";
    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");

      ObjectMapper mapper = new ObjectMapper();
      UserAddByAdminRequest addRequest = new UserAddByAdminRequest();
      addRequest.setDistinguishedName("dn here");
      addRequest.setTempPassword("");
      addRequest.setUserName(testUserName);
      String body = mapper.writeValueAsString(addRequest);
      httpPut.setEntity(new StringEntity(body));

      HttpResponse response =
          clientAndContext.getHttpClient().execute(httpPut, clientAndContext.getHttpContext());
      HttpEntity entity = response.getEntity();
      Assert.assertEquals(200, response.getStatusLine().getStatusCode());
      String entityData = EntityUtils.toString(entity);
      UserAddActionResponse actual = mapper.readValue(entityData, UserAddActionResponse.class);
      Assert.assertEquals(
          UserAddActionResponse.UserAddActionResponseCode.ATTRIBUTES_MISSING,
          actual.getUserAddActionResponse());
      Assert.assertEquals(
          UserAddActionResponse.UserAddActionResponseCode.ATTRIBUTES_MISSING.ordinal(),
          actual.getUserAddActionResponseNumericCode());

    } 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();
    }
  }
  protected String getData(
      String url, String method, String contentType, String content, ContinuationToken cTokens) {
    try {
      HttpClient client = new DefaultHttpClient();
      HttpResponse res = null;
      url = url.replaceAll(" ", "%20");
      if (method == "GET") {
        HttpGet get = new HttpGet(url);
        get.addHeader("Authorization", token);
        get.addHeader("Content-Type", contentType);
        get.addHeader("Content-Length", content.length() + "");
        res = client.execute(get);
      } else if (method == "POST") {
        HttpPost post = new HttpPost(url);
        post.addHeader("Authorization", token);
        post.addHeader("Content-Type", contentType);
        StringEntity entity = new StringEntity(content, HTTP.UTF_8);
        post.setEntity(entity);
        res = client.execute(post);
      } else if (method == "DELETE") {
        HttpDelete del = new HttpDelete(url);
        del.addHeader("Authorization", token);
        del.addHeader("Content-Type", contentType);
        res = client.execute(del);
      } else if (method == "PUT") {
        HttpPut put = new HttpPut(url);
        put.addHeader("Authorization", token);
        put.addHeader("Content-Type", contentType);
        StringEntity entity = new StringEntity(content, HTTP.UTF_8);
        put.setEntity(entity);
        res = client.execute(put);
      }
      StatusLine sl = res.getStatusLine();
      String json = "";
      if (sl.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        res.getEntity().writeTo(out);
        out.close();
        json = out.toString();
        Log.i("result", json);
        return json;
      } else {
        Log.i("error", sl.getReasonPhrase());
      }

    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return null;
  }
  @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());
  }
 /** 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
       }
     }
   }
 }
Beispiel #12
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);
  }
Beispiel #13
0
  public static String put(String url, Map<String, String> data)
      throws IllegalStateException, ClientProtocolException, HttpResponseException, IOException {

    HttpPut request = new HttpPut(url);

    L.e("Request URL:" + url);
    // add the support of Gzip
    supportGzip(request);

    List<NameValuePair> parameters = new LinkedList<NameValuePair>();
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : data.entrySet()) {
      if (entry.getValue() == null) continue;
      sb.append(entry.getKey() + "=" + entry.getValue() + "&");
      parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    L.e(sb.toString());
    try {
      UrlEncodedFormEntity form = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
      request.addHeader("Content-Type", "application/x-www-form-urlencoded");
      request.setEntity(form);

      return processResponse(httpClient.execute(request));
    } catch (UnsupportedEncodingException e) {
      throw new ParseException(e.getMessage());
    }
  }
Beispiel #14
0
  @Override
  public int sendPut(String data, String url) {
    int responseCode = -1;
    HttpClient httpClient = new DefaultHttpClient();
    try {

      HttpPut request = new HttpPut(url);
      StringEntity params = new StringEntity(data, "UTF-8");
      params.setContentType("application/json");
      request.addHeader("content-type", "application/json");
      request.addHeader("Accept", "*/*");
      request.addHeader("Accept-Encoding", "gzip,deflate,sdch");
      request.addHeader("Accept-Language", "en-US,en;q=0.8");
      request.setEntity(params);
      HttpResponse response = httpClient.execute(request);
      responseCode = response.getStatusLine().getStatusCode();
      if (response.getStatusLine().getStatusCode() == 200
          || response.getStatusLine().getStatusCode() == 204) {

        BufferedReader br =
            new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        // System.out.println("Output from Server ...." + response.getStatusLine().getStatusCode() +
        // "\n");
        while ((output = br.readLine()) != null) {
          // System.out.println(output);
        }
      } else {
        logger.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        throw new RuntimeException(
            "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
      }

    } catch (Exception ex) {
      logger.error("exception for data: " + data + ", url = " + url);
      logger.error(elog.toStringException(ex));

    } finally {
      httpClient.getConnectionManager().shutdown();
    }

    return responseCode;
  }
 /** Creates the appropriate subclass of HttpUriRequest for passed in request. */
 @SuppressWarnings("deprecation")
 /* protected */ static HttpUriRequest createHttpRequest(
     Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError {
   switch (request.getMethod()) {
     case Method.DEPRECATED_GET_OR_POST:
       {
         // This is the deprecated way that needs to be handled for backwards compatibility.
         // If the request's post body is null, then the assumption is that the request is
         // GET. Otherwise, it is assumed that the request is a POST.
         byte[] postBody = request.getPostBody();
         if (postBody != null) {
           HttpPost postRequest = new HttpPost(request.getUrl());
           postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
           HttpEntity entity;
           entity = new ByteArrayEntity(postBody);
           postRequest.setEntity(entity);
           return postRequest;
         } else {
           return new HttpGet(request.getUrl());
         }
       }
     case Method.GET:
       return new HttpGet(request.getUrl());
     case Method.DELETE:
       return new HttpDelete(request.getUrl());
     case Method.POST:
       {
         HttpPost postRequest = new HttpPost(request.getUrl());
         postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         setEntityIfNonEmptyBody(postRequest, request);
         return postRequest;
       }
     case Method.PUT:
       {
         HttpPut putRequest = new HttpPut(request.getUrl());
         putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         setEntityIfNonEmptyBody(putRequest, request);
         return putRequest;
       }
     case Method.HEAD:
       return new HttpHead(request.getUrl());
     case Method.OPTIONS:
       return new HttpOptions(request.getUrl());
     case Method.TRACE:
       return new HttpTrace(request.getUrl());
     case Method.PATCH:
       {
         HttpPatch patchRequest = new HttpPatch(request.getUrl());
         patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         setEntityIfNonEmptyBody(patchRequest, request);
         return patchRequest;
       }
     default:
       throw new IllegalStateException("Unknown request method.");
   }
 }
Beispiel #16
0
  // TODO: throw all exceptions in the Execute method (or equivalent)
  public void Execute(int method) throws UnsupportedEncodingException {
    last_method = method;
    switch (method) {
      case HTTP_GET:
        {
          HttpGet request = new HttpGet(url + getCombinedParams());
          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }
          executeRequest(request, url);
          break;
        }
      case HTTP_POST:
        {
          HttpPost request = new HttpPost(url);
          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
          }

          executeRequest(request, url);
          break;
        }
      case HTTP_PUT:
        {
          HttpPut request = new HttpPut(url);
          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
          }

          executeRequest(request, url);
          break;
        }
      case HTTP_DELETE:
        {
          HttpDelete request = new HttpDelete(url + getCombinedParams());
          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }
          executeRequest(request, url);
          break;
        }
    }
  }
Beispiel #17
0
  /**
   * PUT request to the blogger api
   *
   * @param url the PUT url
   * @param accessToken the access token required by the blogger API
   * @param json the JSON containing the content to send
   * @return JSON containing the response
   * @throws Exception
   */
  protected String doPutRestBloggerApi(String url, String accessToken, String json)
      throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPut httpput = new HttpPut(url);
    StringEntity postee = null;
    HttpResponse response = null;
    HttpEntity entity = null;
    try {
      System.out.println((new Date()).toString() + " - Trying to PUT to " + url);
      httpput.addHeader("Authorization", accessToken);
      postee = new StringEntity(json, "UTF-8");
      postee.setContentType("application/json");
      httpput.setEntity(postee);
      response = httpclient.execute(httpput);

      int rc = response.getStatusLine().getStatusCode();

      entity = response.getEntity();
      if (rc != 201 && rc != 200) {
        throw new Exception("PUT unsuccessful. Returned code " + rc);
      }

      if (entity != null) {

        String content = EntityUtils.toString(entity, "UTF-8");
        System.out.println((new Date()).toString() + " - Got response from server: " + content);

        return content;
      } else throw new Exception("PUT unsuccessful. Null entity!");

    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      throw e;
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      throw e;
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    } finally {
      if (entity != null) {
        try {
          EntityUtils.consume(entity);
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if (httpput != null) httpput.abort();
      if (httpclient != null) httpclient.getConnectionManager().shutdown();
    }
  }
Beispiel #18
0
 static HttpUriRequest createMultiPartRequest(
     Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError {
   switch (request.getMethod()) {
     case Method.DEPRECATED_GET_OR_POST:
       {
         // This is the deprecated way that needs to be handled for backwards compatibility.
         // If the request's post body is null, then the assumption is that the request is
         // GET.  Otherwise, it is assumed that the request is a POST.
         byte[] postBody = request.getBody();
         if (postBody != null) {
           HttpPost postRequest = new HttpPost(request.getUrl());
           if (request.getBodyContentType() != null)
             postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
           HttpEntity entity;
           entity = new ByteArrayEntity(postBody);
           postRequest.setEntity(entity);
           return postRequest;
         } else {
           return new HttpGet(request.getUrl());
         }
       }
     case Method.GET:
       return new HttpGet(request.getUrl());
     case Method.DELETE:
       return new HttpDelete(request.getUrl());
     case Method.POST:
       {
         HttpPost postRequest = new HttpPost(request.getUrl());
         if (request.getBodyContentType() != null) {
           postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         }
         setMultiPartBody(postRequest, request);
         return postRequest;
       }
     case Method.PUT:
       {
         HttpPut putRequest = new HttpPut(request.getUrl());
         if (request.getBodyContentType() != null)
           putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         setMultiPartBody(putRequest, request);
         return putRequest;
       }
       // Added in source code of Volley libray.
     case Method.PATCH:
       {
         HttpPatch patchRequest = new HttpPatch(request.getUrl());
         if (request.getBodyContentType() != null)
           patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         return patchRequest;
       }
     default:
       throw new IllegalStateException("Unknown request method.");
   }
 }
Beispiel #19
0
 @SuppressWarnings("deprecation")
 static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders)
     throws AuthFailureError {
   switch (request.getMethod()) {
     case Method.DEPRECATED_GET_OR_POST:
       {
         byte[] postBody = request.getPostBody();
         if (postBody != null) {
           HttpPost postRequest = new HttpPost(request.getUrl());
           postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
           HttpEntity entity;
           entity = new ByteArrayEntity(postBody);
           postRequest.setEntity(entity);
           return postRequest;
         } else {
           return new HttpGet(request.getUrl());
         }
       }
     case Method.GET:
       return new HttpGet(request.getUrl());
     case Method.DELETE:
       return new HttpDelete(request.getUrl());
     case Method.POST:
       {
         HttpPost postRequest = new HttpPost(request.getUrl());
         postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         setEntityIfNonEmptyBody(postRequest, request);
         return postRequest;
       }
     case Method.PUT:
       {
         HttpPut putRequest = new HttpPut(request.getUrl());
         putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         setEntityIfNonEmptyBody(putRequest, request);
         return putRequest;
       }
     case Method.HEAD:
       return new HttpHead(request.getUrl());
     case Method.OPTIONS:
       return new HttpOptions(request.getUrl());
     case Method.TRACE:
       return new HttpTrace(request.getUrl());
     case Method.PATCH:
       {
         HttpPatch patchRequest = new HttpPatch(request.getUrl());
         patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         setEntityIfNonEmptyBody(patchRequest, request);
         return patchRequest;
       }
     default:
       throw new IllegalStateException("Unknown request method.");
   }
 }
 private synchronized void doRegister(String service) {
   String url = registryURL;
   try {
     HttpPut method = new HttpPut(url);
     method.addHeader("service", service);
     ResponseHandler<String> handler = new BasicResponseHandler();
     String responseBody = httpClient.execute(method, handler);
     LOG.debug("PUT to " + url + " got a " + responseBody);
   } catch (Exception e) {
     LOG.debug("PUT to " + url + " failed with: " + e);
   }
 }
  public String sentPost(String restUrl, AbstractHttpEntity reqEntity) throws IOException {
    HttpPut httpPut = new HttpPut(restUrl);
    httpPut.addHeader("Content-Type", "text/xml");
    // httpPost.addHeader("Content-Type", "application/x-protobuf");
    httpPut.setEntity(reqEntity);
    HttpResponse response = client.execute(httpPut);
    // System.out.println("response.getStatusLine().getStatusCode()=" +
    // response.getStatusLine().getStatusCode());
    // System.out.println("response.getStatusLine().getReasonPhrase()=" +
    // response.getStatusLine().getReasonPhrase());

    HttpEntity entity = response.getEntity();
    StringWriter writer = new StringWriter();
    IOUtils.copy(entity.getContent(), writer);
    return writer.toString();
  }
  public static int cancel10x(String urlString) throws IOException, InterruptedException {

    final URI uri = OOBuildStep.URI(urlString + EXECUTIONS_API + "/status");
    final HttpPut httpPut = new HttpPut(uri);
    String body = "{\"action\":\"cancel\"}";
    StringEntity entity = new StringEntity(body);
    httpPut.setEntity(entity);
    httpPut.setHeader(
        "Content-Type", "application/json"); // this is mandatory in order for the request to work
    if (OOBuildStep.getEncodedCredentials() != null) {
      httpPut.addHeader(
          "Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials()));
    }
    HttpResponse response = client.execute(httpPut);
    return response.getStatusLine().getStatusCode();
  }
  @Test
  public void testPutConsumer() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    mock.message(0).body().isInstanceOf(Customer.class);

    HttpPut put = new HttpPut("http://localhost:" + CXT + "/rest/customerservice/customers");
    StringEntity entity = new StringEntity(PUT_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    put.addHeader("test", "header1;header2");
    put.setEntity(entity);
    HttpClient httpclient = new DefaultHttpClient();

    try {
      HttpResponse response = httpclient.execute(put);
      assertEquals(200, response.getStatusLine().getStatusCode());
      assertEquals("", EntityUtils.toString(response.getEntity()));
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
  }
  public void getWebIdFromServerCaseTwo(Integer[] integer) {
    int webId;
    int responseId = integer[2];

    webId = integer[1];
    String recordsyncString = "";
    JSONObject jsonObject = new JSONObject();
    try {
      jsonObject.put("category_id", integer[0]);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    HttpClient httpclient = new DefaultHttpClient();

    HttpPut httppost = new HttpPut(baseUrl + "/api/records/" + webId + ".json");
    // attributes for survey sync
    try {
      httppost.addHeader("access_token", appController.getPreferences().getAccessToken());
      httppost.setEntity(createStringEntity(jsonObject));
      HttpResponse httpResponse = httpclient.execute(httppost);
      HttpEntity httpEntity = httpResponse.getEntity();
      recordsyncString = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    int recordId = jsonParser.parseRecordIdResult(recordsyncString);
    if (recordId != 0) {
      dbAdapter.updateRecordsTable(recordId, responseId);
      dbAdapter.updateAnswerTable(responseId, recordId, webId);
    } else {
      asynTaskCheck = true;
    }
  }
    @Override
    public void run() {
      String s;
      while ((s = queue.poll()) != null) {
        try {
          HttpClient client = HttpClientBuilder.create().build();
          HttpPut put =
              new HttpPut(
                  serverAddress
                      + "/_ah/api/voucheradmin/v2/communities/1/vouchers/"
                      + s
                      + "/redeem");
          put.addHeader("Content-Type", "application/json");
          put.setEntity(
              new StringEntity(
                  "{\"id\":33333,\"userName\":\"" + Thread.currentThread().getName() + "\"}"));

          org.apache.http.HttpResponse response = client.execute(put);

          BufferedReader rd =
              new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

          StringBuilder result = new StringBuilder();
          String line;
          while ((line = rd.readLine()) != null) {
            result.append(line);
          }

          System.out.println(
              Thread.currentThread().getName() + " : " + result.toString().replaceAll("\n", ""));

        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
Beispiel #26
0
  /**
   * Generate and make the necessary HTTP request.
   *
   * @return
   * @throws IOException
   * @throws ClientProtocolException
   * @throws URISyntaxException
   * @throws Exception
   */
  public HttpResponse generateRequest()
      throws ClientProtocolException, IOException, URISyntaxException {

    String URL = this.getRequestURL();
    // List<NameValuePair> queryParamsNVPair = null;
    HttpRequestBase request = null;

    switch (method) {
      case "GET":
        request = new HttpGet(URL);
        for (String headerKey : this.headers.keySet()) {
          request.addHeader(headerKey, headers.get(headerKey));
        }
        break;
      case "POST":
        HttpPost postRequest = new HttpPost(URL);
        for (String headerKey : this.headers.keySet()) {
          postRequest.addHeader(headerKey, headers.get(headerKey));
        }
        if (bodyParams != null) {
          StringEntity requestBodySE = new StringEntity(bodyParams.toString());
          requestBodySE.setContentType("application/json");
          postRequest.setEntity(requestBodySE);
        }
        request = postRequest;
        break;
      case "PUT":
        HttpPut putRequest = new HttpPut(URL);
        for (String headerKey : this.headers.keySet()) {
          putRequest.addHeader(headerKey, headers.get(headerKey));
        }
        if (bodyParams != null) {
          StringEntity requestBodySE = new StringEntity(bodyParams.toString());
          System.out.println(requestBodySE.toString());
          requestBodySE.setContentEncoding("application/json");
          putRequest.setEntity(requestBodySE);
        }
        request = putRequest;
        System.out.println(request.getURI().toString());
        break;
      case "DELETE":
        request = new HttpDelete(URL);
        for (String headerKey : this.headers.keySet()) {
          request.addHeader(headerKey, headers.get(headerKey));
        }
        break;
      default:
        break;
    }

    if (queryParams != null) {
      URIBuilder getUriBuilder = new URIBuilder(request.getURI());
      Iterator<?> paramKeys = queryParams.keys();
      while (paramKeys.hasNext()) {
        String param = (String) paramKeys.next();
        try {
          getUriBuilder.addParameter(param, queryParams.getString(param));
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
      URI getUri = getUriBuilder.build();
      ((HttpRequestBase) request).setURI(getUri);
    }

    HttpResponse response = sbgClient.execute(request);

    return response;
  }
  @Test
  public void testAddUserByAdmin() throws Exception {

    String testUser = "******";
    String testPassword = "******";
    String testDn = "testDNForaddubyAdminRest";
    IRODSAccount irodsAccount =
        testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);

    IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem.getIRODSAccessObjectFactory();

    UserAO userAO = accessObjectFactory.getUserAO(irodsAccount);
    userAO.deleteUser(testUser);

    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");

      ObjectMapper mapper = new ObjectMapper();
      UserAddByAdminRequest addRequest = new UserAddByAdminRequest();
      addRequest.setDistinguishedName(testDn);
      addRequest.setTempPassword(testPassword);
      addRequest.setUserName(testUser);
      String body = mapper.writeValueAsString(addRequest);

      System.out.println(body);

      httpPut.setEntity(new StringEntity(body));

      HttpResponse response =
          clientAndContext.getHttpClient().execute(httpPut, clientAndContext.getHttpContext());
      HttpEntity entity = response.getEntity();
      Assert.assertEquals(200, response.getStatusLine().getStatusCode());
      String entityData = EntityUtils.toString(entity);

      System.out.println(entityData);

      UserAddActionResponse actual = mapper.readValue(entityData, UserAddActionResponse.class);
      Assert.assertEquals(testUser, actual.getUserName());
      Assert.assertEquals(
          UserAddActionResponse.UserAddActionResponseCode.SUCCESS,
          actual.getUserAddActionResponse());
      Assert.assertEquals(
          UserAddActionResponse.UserAddActionResponseCode.SUCCESS.ordinal(),
          actual.getUserAddActionResponseNumericCode());

    } 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();
    }

    User user = userAO.findByName(testUser);
    Assert.assertNotNull("user not added", user);
    Assert.assertEquals("dn not set", testDn, user.getUserDN());
  }
  /**
   * Stuurt alle nieuwe polygonen naar de server
   *
   * @throws SyncException
   */
  private void putGroups() throws SyncException {
    Cursor c = db.getNewGroups();
    String name = "";
    int id = 0;

    if (!c.moveToFirst()) {
      return; // Niks te syncen, dus gelijk klaar!
    }

    /**
     * Als er tijdens het syncen een andere groep een ander id krijgt (omdat zijn id nodig was),
     * klopt onze cursor misschien niet meer dus moeten we opnieuw query'en.
     */
    boolean requery = false;

    do {
      HttpPut httpp = new HttpPut(serverUrl + "group");
      UsernamePasswordCredentials creds = new UsernamePasswordCredentials(mappUser, mappPass);

      id = c.getInt(0);
      name = c.getString(1);

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("name", name));

      try {
        httpp.addHeader(new BasicScheme().authenticate(creds, httpp));
        httpp.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      } catch (AuthenticationException e1) {
        Log.e(Mapp.TAG, e1.getStackTrace().toString());
        throw new SyncException("Authentication failed");
      } catch (UnsupportedEncodingException e) {
        Log.e(Mapp.TAG, e.getStackTrace().toString());
        throw new SyncException("Failed to encode data");
      }

      HttpResponse response;

      try {
        response = httpclient.execute(httpp);

        // Lees het resultaat van de actie in
        JSONObject result = null;
        InputStream is = response.getEntity().getContent();
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
          total.append(line);
        }

        result = new JSONObject(total.toString());

        if (response.getStatusLine().getStatusCode() == 418) {
          throw new SyncException("Unable to synchronize because the server is a teapot.");
        } else if (response.getStatusLine().getStatusCode() == 401) {
          throw new SyncException("Not authorized");
        } else if (response.getStatusLine().getStatusCode() != 200) {
          // Er is iets mis gegaan.
          Log.e(Mapp.TAG, "Sync error: " + result.getString("message"));
          throw new SyncException(result.getString("message"));
        } else {
          // De polygoon een nieuw id geven en het 'nieuw'-vlaggetje verwijderen
          db.setGroupIsSynced(id);
          requery = db.updateGroupId(id, result.getInt("group_id"));
        }
      } catch (ClientProtocolException e) {
        Log.e(Mapp.TAG, e.getMessage());
        throw new SyncException("Epic HTTP failure");
      } catch (IOException e) {
        Log.e(Mapp.TAG, e.getMessage());
        throw new SyncException("Exception during server synchronisation");
      } catch (JSONException e) {
        Log.e(Mapp.TAG, "Sync failed. Response is no valid JSON or expected variable not found.");
        throw new SyncException("Invalid server response");
      }

      if (requery) {
        c = db.getNewGroups(); // Opnieuw laden omdat polygoonid's gewijzigd kunnen zijn inmiddels
      }
    } while (c.moveToNext());
  }
  /**
   * Stuurt nieuwe lidmaatschappen naar 't servertje
   *
   * @throws SyncException
   */
  private void putMemberships() throws SyncException {
    Cursor c = db.getNewMemberships();
    String email = "";
    int id = 0;

    if (!c.moveToFirst()) {
      return; // Niks te syncen, dus gelijk klaar!
    }

    do {
      HttpPut httpp = new HttpPut(serverUrl + "membership");
      UsernamePasswordCredentials creds = new UsernamePasswordCredentials(mappUser, mappPass);

      id = c.getInt(0);
      email = c.getString(1);

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
      nameValuePairs.add(new BasicNameValuePair("email", email));
      nameValuePairs.add(new BasicNameValuePair("group_id", id + ""));

      try {
        httpp.addHeader(new BasicScheme().authenticate(creds, httpp));
        httpp.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      } catch (AuthenticationException e1) {
        Log.e(Mapp.TAG, e1.getStackTrace().toString());
        throw new SyncException("Authentication failed");
      } catch (UnsupportedEncodingException e) {
        Log.e(Mapp.TAG, e.getStackTrace().toString());
        throw new SyncException("Failed to encode data");
      }

      HttpResponse response;

      try {
        response = httpclient.execute(httpp);

        // Lees het resultaat van de actie in
        JSONObject result = null;
        InputStream is = response.getEntity().getContent();
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
          total.append(line);
        }

        result = new JSONObject(total.toString());

        if (response.getStatusLine().getStatusCode() == 418) {
          throw new SyncException("Unable to synchronize because the server is a teapot.");
        } else if (response.getStatusLine().getStatusCode() == 401) {
          throw new SyncException("Not authorized");
        } else if (response.getStatusLine().getStatusCode() != 200) {
          // Er is iets mis gegaan.
          Log.e(Mapp.TAG, "Sync error: " + result.getString("message"));
          throw new SyncException(result.getString("message"));
        } else {
          // Het 'nieuw'-vlaggetje verwijderen
          db.setMembershipIsSynced(id, email);
        }
      } catch (ClientProtocolException e) {
        Log.e(Mapp.TAG, e.getMessage());
        throw new SyncException("Epic HTTP failure");
      } catch (IOException e) {
        Log.e(Mapp.TAG, e.getMessage());
        throw new SyncException("Exception during server synchronisation");
      } catch (JSONException e) {
        Log.e(Mapp.TAG, "Sync failed. Response is no valid JSON or expected variable not found.");
        throw new SyncException("Invalid server response");
      }
    } while (c.moveToNext());
  }
  @Test
  public void testAddUserByAdminLongDn() throws Exception {

    String testUser = "******";
    String testPassword = "******";
    String testDN =
        "/CN=xxxxxyyxx-64f0-4d49-a0a9-508a8a5328cd/emailAddress=xxxxxxxxxxthismaynotshowup";
    IRODSAccount irodsAccount =
        testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);

    IRODSAccount userAccount =
        testingPropertiesHelper.buildIRODSAccountForIRODSUserFromTestPropertiesForGivenUser(
            testingProperties, testUser, testPassword);

    IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem.getIRODSAccessObjectFactory();

    UserAO userAO = accessObjectFactory.getUserAO(irodsAccount);

    try {
      userAO.findByName(testUser);
      String homeDir = MiscIRODSUtils.computeHomeDirectoryForIRODSAccount(userAccount);
      IRODSFile userHomeDir =
          irodsFileSystem.getIRODSFileFactory(userAccount).instanceIRODSFile(homeDir);

      for (File homeDirFile : userHomeDir.listFiles()) {
        homeDirFile.delete();
      }
      userAO.deleteUser(testUser);

    } catch (DataNotFoundException dnf) {
      // OK
    }

    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");

      ObjectMapper mapper = new ObjectMapper();
      UserAddByAdminRequest addRequest = new UserAddByAdminRequest();
      addRequest.setDistinguishedName(testDN);
      addRequest.setTempPassword(testPassword);
      addRequest.setUserName(testUser);
      String body = mapper.writeValueAsString(addRequest);

      System.out.println(body);

      httpPut.setEntity(new StringEntity(body));

      HttpResponse response =
          clientAndContext.getHttpClient().execute(httpPut, clientAndContext.getHttpContext());
      HttpEntity entity = response.getEntity();
      Assert.assertEquals(200, response.getStatusLine().getStatusCode());
      String entityData = EntityUtils.toString(entity);

      System.out.println(entityData);

      UserAddActionResponse actual = mapper.readValue(entityData, UserAddActionResponse.class);
      Assert.assertEquals(testUser, actual.getUserName());
      Assert.assertEquals(
          UserAddActionResponse.UserAddActionResponseCode.SUCCESS,
          actual.getUserAddActionResponse());
      Assert.assertEquals(
          UserAddActionResponse.UserAddActionResponseCode.SUCCESS.ordinal(),
          actual.getUserAddActionResponseNumericCode());

    } 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();
    }

    User user = userAO.findByName(testUser);
    Assert.assertNotNull("user not added", user);
    Assert.assertEquals("dn not set", testDN, user.getUserDN());
  }