1 /*
   2  * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  */
  24 package java.net.http;
  25 
  26 import java.util.concurrent.Semaphore;
  27 
  28 /**
  29  * Connection or stream blocking flow control window.
  30  */
  31 class WindowControl {
  32 
  33     final Semaphore window;
  34 
  35     WindowControl() {
  36         this(0);
  37     }
  38 
  39     WindowControl(int intialPermits) {
  40         this.window = new Semaphore(intialPermits);
  41     }
  42 
  43     void update(int permits) {
  44         /* TODO
  45             RFC-7540 says:
  46             A sender MUST NOT allow a flow-control window to exceed 2^31-1
  47             octets.  If a sender receives a WINDOW_UPDATE that causes a flow-
  48             control window to exceed this maximum, it MUST terminate either the
  49             stream or the connection, as appropriate.  For streams, the sender
  50             sends a RST_STREAM with an error code of FLOW_CONTROL_ERROR; for the
  51             connection, a GOAWAY frame with an error code of FLOW_CONTROL_ERROR
  52             is sent.
  53          */
  54         if (permits > 0) {
  55             window.release(permits);
  56         }
  57     }
  58 
  59     void acquire(int permits) throws InterruptedException {
  60         if (permits > 0) {
  61             window.acquire(permits);
  62         }
  63     }
  64 
  65     int available() {
  66         return window.availablePermits();
  67     }
  68 }