View Javadoc
1   /*
2    * Copyright 2015 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty5.example.http2.tiles;
17  
18  import io.netty5.buffer.api.Buffer;
19  
20  import java.io.IOException;
21  import java.util.HashMap;
22  import java.util.Map;
23  
24  import static io.netty5.example.http2.Http2ExampleUtil.toBuffer;
25  
26  /**
27   * Caches the images to avoid reading them every time from the disk.
28   */
29  public final class ImageCache {
30  
31      public static ImageCache INSTANCE = new ImageCache();
32  
33      private final Map<String, Buffer> imageBank = new HashMap<>(200);
34  
35      private ImageCache() {
36          init();
37      }
38  
39      public static String name(int x, int y) {
40          return "tile-" + y + "-" + x + ".jpeg";
41      }
42  
43      public Buffer image(int x, int y) {
44          return imageBank.get(name(x, y)).copy(true);
45      }
46  
47      private void init() {
48          for (int y = 0; y < 10; y++) {
49              for (int x = 0; x < 20; x++) {
50                  try {
51                      String name = name(x, y);
52                      Buffer fileBytes = toBuffer(getClass().getResourceAsStream(name)).makeReadOnly();
53                      imageBank.put(name, fileBytes);
54                  } catch (IOException e) {
55                      e.printStackTrace();
56                  }
57              }
58          }
59      }
60  }