コード例 #1
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());
    }
  }
コード例 #2
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());
    }
  }
コード例 #3
0
ファイル: Cosm.java プロジェクト: nuest/JCosmAPI
  // get a datapoint
  public Datapoint getDatapoint(Integer feedid, String datastreamid, String at)
      throws CosmException {
    try {
      HttpGet request =
          new HttpGet(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams/"
                  + datastreamid
                  + "/datapoints/"
                  + at
                  + JSON_FILE_EXTENSION);
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == 200) {
        return CosmFactory.toDatapoint(this.client.getBody(response));
      }

      throw new HttpException(statusLine.toString());
    } catch (Exception e) {
      e.printStackTrace();
      throw new CosmException(e.getMessage());
    }
  }
コード例 #4
0
  @Override
  protected String doInBackground(RazrbitCallParams... params) {

    Log.d("trial", "doInBackground starts");
    RazrbitCallParams razrbitCallParams = params[0];

    m_fnCallback = razrbitCallParams.GetCallback();

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(razrbitCallParams.GetUrl());

    Log.d("trial", "doInBackground before try");
    try {
      // Add your data
      httppost.setEntity(new UrlEncodedFormEntity(razrbitCallParams.GetParamList()));

      Log.d("trial", "doInBackground before execute");
      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httppost);

      StatusLine statusLine = response.getStatusLine();
      // Check the Http Request for success
      if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        m_bResultTypeIsNvp = razrbitCallParams.GetResultTypeIsNvp();
        if (m_bResultTypeIsNvp) {
          m_listNvpResult = ParseJsonFlatListToListNvp(out);
        } else {
          m_strResult = out.toString();
        }
      } else {
        // Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException("status code NOT OK: " + statusLine.toString());
      }
    } catch (ClientProtocolException e) {
      Log.w("HTTP2:", e);
      m_strResult = e.getMessage();
      m_bError = true;
      cancel(true);
    } catch (IOException e) {
      Log.w("HTTP3:", e);
      m_strResult = e.getMessage();
      m_bError = true;
      cancel(true);
    } catch (Exception e) {
      Log.w("HTTP4:", e);
      m_strResult = e.getMessage();
      m_bError = true;
      cancel(true);
    }

    return m_strResult;
  }
コード例 #5
0
  protected void throwExceptionIfNeeded(StatusLine statusLine, StreamSource streamSource) {
    log.debug("throwExceptionIfNeeded() statusLine:{}", statusLine);
    if (statusLine.getStatusCode() >= 200 && statusLine.getStatusCode() < 300) {
      log.debug("throwExceptionIfNeeded() returning without throwing exception");
      return;
    } else {
      String errorMsg;
      try {
        Errors errors = unmarshal(Errors.class, streamSource);
        log.debug("throwExceptionIfNeeded() parsed XML from error response:{}", errors);
        if (errors.getError() != null && !errors.getError().isEmpty()) {
          errorMsg = errors.getError().get(0);
        } else {
          errorMsg = UNKOWN_ERROR_CHARGIFY;
        }
      } catch (Exception e) {
        log.error(
            "throwExceptionIfNeeded() couldn't parse XML out of error response (this is normal)",
            e);
        errorMsg = statusLine.toString();
      }

      RuntimeException e;
      switch (statusLine.getStatusCode()) {
        case 401:
          e = new AuthenticationFailedException(errorMsg);
          break;
        case 403:
          e = new DisabledEndpointException(errorMsg);
          break;
        case 404:
          e = new NotFoundException(errorMsg);
          break;
        case 500:
          e = new InternalServerException(errorMsg);
          break;
        case 422:
          {
            if (errorMsg.contains("must be unique - that value has been taken")) {
              e = new DuplicateEntityException(errorMsg);
            } else {
              e = new InvalidRequestException(errorMsg);
            }
            break;
          }
        default:
          e = new ChargifyException(errorMsg);
          break;
      }
      log.debug("throwExceptionIfNeeded() throwing exception", e);
      throw e;
    }
  }
コード例 #6
0
ファイル: Cosm.java プロジェクト: nuest/JCosmAPI
 // delete user
 public void deleteUser(String login) throws CosmException {
   try {
     HttpDelete request = new HttpDelete(API_BASE_URL_V2 + "users/" + login + JSON_FILE_EXTENSION);
     HttpResponse response = this.client.execute(request);
     StatusLine statusLine = response.getStatusLine();
     this.client.getBody(response);
     if (statusLine.getStatusCode() != 200) {
       throw new HttpException(statusLine.toString());
     }
   } catch (Exception e) {
     e.printStackTrace();
     throw new CosmException(e.getMessage());
   }
 }
コード例 #7
0
ファイル: Cosm.java プロジェクト: nuest/JCosmAPI
 // deleting an apikey
 public void deleteApikey(String apikey) throws CosmException {
   try {
     HttpDelete request = new HttpDelete(API_BASE_URL_V2 + "keys/" + apikey);
     HttpResponse response = this.client.execute(request);
     StatusLine statusLine = response.getStatusLine();
     this.client.getBody(response);
     if (statusLine.getStatusCode() != 200) {
       throw new HttpException(statusLine.toString());
     }
   } catch (Exception e) {
     e.printStackTrace();
     throw new CosmException(e.getMessage());
   }
 }
コード例 #8
0
ファイル: Cosm.java プロジェクト: nuest/JCosmAPI
 // update user
 public void updateUser(String login, User user) throws CosmException {
   try {
     HttpPut request = new HttpPut(API_BASE_URL_V2 + "users/" + login + JSON_FILE_EXTENSION);
     request.setEntity(new StringEntity(user.toJSONObject().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 trigger: " + e.getMessage());
   }
 }
コード例 #9
0
  /**
   * download tickets.
   *
   * @return Array of json strings returned by the API.
   * @throws ApiException
   */
  protected static synchronized String downloadFromServer(String... params) throws ApiException {
    String retval = null;

    String url = Zendesk;

    Log.d(logTag, "Fetching " + url);

    // create an http client and a request object.
    HttpGet request = new HttpGet(url);

    HttpClient client = getNewHttpClient();

    try {

      // execute the request
      HttpResponse response = client.execute(request);

      StatusLine status = response.getStatusLine();
      if (status.getStatusCode() != HTTP_STATUS_OK) {
        // handle error here
        throw new ApiException("Invalid response from zendesk" + status.toString());
      }

      // process the content.
      HttpEntity entity = response.getEntity();
      InputStream ist = entity.getContent();
      ByteArrayOutputStream content = new ByteArrayOutputStream();

      int readCount = 0;
      while ((readCount = ist.read(buff)) != -1) {
        content.write(buff, 0, readCount);
      }
      retval = new String(content.toByteArray());

      // appendLog(retval);

    } catch (Exception e) {
      throw new ApiException("Problem connecting to the server " + e.getMessage(), e);
    }

    return retval;
  }
コード例 #10
0
  private String execute(HttpUriRequest request) throws IOException {
    log.debug("Executing following request: " + request.getRequestLine().toString());
    HttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    String responseString = null;
    if (entity != null) {
      responseString = EntityUtils.toString(entity);
      log.debug("Got response from http request: " + responseString);
    }

    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
      String message =
          request.getURI().toString() + " : GET Request failed(" + statusLine.toString() + ")";
      log.error(message);
      return null;
    }

    return responseString;
  }
コード例 #11
0
ファイル: Cosm.java プロジェクト: nuest/JCosmAPI
 // create user
 public void createUser(User user) throws CosmException {
   try {
     HttpPost request = new HttpPost(API_BASE_URL_V2 + "users" + JSON_FILE_EXTENSION);
     request.setEntity(new StringEntity(user.toJSONObject().toString()));
     HttpResponse response = this.client.execute(request);
     StatusLine statusLine = response.getStatusLine();
     String body = this.client.getBody(response);
     if (statusLine.getStatusCode() == 201) {
       return;
     }
     if ((body != null) && (body.length() > 0)) {
       JSONObject ej = new JSONObject(body);
       throw new CosmException(ej.getString("errors"));
     }
     throw new CosmException(statusLine.toString());
   } catch (Exception e) {
     e.printStackTrace();
     throw new CosmException("Caught exception in update createUser: " + e.getMessage());
   }
 }
コード例 #12
0
ファイル: Cosm.java プロジェクト: nuest/JCosmAPI
 // deleting multiple datapoints
 public void deleteDatapoints(
     Integer feedid, String datastreamid, String start, String end, String duration)
     throws CosmException {
   try {
     String url =
         API_BASE_URL_V2
             + API_RESOURCE_FEEDS
             + "/"
             + feedid
             + "/datastreams/"
             + datastreamid
             + "/datapoints?";
     boolean bAdd = false;
     if (start != null) {
       if (bAdd) url += '&';
       url += "start=" + start;
       bAdd = true;
     }
     if (end != null) {
       if (bAdd) url += '&';
       url += "end=" + end;
       bAdd = true;
     }
     if (duration != null) {
       if (bAdd) url += '&';
       url += "duration=" + duration;
       bAdd = true;
     }
     HttpDelete request = new HttpDelete(url);
     HttpResponse response = this.client.execute(request);
     StatusLine statusLine = response.getStatusLine();
     if (statusLine.getStatusCode() != 200) {
       throw new HttpException(statusLine.toString());
     }
   } catch (Exception e) {
     e.printStackTrace();
     throw new CosmException(e.getMessage());
   }
 }
コード例 #13
0
ファイル: Cosm.java プロジェクト: nuest/JCosmAPI
 // deleting a datapoint
 public void deleteDatapoint(Integer feedid, String datastreamid, String at) throws CosmException {
   try {
     HttpDelete request =
         new HttpDelete(
             API_BASE_URL_V2
                 + API_RESOURCE_FEEDS
                 + "/"
                 + feedid
                 + "/datastreams/"
                 + datastreamid
                 + "/datapoints/"
                 + at);
     HttpResponse response = this.client.execute(request);
     StatusLine statusLine = response.getStatusLine();
     this.client.getBody(response);
     if (statusLine.getStatusCode() != 200) {
       throw new HttpException(statusLine.toString());
     }
   } catch (Exception e) {
     e.printStackTrace();
     throw new CosmException(e.getMessage());
   }
 }
コード例 #14
0
  /**
   * Pull the raw text content of the given URL. This call blocks until the operation has completed,
   * and is synchronized because it uses a shared buffer {@link #sBuffer}.
   *
   * @param url The exact URL to request.
   * @return The raw content returned by the server.
   * @throws ApiException If any connection or server error occurs.
   */
  protected static synchronized String getUrlContent(String url) throws ApiException {
    if (sUserAgent == null) {
      throw new ApiException("User-Agent string must be prepared");
    }

    // Create client and set our specific user-agent string
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    request.setHeader("User-Agent", sUserAgent);

    try {
      HttpResponse response = client.execute(request);

      // Check if server response is valid
      StatusLine status = response.getStatusLine();
      if (status.getStatusCode() != HTTP_STATUS_OK) {
        throw new ApiException("Invalid response from server: " + status.toString());
      }

      // Pull content stream from response
      HttpEntity entity = response.getEntity();
      InputStream inputStream = entity.getContent();

      ByteArrayOutputStream content = new ByteArrayOutputStream();

      // Read response into a buffered stream
      int readBytes = 0;
      while ((readBytes = inputStream.read(sBuffer)) != -1) {
        content.write(sBuffer, 0, readBytes);
      }

      // Return result from buffered stream
      return new String(content.toByteArray());
    } catch (IOException e) {
      throw new ApiException("Problem communicating with API", e);
    }
  }
コード例 #15
0
  public void tempRedirectInvoke(
      @Nonnull String tempEndpoint,
      @Nonnull String method,
      @Nonnull String account,
      @Nonnull String resource,
      @Nonnull String body)
      throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
      logger.trace(
          "enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
    }
    if (wire.isDebugEnabled()) {
      wire.debug(
          "POST --------------------------------------------------------> "
              + endpoint
              + account
              + resource);
      wire.debug("");
    }
    try {
      HttpClient client = getClient();
      String url = tempEndpoint + account + resource;

      HttpRequestBase httpMethod = getMethod(method, url);

      // If it is networking configuration services
      if (httpMethod instanceof HttpPut) {
        if (url.endsWith("/services/networking/media")) {
          httpMethod.addHeader("Content-Type", "text/plain");
        } else {
          httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
        }
      } else {
        httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
      }

      // dmayne version is older for anything to do with images and for disk deletion
      if (url.indexOf("/services/images") > -1
          || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) {
        httpMethod.addHeader("x-ms-version", "2012-08-01");
      } else {
        httpMethod.addHeader("x-ms-version", "2012-03-01");
      }

      if (strategy != null && strategy.getSendAsHeader()) {
        httpMethod.addHeader(strategy.getHeaderName(), strategy.getRequestId());
      }

      if (wire.isDebugEnabled()) {
        wire.debug(httpMethod.getRequestLine().toString());
        for (Header header : httpMethod.getAllHeaders()) {
          wire.debug(header.getName() + ": " + header.getValue());
        }
        wire.debug("");
        if (body != null) {
          wire.debug(body);
          wire.debug("");
        }
      }

      if (httpMethod instanceof HttpEntityEnclosingRequestBase) {

        HttpEntityEnclosingRequestBase entityEnclosingMethod =
            (HttpEntityEnclosingRequestBase) httpMethod;

        if (body != null) {
          try {
            entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8"));
          } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }

      HttpResponse response;
      StatusLine status;

      try {
        response = client.execute(httpMethod);
        status = response.getStatusLine();
      } catch (IOException e) {
        logger.error(
            "post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
        if (logger.isTraceEnabled()) {
          e.printStackTrace();
        }
        throw new CloudException(e);
      }
      if (logger.isDebugEnabled()) {
        logger.debug("post(): HTTP Status " + status);
      }
      Header[] headers = response.getAllHeaders();

      if (wire.isDebugEnabled()) {
        wire.debug(status.toString());
        for (Header h : headers) {
          if (h.getValue() != null) {
            wire.debug(h.getName() + ": " + h.getValue().trim());
          } else {
            wire.debug(h.getName() + ":");
          }
        }
        wire.debug("");
      }
      if (status.getStatusCode() != HttpServletResponse.SC_OK
          && status.getStatusCode() != HttpServletResponse.SC_CREATED
          && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
        logger.error("post(): Expected OK for GET request, got " + status.getStatusCode());

        HttpEntity entity = response.getEntity();

        if (entity == null) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              "An error was returned without explanation");
        }
        try {
          body = EntityUtils.toString(entity);
        } catch (IOException e) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              e.getMessage());
        }
        if (wire.isDebugEnabled()) {
          wire.debug(body);
        }
        wire.debug("");
        AzureException.ExceptionItems items =
            AzureException.parseException(status.getStatusCode(), body);

        if (items == null) {
          throw new CloudException(
              CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown");
        }
        logger.error(
            "post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
        throw new AzureException(items);
      }
    } finally {
      if (logger.isTraceEnabled()) {
        logger.trace("exit - " + AzureMethod.class.getName() + ".post()");
      }
      if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(
            "POST --------------------------------------------------------> "
                + endpoint
                + account
                + resource);
      }
    }
  }
コード例 #16
0
 public BetfairApiServiceException(StatusLine statusLine, String body) {
   super(statusLine.toString() + (body.trim().isEmpty() ? "" : ": " + body.trim()));
 }
コード例 #17
0
  public String post(@Nonnull String account, @Nonnull String resource, @Nonnull String body)
      throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
      logger.trace(
          "enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
    }
    if (wire.isDebugEnabled()) {
      wire.debug(
          "POST --------------------------------------------------------> "
              + endpoint
              + account
              + resource);
      wire.debug("");
    }
    String requestId = null;
    try {
      HttpClient client = getClient();
      String url = endpoint + account + resource;

      HttpPost post = new HttpPost(url);

      if (url.toLowerCase().contains("operations")) {
        post.addHeader("x-ms-version", "2014-02-01");
      } else if (url.toLowerCase().contains("/deployments")) {
        post.addHeader("x-ms-version", "2014-05-01");
      } else {
        post.addHeader("x-ms-version", "2012-03-01");
      }

      if (strategy != null && strategy.getSendAsHeader()) {
        post.addHeader(strategy.getHeaderName(), strategy.getRequestId());
      }

      // If it is networking configuration services
      if (url.endsWith("/services/networking/media")) {
        post.addHeader("Content-Type", "text/plain;charset=UTF-8");
      } else {
        post.addHeader("Content-Type", "application/xml;charset=UTF-8");
      }

      if (wire.isDebugEnabled()) {
        wire.debug(post.getRequestLine().toString());
        for (Header header : post.getAllHeaders()) {
          wire.debug(header.getName() + ": " + header.getValue());
        }
        wire.debug("");
        if (body != null) {
          wire.debug(body);
          wire.debug("");
        }
      }
      if (body != null) {
        try {
          if (url.endsWith("/services/networking/media")) {
            post.setEntity(new StringEntity(body, "text/plain", "utf-8"));
          } else {
            post.setEntity(new StringEntity(body, "application/xml", "utf-8"));
          }

        } catch (UnsupportedEncodingException e) {
          throw new InternalException(e);
        }
      }
      HttpResponse response;
      StatusLine status;

      try {
        response = client.execute(post);
        status = response.getStatusLine();
      } catch (IOException e) {
        logger.error(
            "post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
        if (logger.isTraceEnabled()) {
          e.printStackTrace();
        }
        throw new CloudException(e);
      }
      if (logger.isDebugEnabled()) {
        logger.debug("post(): HTTP Status " + status);
      }
      Header[] headers = response.getAllHeaders();

      if (wire.isDebugEnabled()) {
        wire.debug(status.toString());
      }
      for (Header h : headers) {
        if (h.getValue() != null) {
          if (wire.isDebugEnabled()) {
            wire.debug(h.getName() + ": " + h.getValue().trim());
          }
          if (h.getName().equalsIgnoreCase("x-ms-request-id")) {
            requestId = h.getValue().trim();
          }
        } else {
          if (wire.isDebugEnabled()) {
            wire.debug(h.getName() + ":");
          }
        }
      }
      if (wire.isDebugEnabled()) {
        wire.debug("");
      }

      if (status.getStatusCode() != HttpServletResponse.SC_OK
          && status.getStatusCode() != HttpServletResponse.SC_CREATED
          && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
        logger.error("post(): Expected OK for GET request, got " + status.getStatusCode());

        HttpEntity entity = response.getEntity();

        if (entity == null) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              "An error was returned without explanation");
        }
        try {
          body = EntityUtils.toString(entity);
        } catch (IOException e) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              e.getMessage());
        }
        if (wire.isDebugEnabled()) {
          wire.debug(body);
        }
        wire.debug("");
        AzureException.ExceptionItems items =
            AzureException.parseException(status.getStatusCode(), body);

        if (items == null) {
          throw new CloudException(
              CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown");
        }
        logger.error(
            "post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
        throw new AzureException(items);
      }
    } finally {
      if (logger.isTraceEnabled()) {
        logger.trace("exit - " + AzureMethod.class.getName() + ".post()");
      }
      if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(
            "POST --------------------------------------------------------> "
                + endpoint
                + account
                + resource);
      }
    }
    return requestId;
  }
  private Map<Attribute, String> invokeWebService(
      URI serviceTargetURI, List<NameValuePair> formparams)
      throws VirtualCollectionRegistryException {
    // force xml encoding
    formparams.add(new BasicNameValuePair("encoding", "xml"));

    DefaultHttpClient client = null;
    try {
      client = new DefaultHttpClient();
      int port = serviceTargetURI.getPort() != -1 ? serviceTargetURI.getPort() : AuthScope.ANY_PORT;
      client
          .getCredentialsProvider()
          .setCredentials(
              new AuthScope(serviceTargetURI.getHost(), port),
              new UsernamePasswordCredentials(username, password));
      // disable expect continue, GWDG does not like very well
      client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
      // set a proper user agent
      client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
      HttpPost request = new HttpPost(serviceTargetURI);
      request.addHeader("Accept", "text/xml, application/xml");
      request.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
      HttpContext ctx = new BasicHttpContext();

      logger.debug("invoking GWDG service at {}", serviceTargetURI);
      HttpResponse response = client.execute(request, ctx);
      StatusLine status = response.getStatusLine();
      HttpEntity entity = response.getEntity();
      Map<Attribute, String> props = Collections.emptyMap();

      logger.debug("GWDG Service status: {}", status.toString());
      if ((status.getStatusCode() >= 200) && (status.getStatusCode() <= 299) && (entity != null)) {
        String encoding = EntityUtils.getContentCharSet(entity);
        if (encoding == null) {
          encoding = "UTF-8";
        }

        XMLStreamReader reader = factory.createXMLStreamReader(entity.getContent(), encoding);
        props = new HashMap<Attribute, String>();
        while (reader.hasNext()) {
          reader.next();

          int type = reader.getEventType();
          if (type != XMLStreamConstants.START_ELEMENT) {
            continue;
          }
          Attribute attribute = Attribute.fromString(reader.getLocalName());
          if (attribute != null) {
            if (!reader.hasNext()) {
              throw new VirtualCollectionRegistryException("unexpected end of data stream");
            }
            reader.next();
            if (reader.getEventType() != XMLStreamConstants.CHARACTERS) {
              throw new VirtualCollectionRegistryException(
                  "unexpected element type: " + reader.getEventType());
            }
            String value = reader.getText();
            if (value == null) {
              throw new VirtualCollectionRegistryException(
                  "element \"" + attribute + "\" was empty");
            }
            value = value.trim();
            if (!value.isEmpty()) {
              props.put(attribute, value);
            }
          }
        }

      } else {
        logger.debug("GWDG Handle service failed: {}", status);
        request.abort();
        throw new VirtualCollectionRegistryException("error invoking GWDG handle service");
      }
      return props;
    } catch (VirtualCollectionRegistryException e) {
      throw e;
    } catch (Exception e) {
      logger.debug("GWDG Handle service failed", e);
      throw new VirtualCollectionRegistryException("error invoking GWDG handle service", e);
    } finally {
      if (client != null) {
        client.getConnectionManager().shutdown();
      }
    }
  }
コード例 #19
0
  public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull URI uri)
      throws CloudException, InternalException {
    logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + uri + ")");
    wire.debug("--------------------------------------------------------> " + uri.toASCIIString());

    try {
      HttpClient client = getClient();
      HttpUriRequest get = new HttpGet(uri);

      if (uri.toString().indexOf("/services/images") > -1) {
        get.addHeader("x-ms-version", "2012-08-01");
      } else if (uri.toString().contains("/services/vmimages")) {
        get.addHeader("x-ms-version", "2014-05-01");
      } else {
        get.addHeader("x-ms-version", "2012-03-01");
      }

      if (strategy != null && strategy.getSendAsHeader()) {
        get.addHeader(strategy.getHeaderName(), strategy.getRequestId());
      }

      wire.debug(get.getRequestLine().toString());
      for (Header header : get.getAllHeaders()) {
        wire.debug(header.getName() + ": " + header.getValue());
      }

      HttpResponse response;
      StatusLine status;

      try {
        response = client.execute(get);
        status = response.getStatusLine();
      } catch (IOException e) {
        logger.error(
            "get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
        throw new CloudException(e);
      }

      logger.debug("get(): HTTP Status " + status);

      Header[] headers = response.getAllHeaders();

      wire.debug(status.toString());
      for (Header h : headers) {
        if (h.getValue() != null) {
          wire.debug(h.getName() + ": " + h.getValue().trim());
        } else {
          wire.debug(h.getName() + ":");
        }
      }

      if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {
        return null;
      }
      if (status.getStatusCode() != HttpServletResponse.SC_OK
          && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) {
        logger.error("get(): Expected OK for GET request, got " + status.getStatusCode());

        HttpEntity entity = response.getEntity();
        String body;

        if (entity == null) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              "An error was returned without explanation");
        }
        try {
          body = EntityUtils.toString(entity);
        } catch (IOException e) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              e.getMessage());
        }

        wire.debug(body);

        AzureException.ExceptionItems items =
            AzureException.parseException(status.getStatusCode(), body);

        if (items == null) {
          return null;
        }
        logger.error(
            "get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
        throw new AzureException(items);
      } else {
        HttpEntity entity = response.getEntity();

        if (entity == null) {
          return null;
        }
        InputStream input;

        try {
          input = entity.getContent();
        } catch (IOException e) {
          logger.error(
              "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage());
          throw new CloudException(e);
        }

        wire.debug("---> Binary Data <---");
        return input;
      }
    } finally {
      logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()");
      wire.debug(
          "--------------------------------------------------------> " + uri.toASCIIString());
    }
  }