Coverage Report - com.jcabi.github.wire.CarefulWire
 
Classes in this File Line Coverage Branch Coverage Complexity
CarefulWire
86%
31/36
45%
11/24
2.6
 
 1  2
 /**
 2  
  * Copyright (c) 2013-2015, jcabi.com
 3  
  * All rights reserved.
 4  
  *
 5  
  * Redistribution and use in source and binary forms, with or without
 6  
  * modification, are permitted provided that the following conditions
 7  
  * are met: 1) Redistributions of source code must retain the above
 8  
  * copyright notice, this list of conditions and the following
 9  
  * disclaimer. 2) Redistributions in binary form must reproduce the above
 10  
  * copyright notice, this list of conditions and the following
 11  
  * disclaimer in the documentation and/or other materials provided
 12  
  * with the distribution. 3) Neither the name of the jcabi.com nor
 13  
  * the names of its contributors may be used to endorse or promote
 14  
  * products derived from this software without specific prior written
 15  
  * permission.
 16  
  *
 17  
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 18  
  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
 19  
  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 20  
  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 21  
  * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 22  
  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 23  
  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 24  
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 25  
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 26  
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 27  
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 28  
  * OF THE POSSIBILITY OF SUCH DAMAGE.
 29  
  */
 30  
 package com.jcabi.github.wire;
 31  
 
 32  
 import com.jcabi.aspects.Immutable;
 33  
 import com.jcabi.http.Request;
 34  
 import com.jcabi.http.Response;
 35  
 import com.jcabi.http.Wire;
 36  
 import com.jcabi.log.Logger;
 37  
 import java.io.IOException;
 38  
 import java.io.InputStream;
 39  
 import java.util.Collection;
 40  
 import java.util.List;
 41  
 import java.util.Map;
 42  
 import java.util.concurrent.TimeUnit;
 43  
 import javax.validation.constraints.NotNull;
 44  
 import lombok.EqualsAndHashCode;
 45  
 import lombok.ToString;
 46  
 
 47  
 /**
 48  
  * Wire that waits if number of remaining request per hour is less than
 49  
  * a given threshold.
 50  
  *
 51  
  * <p>Github sets following headers in each response:
 52  
  * {@code X-RateLimit-Limit}, {@code X-RateLimit-Remaining}, and
 53  
  * {@code X-RateLimit-Reset}. If {@code X-RateLimit-Remaining} is
 54  
  * less than a given threshold, {@code CarefulWire} will sleep until a time
 55  
  * specified in the {@code X-RateLimit-Reset} header. For further information
 56  
  * about the Github rate limiting see
 57  
  * <a href="http://developer.github.com/v3/#rate-limiting">API
 58  
  * documentation</a>.
 59  
  *
 60  
  * <p>You can use {@code CarefulWire} with a {@link com.jcabi.github.Github}
 61  
  * object:
 62  
  * <pre>
 63  
  * {@code
 64  
  * Github github = new RtGithub(
 65  
  *     new RtGithub().entry().through(CarefulWire.class, 50)
 66  
  * );
 67  
  * }
 68  
  * </pre>
 69  
  *
 70  
  * @author Alexander Sinyagin (sinyagin.alexander@gmail.com)
 71  
  * @version $Id$
 72  
  */
 73  
 @Immutable
 74  0
 @ToString
 75  0
 @EqualsAndHashCode(of = { "origin", "threshold" })
 76  
 @SuppressWarnings("PMD.AvoidDuplicateLiterals")
 77  
 public final class CarefulWire implements Wire {
 78  
 
 79  
     /**
 80  
      * Original wire.
 81  
      */
 82  
     private final transient Wire origin;
 83  
 
 84  
     /**
 85  
      * Threshold of number of remaining requests, below which requests are
 86  
      * blocked until reset.
 87  
      */
 88  
     private final transient int threshold;
 89  
 
 90  
     /**
 91  
      * Public ctor.
 92  
      *
 93  
      * @param wire Original wire
 94  
      * @param thrshld Threshold of number of remaining requests, below which
 95  
      *  requests are blocked until reset
 96  
      */
 97  
     public CarefulWire(@NotNull(message = "wire can't be NULL")
 98  6
         final Wire wire, final int thrshld) {
 99  6
         this.origin = wire;
 100  6
         this.threshold = thrshld;
 101  6
     }
 102  
 
 103  
     /**
 104  
      * {@inheritDoc}
 105  
      * @checkstyle ParameterNumber (6 lines)
 106  
      */
 107  
     @Override
 108  
     @NotNull(message = "response can't be NULL")
 109  
     public Response send(
 110  
         @NotNull(message = "req can't be NULL") final Request req,
 111  
         @NotNull(message = "home can't be NULL") final String home,
 112  
         @NotNull(message = "method can't be NULL")final String method,
 113  
         @NotNull(message = "headers can't be NULL")
 114  
         final Collection<Map.Entry<String, String>> headers,
 115  
         @NotNull(message = "content can't be NULL")
 116  
         final InputStream content
 117  
     ) throws IOException {
 118  8
         final Response resp = this.origin
 119  
             .send(req, home, method, headers, content);
 120  8
         final int remaining = this.remainingHeader(resp);
 121  8
         if (remaining < this.threshold) {
 122  4
             final long reset = this.resetHeader(resp);
 123  4
             final long now = TimeUnit.MILLISECONDS
 124  
                 .toSeconds(System.currentTimeMillis());
 125  4
             if (reset > now) {
 126  2
                 final long length = reset - now;
 127  2
                 Logger.info(
 128  
                     this,
 129  
                     // @checkstyle LineLength (1 line)
 130  
                     "Remaining number of requests per hour is less than %d. Waiting for %d seconds.",
 131  
                     this.threshold, length
 132  
                 );
 133  
                 try {
 134  2
                     TimeUnit.SECONDS.sleep(length);
 135  0
                 } catch (final InterruptedException ex) {
 136  0
                     Thread.currentThread().interrupt();
 137  0
                     throw new IllegalStateException(ex);
 138  2
                 }
 139  
             }
 140  
         }
 141  8
         return resp;
 142  
     }
 143  
 
 144  
     /**
 145  
      * Get the header with the given name from the response.
 146  
      * If there is no such header, returns null.
 147  
      * @param resp Response to get header from
 148  
      * @param headername Name of header to get
 149  
      * @return The value of the first header with the given name, or null.
 150  
      */
 151  
     private String headerOrNull(
 152  
         @NotNull(message = "response can't be NULL")
 153  
         final Response resp,
 154  
         @NotNull(message = "header name can't be NULL")
 155  
         final String headername) {
 156  12
         final List<String> values = resp.headers().get(headername);
 157  12
         String value = null;
 158  12
         if (values != null && !values.isEmpty()) {
 159  6
             value = values.get(0);
 160  
         }
 161  12
         return value;
 162  
     }
 163  
 
 164  
     /**
 165  
      * Returns the value of the X-RateLimit-Remaining header.
 166  
      * If there is no such header, returns Integer.MAX_VALUE (no rate limit).
 167  
      * @param resp Response to get header from
 168  
      * @return Number of requests remaining before the rate limit will be hit
 169  
      */
 170  
     private int remainingHeader(
 171  
         @NotNull(message = "response can't be NULL")
 172  
         final Response resp) {
 173  8
         final String remainingstr = this.headerOrNull(
 174  
             resp,
 175  
             "X-RateLimit-Remaining"
 176  
         );
 177  8
         int remaining = Integer.MAX_VALUE;
 178  8
         if (remainingstr != null) {
 179  4
             remaining = Integer.parseInt(remainingstr);
 180  
         }
 181  8
         return remaining;
 182  
     }
 183  
 
 184  
     /**
 185  
      * Returns the value of the X-RateLimit-Reset header.
 186  
      * If there is no such header, returns 0 (reset immediately).
 187  
      * @param resp Response to get header from
 188  
      * @return Timestamp (in seconds) at which the rate limit will reset
 189  
      */
 190  
     private long resetHeader(
 191  
         @NotNull(message = "response can't be NULL")
 192  
         final Response resp) {
 193  4
         final String resetstr = this.headerOrNull(resp, "X-RateLimit-Reset");
 194  4
         long reset = 0;
 195  4
         if (resetstr != null) {
 196  2
             reset = Long.parseLong(resetstr);
 197  
         }
 198  4
         return reset;
 199  
     }
 200  
 }