首页

关于atmos中基于javax.inject.Singleton的实现ShareUrl、SignRequest类对象单例注入示例

标签:Singleton,单例注入,inject,atmos,jclouds     发布时间:2017-12-31   

一、前言

关于atmos(1.8.1)的包中基于javax.inject.Singleton注释的方式分别对org.jclouds.atmos.filters.SignRequest、org.jclouds.atmos.filters.ShareUrl以@Singleton的方式注入单例对象,具体源码示例参考如下

二、源码说明

1.ShareUrl类(@Singleton注入其单例对象)

package org.jclouds.atmos.filters;@b@@b@import com.google.common.base.Function;@b@import com.google.common.base.Supplier;@b@import com.google.common.base.Throwables;@b@import com.google.common.collect.ImmutableMap;@b@import com.google.common.io.BaseEncoding;@b@import com.google.common.io.ByteProcessor;@b@import com.google.common.io.ByteStreams;@b@import java.io.IOException;@b@import java.net.URI;@b@import java.security.InvalidKeyException;@b@import javax.annotation.Resource;@b@import javax.inject.Inject;@b@import javax.inject.Named;@b@import javax.inject.Singleton;@b@import org.jclouds.crypto.Crypto;@b@import org.jclouds.crypto.Macs;@b@import org.jclouds.date.TimeStamp;@b@import org.jclouds.domain.Credentials;@b@import org.jclouds.http.HttpException;@b@import org.jclouds.http.Uris;@b@import org.jclouds.http.Uris.UriBuilder;@b@import org.jclouds.logging.Logger;@b@import org.jclouds.util.Strings2;@b@@b@@Singleton@b@public class ShareUrl@b@  implements Function<String, URI>@b@{@b@  private final Supplier<Credentials> creds;@b@  private final Supplier<URI> provider;@b@  private final javax.inject.Provider<Long> timeStampProvider;@b@  private final Crypto crypto;@b@@b@  @Resource@b@  Logger logger = Logger.NULL;@b@@b@  @Resource@b@  @Named("jclouds.signature")@b@  Logger signatureLog = Logger.NULL;@b@@b@  @Inject@b@  public ShareUrl(@org.jclouds.location.Provider Supplier<Credentials> creds, @org.jclouds.location.Provider Supplier<URI> provider, @TimeStamp javax.inject.Provider<Long> timeStampProvider, Crypto crypto)@b@  {@b@    this.creds = creds;@b@    this.provider = provider;@b@    this.timeStampProvider = timeStampProvider;@b@    this.crypto = crypto;@b@  }@b@@b@  public URI apply(String path) throws HttpException@b@  {@b@    String requestedResource = "/rest/namespace/" + path;@b@    String expires = ((Long)this.timeStampProvider.get()).toString();@b@    String signature = signString(createStringToSign(requestedResource, expires));@b@    return Uris.uriBuilder((URI)this.provider.get()).replaceQuery(ImmutableMap.of("uid", ((Credentials)this.creds.get()).identity, "expires", expires, "signature", signature)).appendPath(requestedResource).build();@b@  }@b@@b@  public String createStringToSign(String requestedResource, String expires)@b@  {@b@    StringBuilder toSign = new StringBuilder();@b@    toSign.append("GET\n");@b@    toSign.append(requestedResource.toLowerCase()).append("\n");@b@    toSign.append(((Credentials)this.creds.get()).identity).append("\n");@b@    toSign.append(expires);@b@    return toSign.toString(); }@b@@b@  public String signString(String toSign) {@b@    ByteProcessor hmacSHA1;@b@    try {@b@      hmacSHA1 = Macs.asByteProcessor(this.crypto.hmacSHA1(BaseEncoding.base64().decode(((Credentials)this.creds.get()).credential)));@b@      return BaseEncoding.base64().encode((byte[])ByteStreams.readBytes(Strings2.toInputStream(toSign), hmacSHA1));@b@    } catch (InvalidKeyException e) {@b@      throw Throwables.propagate(e);@b@    } catch (IOException e) {@b@      throw Throwables.propagate(e);@b@    }@b@  }@b@}

2.SignRequest类也同样以@Singleton方式注入单例对象

package org.jclouds.atmos.filters;@b@@b@import com.google.common.annotations.VisibleForTesting;@b@import com.google.common.base.Strings;@b@import com.google.common.base.Supplier;@b@import com.google.common.collect.ImmutableMap;@b@import com.google.common.collect.ImmutableMap.Builder;@b@import com.google.common.collect.Multimap;@b@import com.google.common.collect.Multimaps;@b@import com.google.common.collect.Sets;@b@import com.google.common.io.BaseEncoding;@b@import com.google.common.io.ByteProcessor;@b@import com.google.common.io.ByteStreams;@b@import java.net.URI;@b@import java.util.Set;@b@import java.util.regex.Matcher;@b@import java.util.regex.Pattern;@b@import javax.annotation.Resource;@b@import javax.inject.Inject;@b@import javax.inject.Named;@b@import javax.inject.Singleton;@b@import org.jclouds.crypto.Crypto;@b@import org.jclouds.crypto.Macs;@b@import org.jclouds.date.TimeStamp;@b@import org.jclouds.domain.Credentials;@b@import org.jclouds.http.HttpException;@b@import org.jclouds.http.HttpRequest;@b@import org.jclouds.http.HttpRequest.Builder;@b@import org.jclouds.http.HttpRequestFilter;@b@import org.jclouds.http.HttpUtils;@b@import org.jclouds.http.internal.SignatureWire;@b@import org.jclouds.io.MutableContentMetadata;@b@import org.jclouds.io.Payload;@b@import org.jclouds.logging.Logger;@b@import org.jclouds.util.Patterns;@b@import org.jclouds.util.Strings2;@b@@b@@Singleton@b@public class SignRequest@b@  implements HttpRequestFilter@b@{@b@  private final SignatureWire signatureWire;@b@  private final Supplier<Credentials> creds;@b@  private final javax.inject.Provider<String> timeStampProvider;@b@  private final Crypto crypto;@b@  private final HttpUtils utils;@b@@b@  @Resource@b@  Logger logger = Logger.NULL;@b@@b@  @Resource@b@  @Named("jclouds.signature")@b@  Logger signatureLog = Logger.NULL;@b@@b@  @Inject@b@  public SignRequest(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds, @TimeStamp javax.inject.Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils)@b@  {@b@    this.signatureWire = signatureWire;@b@    this.creds = creds;@b@    this.timeStampProvider = timeStampProvider;@b@    this.crypto = crypto;@b@    this.utils = utils;@b@  }@b@@b@  public HttpRequest filter(HttpRequest request) throws HttpException@b@  {@b@    ImmutableMap.Builder builder = ImmutableMap.builder();@b@    builder.put("x-emc-uid", ((Credentials)this.creds.get()).identity);@b@    String date = (String)this.timeStampProvider.get();@b@    builder.put("Date", date);@b@    if (request.getHeaders().containsKey("x-emc-date"))@b@      builder.put("x-emc-date", date);@b@    request = ((HttpRequest.Builder)request.toBuilder().replaceHeaders(Multimaps.forMap(builder.build()))).build();@b@    String signature = calculateSignature(createStringToSign(request));@b@    request = ((HttpRequest.Builder)request.toBuilder().replaceHeader("x-emc-signature", new String[] { signature })).build();@b@    this.utils.logRequest(this.signatureLog, request, "<<");@b@    return request;@b@  }@b@@b@  public String createStringToSign(HttpRequest request) {@b@    this.utils.logRequest(this.signatureLog, request, ">>");@b@    StringBuilder buffer = new StringBuilder();@b@@b@    appendMethod(request, buffer);@b@    appendPayloadMetadata(request, buffer);@b@    appendHttpHeaders(request, buffer);@b@    appendCanonicalizedResource(request, buffer);@b@    appendCanonicalizedHeaders(request, buffer);@b@    if (this.signatureWire.enabled())@b@      this.signatureWire.output(buffer.toString());@b@    return buffer.toString();@b@  }@b@@b@  private String calculateSignature(String toSign) {@b@    String signature = signString(toSign);@b@    if (this.signatureWire.enabled())@b@      this.signatureWire.input(Strings2.toInputStream(signature));@b@    return signature; }@b@@b@  public String signString(String toSign) {@b@    ByteProcessor hmacSHA1;@b@    try {@b@      hmacSHA1 = Macs.asByteProcessor(this.crypto.hmacSHA1(BaseEncoding.base64().decode(((Credentials)this.creds.get()).credential)));@b@      return BaseEncoding.base64().encode((byte[])ByteStreams.readBytes(Strings2.toInputStream(toSign), hmacSHA1));@b@    } catch (Exception e) {@b@      throw new HttpException("error signing request", e);@b@    }@b@  }@b@@b@  private void appendMethod(HttpRequest request, StringBuilder toSign) {@b@    toSign.append(request.getMethod()).append("\n");@b@  }@b@@b@  private void appendCanonicalizedHeaders(HttpRequest request, StringBuilder toSign)@b@  {@b@    Set headers = Sets.newTreeSet(request.getHeaders().keySet());@b@    for (String header : headers)@b@      if ((header.startsWith("x-emc-")) && (!(header.equals("x-emc-signature"))))@b@      {@b@        toSign.append(header.toLowerCase()).append(":");@b@@b@        for (String value : request.getHeaders().get(header)) {@b@          value = value.replace("  ", " ");@b@          value = Patterns.NEWLINE_PATTERN.matcher(value).replaceAll("");@b@          toSign.append(value).append(' ');@b@        }@b@        toSign.deleteCharAt(toSign.lastIndexOf(" "));@b@@b@        toSign.append("\n");@b@      }@b@@b@@b@    if (toSign.charAt(toSign.length() - 1) == '\n')@b@      toSign.deleteCharAt(toSign.length() - 1);@b@  }@b@@b@  private void appendPayloadMetadata(HttpRequest request, StringBuilder buffer) {@b@    buffer.append(Strings.nullToEmpty((request.getPayload() == null) ? null : request.getPayload().getContentMetadata().getContentType())).append("\n");@b@  }@b@@b@  @VisibleForTesting@b@  void appendHttpHeaders(HttpRequest request, StringBuilder toSign)@b@  {@b@    toSign.append(HttpUtils.nullToEmpty(request.getHeaders().get("Range")).toLowerCase()).append("\n");@b@@b@    toSign.append(request.getFirstHeaderOrNull("Date")).append("\n");@b@  }@b@@b@  @VisibleForTesting@b@  void appendCanonicalizedResource(HttpRequest request, StringBuilder toSign)@b@  {@b@    toSign.append(request.getEndpoint().getRawPath().toLowerCase()).append("\n");@b@  }@b@}
<<热门下载>>