1 /*
2 * Copyright 2021 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
17 package io.netty.handler.codec.compression;
18
19 import io.netty.util.internal.PlatformDependent;
20 import io.netty.util.internal.logging.InternalLogger;
21 import io.netty.util.internal.logging.InternalLoggerFactory;
22
23 public final class Zstd {
24
25 private static final InternalLogger logger = InternalLoggerFactory.getInstance(Zstd.class);
26 private static final Throwable cause;
27
28 static {
29 Throwable t = null;
30
31 try {
32 Class.forName("com.github.luben.zstd.Zstd", false,
33 PlatformDependent.getClassLoader(Zstd.class));
34 } catch (ClassNotFoundException e) {
35 t = e;
36 logger.debug(
37 "zstd-jni not in the classpath; Zstd support will be unavailable.");
38 }
39
40 // If in the classpath, try to load the native library and initialize zstd.
41 if (t == null) {
42 try {
43 com.github.luben.zstd.util.Native.load();
44 } catch (Throwable e) {
45 t = e;
46 logger.debug("Failed to load zstd-jni; Zstd support will be unavailable.", t);
47 }
48 }
49 cause = t;
50 }
51
52 /**
53 *
54 * @return true when zstd-jni is in the classpath
55 * and native library is available on this platform and could be loaded
56 */
57 public static boolean isAvailable() {
58 return cause == null;
59 }
60
61 /**
62 * Throws when zstd support is missing from the classpath or is unavailable on this platform
63 * @throws Throwable a ClassNotFoundException if zstd-jni is missing
64 * or a ExceptionInInitializerError if zstd native lib can't be loaded
65 */
66 public static void ensureAvailability() throws Throwable {
67 if (cause != null) {
68 throw cause;
69 }
70 }
71
72 /**
73 * Returns {@link Throwable} of unavailability cause
74 */
75 public static Throwable cause() {
76 return cause;
77 }
78
79 private Zstd() {
80 }
81 }