protected String getRallyXML(String apiUrl) throws Exception {
    String responseXML = "";

    DefaultHttpClient httpClient = new DefaultHttpClient();

    Base64 base64 = new Base64();
    String encodeString =
        new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes()));

    HttpGet httpGet = new HttpGet(apiUrl);
    httpGet.addHeader("Authorization", "Basic " + encodeString);
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();

    if (entity != null) {

      InputStreamReader reader = new InputStreamReader(entity.getContent());
      BufferedReader br = new BufferedReader(reader);

      StringBuilder sb = new StringBuilder();
      String line = "";
      while ((line = br.readLine()) != null) {
        sb.append(line);
      }

      responseXML = sb.toString();
    }

    log.debug("responseXML=" + responseXML);

    return responseXML;
  }
Beispiel #2
0
    /**
     * Create an object (=file)
     *
     * @param containerName Name of the container
     * @param objectName Name of the file
     * @param contents Binary content of the file
     * @throws IOException
     */
    public void createObject(String containerName, String objectName, byte[] contents)
        throws Exception {
      HttpURLConnection conn =
          getConnBuilder(containerName, objectName)
              .method("PUT")
              .addHeader(HttpHeaders.CONTENT_LENGTH_HEADER, String.valueOf(contents.length))
              .getConnection();

      HttpResponse response = Utils.doSendOperation(conn, contents);

      if (!response.isSuccessCode()) {
        if (response.isAuthDenied()) {
          log.warn("Refreshing credentials and retrying");
          authenticate();
          createObject(containerName, objectName, contents);
        } else {
          log.error(
              "Error creating object "
                  + objectName
                  + " in container "
                  + containerName
                  + ",code = "
                  + response.code);
        }
      }
    }
  public String readResponse(HttpResponse response) {
    String output = "";

    HttpEntity entity = response.getEntity();

    try {
      trapException(response.getStatusLine().getStatusCode());
    } catch (CrowdFlowerException e1) {
      e1.printStackTrace();
    }

    InputStream instream;
    try {
      instream = entity.getContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(instream));

      // do something useful with the response
      output = output + reader.readLine();
      instream.close();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return output;
  }
Beispiel #4
0
 /**
  * Converts an exception raised while processing an HTTP request into a suitable HTTP response.
  *
  * <p>The response is marshalled and queued for writing on the socket associated with the original
  * request.
  *
  * @param msg The HTTP request being processed when the exception occurred.
  * @param e The exception that was raised.
  * @throws IOException if an error occurs marshalling or writing the response.
  */
 protected void handleMessageException(HttpMessageBuffer msg, Exception e) throws IOException {
   HttpResponse httpRsp;
   if (e instanceof HttpResponseException) {
     if (log.logWarn()) {
       log.warn("HttpResponseException", e);
     }
     httpRsp = this.newHttpResponse(msg, (HttpResponseException) e);
     this.queueWrite(msg.getSocket(), httpRsp.marshal(), true);
   } else if (e instanceof RemoteSocketClosedException) {
     if (log.logTrace()) {
       log.trace("Remote entity closed connection", e);
     }
   } else {
     if (log.logError()) {
       log.error("Internal Server Error", e);
     }
     httpRsp =
         this.newHttpResponse(
             msg,
             new HttpResponseException(
                 HttpConstants.StatusCodes._500_INTERNAL_SERVER_ERROR,
                 "Internal Server Error",
                 e));
     this.queueWrite(msg.getSocket(), httpRsp.marshal(), true);
   }
 }
Beispiel #5
0
 protected HttpResponse newHttpResponse(HttpMessageBuffer msg, HttpResponseException e) {
   HttpResponse httpRsp = e.toHttpResponse(msg.getHttpVersionString());
   if (msg.getHttpVersion() > 1.0) {
     httpRsp.addHeader(HttpConstants.Headers.HOST, this.headerHostValue);
   }
   httpRsp.addHeader(HttpConstants.Headers.SERVER, this.getServerName());
   httpRsp.addHeader(HttpConstants.Headers.CONNECTION, "close");
   return httpRsp;
 }
Beispiel #6
0
 /**
  * Constructs a new {@link HttpResponse} containing the given XML-RPC method response.
  *
  * <p>This implementation encodes the response using <code>UTF-8</code>, sets the status code to
  * <code>200</code>, and sets <code>Content-Type</code> header to <code>text/xml</code> as
  * required. No other headers are set.
  *
  * @param methodRsp The XML-RPC method response to be returned in the HTTP response.
  * @param encoding An {@link Encoding} describing the encoding to use when constructing this
  *     message. This also informs the <code>Content-Encoding</code> header value. May be <code>
  *     null</code>.
  * @return A new {@link HttpResponse} with the marshalled XML-RPC response as its content.
  * @throws IOException if an error occurs while marshalling the XML-RPC response.
  * @throws MarshallingException
  */
 protected HttpResponse toHttpResponse(
     HttpMessageBuffer origMsg, RpcResponse methodRsp, Encoding encoding)
     throws IOException, MarshallingException {
   ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
   methodRsp.marshal(byteOs, Charset.forName("UTF-8"));
   byte[] rspXml = byteOs.toByteArray();
   HttpResponse httpRsp = this.newHttpResponse(origMsg, 200, "OK", encoding);
   httpRsp.addHeader(HttpConstants.Headers.CONTENT_TYPE, methodRsp.getContentType());
   httpRsp.setContent(rspXml);
   return httpRsp;
 }
 public Result<InputStream> getInputStream(String endpoint) throws IOException {
   HttpClient cli = createClient();
   HttpGet get = createGet(endpoint);
   HttpResponse res = cli.execute(get);
   Object result = null;
   if (res.getStatusLine().getStatusCode() == 200) result = res.getEntity().getContent();
   else {
     RestResponse resp = new RestResponse(res);
     result = unmarshalPOJO(resp, InputStream.class);
     cli.getConnectionManager().shutdown();
   }
   return new Result<InputStream>(result);
 }
Beispiel #8
0
    /**
     * Create a container, which is equivalent to a bucket
     *
     * @param containerName Name of the container
     * @throws IOException
     */
    public void createContainer(String containerName) throws Exception {
      HttpURLConnection urlConnection =
          getConnBuilder(containerName, null).method("PUT").getConnection();

      HttpResponse response = Utils.doVoidOperation(urlConnection);

      if (!response.isSuccessCode()) {
        if (response.isAuthDenied()) {
          log.warn("Refreshing credentials and retrying");
          authenticate();
          createContainer(containerName);
        } else {
          log.error("Error creating container " + containerName + " ,code = " + response.code);
        }
      }
    }
Beispiel #9
0
    /**
     * Parse the room read response received from reservation backend.
     *
     * <p>This will request the retry if the response status code differs from 200, 201 or 4xx.
     *
     * @param response The Apache HTTP client response
     * @throws IOException
     * @throws ParseException
     * @throws FaultTolerantRESTRequest.RetryRequestedException
     */
    @Override
    protected void parse(HttpResponse response)
        throws IOException, ParseException, FaultTolerantRESTRequest.RetryRequestedException {

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

      logger.info("STATUS CODE: " + statusCode);

      if (200 == statusCode || 201 == statusCode) {
        // OK
        conference = readConferenceResponse(conference, response);

        result = new ApiResult(statusCode, conference);
      } else if ((statusCode >= 400) && (statusCode < 500)) {
        // Client side error, indicates that the reservation
        // backend do not want the resubmission
        ErrorResponse error = readErrorResponse(response);

        result = new ApiResult(statusCode, error);

      } else {

        // Unusual status code, request the retry
        throw new FaultTolerantRESTRequest.RetryRequestedException();
      }
    }
Beispiel #10
0
    /**
     * List files in a folder
     *
     * @param containerName Folder name
     * @return List of file names
     * @throws IOException
     */
    public List<String> listObjects(String containerName) throws Exception {
      HttpURLConnection urlConnection = getConnBuilder(containerName, null).getConnection();

      HttpResponse response = Utils.doReadOperation(urlConnection);

      if (!response.isSuccessCode()) {
        if (response.isAuthDenied()) {
          log.warn("Refreshing credentials and retrying");
          authenticate();
          return listObjects(containerName);
        } else {
          log.error("Error listing container " + containerName + ", code = " + response.code);
        }
      }
      return response.payloadAsLines();
    }
Beispiel #11
0
 public void process(final HttpResponse response, final HttpContext context)
     throws HttpException, IOException {
   HttpEntity entity = response.getEntity();
   if (entity != null) {
     Header ceheader = entity.getContentEncoding();
     if (ceheader != null) {
       HeaderElement[] codecs = ceheader.getElements();
       for (HeaderElement h : codecs) {
         if (h.getName().equalsIgnoreCase("deflate")) {
           response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
           return;
         }
       }
     }
   }
 }
Beispiel #12
0
  private void sendResponse(HttpResponse response) {
    Log.i(LOG_TAG, " sendResponse() started. Response = " + response);

    try {
      OutputStream out = socket.getOutputStream();

      response.write(out);

      out.flush();
      out.close();
      response.close();
    } catch (IOException ioe) {
      Log.e(LOG_TAG, "IOException writing to socket.", ioe);
    }

    Log.i(LOG_TAG, " sendResponse() ended.");
  }
Beispiel #13
0
  /**
   * Parses error response.
   *
   * @param response parsed <tt>ErrorResponse</tt>
   * @return <tt>ErrorResponse</tt> parsed from HTTP content stream.
   * @throws IOException if any IO issues occur.
   * @throws ParseException if any issues with JSON parsing occur.
   */
  private ErrorResponse readErrorResponse(HttpResponse response)
      throws IOException, ParseException {
    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    jsonParser.parse(rd, errorJson);

    return errorJson.getResult();
  }
Beispiel #14
0
 protected HttpResponse newHttpResponse(
     HttpMessageBuffer origMsg, int statusCode, String reasonPhrase, Encoding encoding) {
   Encoding responseEncoding = null;
   if (this.encodeResponses) {
     responseEncoding = encoding;
   }
   HttpResponse httpRsp;
   if (origMsg == null) {
     httpRsp = new HttpResponse(statusCode, reasonPhrase, responseEncoding);
   } else {
     httpRsp =
         new HttpResponse(
             origMsg.getHttpVersionString(), statusCode, reasonPhrase, responseEncoding);
   }
   if (origMsg.getHttpVersion() > 1.0) {
     httpRsp.addHeader(HttpConstants.Headers.HOST, this.headerHostValue);
   }
   httpRsp.addHeader(HttpConstants.Headers.SERVER, this.getServerName());
   return httpRsp;
 }
Beispiel #15
0
  protected String postRallyXML(String apiUrl, String requestXML) throws Exception {
    String responseXML = "";

    DefaultHttpClient httpClient = new DefaultHttpClient();

    Base64 base64 = new Base64();
    String encodeString =
        new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes()));

    HttpPost httpPost = new HttpPost(apiUrl);
    httpPost.addHeader("Authorization", "Basic " + encodeString);

    httpPost.setEntity(new StringEntity(requestXML));

    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();

    responseXML = getEntityString(entity);

    return responseXML;
  }
Beispiel #16
0
    /**
     * Delete a object (=file) from the storage
     *
     * @param containerName Folder name
     * @param objectName File name
     * @throws IOException
     */
    public void deleteObject(String containerName, String objectName) throws Exception {
      HttpURLConnection urlConnection =
          getConnBuilder(containerName, objectName).method("DELETE").getConnection();

      HttpResponse response = Utils.doVoidOperation(urlConnection);

      if (!response.isSuccessCode()) {
        if (response.isAuthDenied()) {
          log.warn("Refreshing credentials and retrying");
          authenticate();
          deleteObject(containerName, objectName);
        } else {
          log.error(
              "Error deleting object "
                  + objectName
                  + " from container "
                  + containerName
                  + ",code = "
                  + response.code);
        }
      }
    }
Beispiel #17
0
    /**
     * Read the content of a file
     *
     * @param containerName Name of the folder
     * @param objectName name of the file
     * @return Content of the files
     * @throws IOException
     */
    public byte[] readObject(String containerName, String objectName) throws Exception {
      HttpURLConnection urlConnection = getConnBuilder(containerName, objectName).getConnection();

      HttpResponse response = Utils.doReadOperation(urlConnection);

      if (!response.isSuccessCode()) {
        if (response.isAuthDenied()) {
          log.warn("Refreshing credentials and retrying");
          authenticate();
          return readObject(containerName, objectName);
        } else {
          log.error(
              "Error reading object "
                  + objectName
                  + " from container "
                  + containerName
                  + ", code = "
                  + response.code);
        }
      }
      return response.payload;
    }
Beispiel #18
0
    public Credentials authenticate() throws Exception {
      HttpURLConnection urlConnection =
          new ConnBuilder(authUrl)
              .addHeader(HttpHeaders.CONTENT_TYPE_HEADER, "application/json")
              .addHeader(HttpHeaders.ACCEPT_HEADER, "application/xml")
              .getConnection();

      StringBuilder jsonBuilder = new StringBuilder();
      jsonBuilder
          .append("{\"auth\": {\"tenantName\": \"")
          .append(tenant)
          .append("\", \"passwordCredentials\": {\"username\": \"")
          .append(username)
          .append("\", \"password\": \"")
          .append(password)
          .append("\"}}}");

      HttpResponse response =
          Utils.doOperation(urlConnection, jsonBuilder.toString().getBytes(), true);

      if (response.isSuccessCode()) {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(response.payload));

        String authToken = (String) tokenIdExpression.evaluate(doc, XPathConstants.STRING);
        String storageUrl = (String) publicUrlExpression.evaluate(doc, XPathConstants.STRING);

        log.trace("Authentication successful");

        return new Credentials(authToken, storageUrl);
      } else {
        throw new IllegalStateException(
            "Error authenticating to the service. Please check your credentials. Code = "
                + response.code);
      }
    }
Beispiel #19
0
  /**
   * Parses JSON string returned in HTTP response and converts it to <tt>Conference</tt> instance.
   *
   * @param conference <tt>Conference</tt> instance that contains the data returned by API endpoint.
   * @param response HTTP response returned by the API endpoint.
   * @return <tt>Conference</tt> instance that contains the data returned by API endpoint.
   * @throws IOException if any IO problems occur.
   * @throws ParseException if any problems with JSON parsing occur.
   */
  private Conference readConferenceResponse(Conference conference, HttpResponse response)
      throws IOException, ParseException {
    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    if (conference != null) {
      conferenceJson.setForUpdate(conference);
    }

    jsonParser.parse(rd, conferenceJson);

    if (conference == null) {
      conference = conferenceJson.getResult();
    }

    logger.info("ID: " + conference.getId());
    logger.info("PIN: " + conference.getPin());
    logger.info("URL: " + conference.getUrl());
    logger.info("SIP ID: " + conference.getSipId());
    logger.info("START TIME: " + conference.getStartTime());
    logger.info("DURATION: " + conference.getDuration());

    return conference;
  }
 @SuppressWarnings("unchecked")
 @Override
 public String success(HttpResponse hr) throws Exception {
   Map<String, ?> rsp = objectMapper.readValue(hr.getContent(), Map.class);
   return (String) rsp.get(REVISION_FIELD_NAME);
 }
Beispiel #21
0
  public HttpResponse getResponse(HttpRequestHeader hdr) {
    Log.i(LOG_TAG, " getResponse() started");

    HttpResponse response;

    if (hdr.getHeaderParams() == null) {
      Log.e(LOG_TAG, "No header params found in request");
      return new HttpResponse(HttpResponse.HTTP_BADREQUEST, "No header params found in request");
    }

    String method = hdr.getHeaderParams().getProperty("method");

    if (method == null) {
      Log.e(LOG_TAG, "No method in request headers");
      return new HttpResponse(HttpResponse.HTTP_BADREQUEST, "No method in request headers");
    }

    if (!method.equalsIgnoreCase("GET")) {
      Log.e(LOG_TAG, "getResponse() - only GET supported");
      return new HttpResponse(HttpResponse.HTTP_NOTIMPLEMENTED, method + " not supported");
    }

    String filename = hdr.getHeaderParams().getProperty("uri");

    if (filename == null
        || filename.startsWith("..")
        || filename.endsWith("..")
        || filename.indexOf("../") >= 0) {
      Log.e(LOG_TAG, "getResponse() - file not found");

      return new HttpResponse(HttpResponse.HTTP_FORBIDDEN, "Relative paths not allowed");
    }

    try {
      String mime = "";
      ContentInputStreamAdapter.ContentInputStream responseData =
          inputStreamAdapter.getContentInputStream(filename);

      if (responseData == null) {
        return new HttpResponse(HttpResponse.HTTP_NOTFOUND, "File not found");
      }

      long startFrom = -1;
      long endAt = -1;
      String range = hdr.getHeaderParams().getProperty("range");

      if (range != null) {
        Log.i(LOG_TAG, "Request contains a range: " + range);

        if (range.startsWith("bytes=")) {
          range = range.substring("bytes=".length());
          int minus = range.indexOf('-');
          try {
            if (minus > 0) {
              startFrom = Long.parseLong(range.substring(0, minus));
              endAt = Long.parseLong(range.substring(minus + 1));
            }
          } catch (NumberFormatException nfe) {
            Log.w(LOG_TAG, "Non Fatal Error extracting range :" + range, nfe);
            startFrom = -1;
            endAt = -1;
          }
        }
      }

      if (startFrom >= 0) {
        if (startFrom >= responseData.contentLength) {
          response =
              new HttpResponse(
                  HttpResponse.HTTP_RANGE_NOT_SATISFIABLE, HttpResponse.MIME_PLAINTEXT, "");
          response.addHeader("Content-Range", "bytes 0-0/" + responseData.contentLength);

          if (mime.startsWith("application/")) {
            response.addHeader(
                "Content-Disposition", "attachment; filename=\"" + responseData.filename + "\"");
          }
        } else {
          response =
              new HttpResponse(
                  HttpResponse.HTTP_PARTIALCONTENT, responseData.mime, responseData.content);

          if (endAt < 0) {
            endAt = responseData.contentLength - 1;
          }

          long length = endAt - startFrom + 1;
          if (length < 0) {
            length = 0;
          }

          if (startFrom > 0) {
            responseData.content.skip(startFrom);
          }

          response.addHeader("Content-Length", "" + length);
          response.addHeader(
              "Content-Range",
              "bytes " + startFrom + "-" + endAt + "/" + responseData.contentLength);
        }
      } else {
        response = new HttpResponse(HttpResponse.HTTP_OK, responseData.mime, responseData.content);
        response.addHeader("Content-Length", "" + responseData.contentLength);
        response.addHeader("Accept-Ranges", "bytes");
      }

      response.addHeader("Original-Length", "" + responseData.contentLength);
      response.addHeader(
          "Last-Modified", dateFormatter.format(new Date(responseData.lastModifiedDate)));
    } catch (IOException ioe) {
      response =
          new HttpResponse(HttpResponse.HTTP_INTERNALERROR, "IOException: " + ioe.getMessage());
      Log.e(LOG_TAG, "Error Reading file", ioe);
    }

    response.addHeader("Date", dateFormatter.format(new Date()));
    response.addHeader("Content-Type", "audio/x-m4a");
    response.addHeader("Connection", "close");
    response.addHeader("Cache-Control", "no-cache");
    response.addHeader("Expires", "-1");
    response.addHeader("Pragma", "no-cache");

    Log.i(LOG_TAG, " getResponse() ended. Response = " + response);

    return response;
  }