All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.qas.api.auth.AbstractSigner Maven / Gradle / Ivy

The newest version!
package org.qas.api.auth;

import org.qas.api.AuthClientException;
import org.qas.api.Request;
import org.qas.api.internal.util.Encoders;
import org.qas.api.internal.util.Https;
import org.qas.api.internal.util.StringInputStream;
import org.qas.api.internal.util.google.base.Charsets;
import org.qas.api.internal.util.google.base.Throwables;
import org.qas.api.internal.util.google.hash.Hasher;
import org.qas.api.internal.util.google.hash.Hashing;
import org.qas.api.net.UrlEncoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.*;

/**
 * AbstractSigner
 *
 * @author Dzung Nguyen
 * @version $Id AbstractSigner 2014-03-27 15:06:30z dungvnguyen $
 * @since 1.0
 */
public abstract class AbstractSigner implements Signer {
  //~ class properties ========================================================
  /** default encoding */
  protected static final Charset DEFAULT_ENCODING = Charsets.UTF_8;

  //~ class members ===========================================================
  public byte[] hash(String text) {
    return Hashing.sha256().hashString(text, DEFAULT_ENCODING).asBytes();
  }

  protected byte[] hash(InputStream input) throws AuthClientException {
    try {
      Hasher function = Hashing.sha256().newHasher();

      byte[] buffer = new byte[1024];
      int length;
      while ((length = input.read(buffer)) > -1) {
        function.putBytes(buffer, 0, length);
      }

      return function.hash().asBytes();
    } catch (Exception ex) {
      throw new AuthClientException("Unable to compute hash while signing request: " + ex.getMessage(), ex);
    }
  }

  public byte[] hash(byte[] data) {
    return Hashing.sha256().hashBytes(data).asBytes();
  }

  protected String getCanonicalizedQueryString(Map params) {
    SortedMap sorted = new TreeMap();

    Iterator> pairs = params.entrySet().iterator();
    while (pairs.hasNext()) {
      Map.Entry pair = pairs.next();
      String key = pair.getKey();
      String value = pair.getValue();
      sorted.put(UrlEncoder.encode(key), UrlEncoder.encode(value));
    }

    StringBuilder builder = new StringBuilder();
    pairs = sorted.entrySet().iterator();

    while (pairs.hasNext()) {
      Map.Entry pair = pairs.next();
      builder.append(pair.getKey())
             .append("=")
             .append(pair.getValue());

      if (pairs.hasNext()) {
        builder.append("&");
      }
    }

    return builder.toString();
  }

  protected String getCanonicalizedQueryString(Request request) {
    if (Https.usePayloadForQueryParameters(request)) return "";
    else return getCanonicalizedQueryString(request.getParameters());
  }

  protected String getCanonicalizedResourcePath(String resourcePath) {
    if (resourcePath == null || resourcePath.length() == 0) {
      return "/";
    } else {
      String value = Https.pathEncode(resourcePath);
      return (value.startsWith("/") ? value : "/".concat(value));
    }
  }

  protected String getRequestPayload(Request request) {
    return Encoders.utf8decode(getBinaryRequestPayload(request));
  }

  protected byte[] getBinaryRequestPayload(Request request) {
    if (Https.usePayloadForQueryParameters(request)) {
      String params = Https.toQueryString(request.getParameters(), Charsets.UTF_8);
      if (params == null) return new byte[0];
      return Encoders.utf8encode(params);
    }
    return getBinaryRequestPayloadWithoutQueryParams(request);
  }

  protected String getRequestPayloadWithoutQueryParams(Request request) {
    return Encoders.utf8decode(getBinaryRequestPayloadWithoutQueryParams(request));
  }

  protected byte[] getBinaryRequestPayloadWithoutQueryParams(Request request) {
    InputStream content = getBinaryRequestPayloadStreamWithoutQueryParams(request);

    try {
      content.mark(-1);

      ByteArrayOutputStream output = new ByteArrayOutputStream(1024);

      byte[] buffer = new byte[8096];
      int length;

      while((length = content.read(buffer)) > -1) {
        output.write(buffer, 0, length);
      }
      output.close();
      content.reset();

      return output.toByteArray();
    } catch (Exception ex) {
      throw new AuthClientException("Unable to read request payload to sign request: " + ex.getMessage(), ex);
    }
  }

  protected InputStream getBinaryRequestPayloadStream(Request request) {
    if (Https.usePayloadForQueryParameters(request)) {
      String params = Https.toQueryString(request.getParameters(), Charsets.UTF_8);
      if (params == null) return new ByteArrayInputStream(new byte[0]);
      return new ByteArrayInputStream(Encoders.utf8encode(params));
    }
    return getBinaryRequestPayloadStreamWithoutQueryParams(request);
  }

  protected InputStream getBinaryRequestPayloadStreamWithoutQueryParams(Request request)
      throws AuthClientException {
    try {
      InputStream content = request.getContent();
      if (content == null) return new ByteArrayInputStream(new byte[0]);
      if (content instanceof StringInputStream) return content;
      if (!content.markSupported()) {
        throw new AuthClientException("Unable to read request payload to sign request.");
      }
      return content;
    } catch (Exception ex) {
      Throwables.propagateIfInstanceOf(ex, AuthClientException.class);
      throw new AuthClientException("Unable to read request payload to sign request: " + ex.getMessage(), ex);
    }
  }

  protected String getCanonicalizedEndPoint(URI endpoint) {
    String endpointAsString = endpoint.getHost().toLowerCase();
    if (Https.isUsingNonDefaultPort(endpoint)) {
      endpointAsString += ":" + endpoint.getPort();
    }
    return endpointAsString;
  }

  protected Date getSignatureDate(int timeOffset) {
    Date dateValue = new Date();
    if (timeOffset != 0) {
      long epochMillis = dateValue.getTime();
      epochMillis -= timeOffset * 1000;
      dateValue = new Date(epochMillis);
    }
    return dateValue;
  }

  protected abstract String base64(byte[] source);
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy