2 * Copyright (c) 2016 Cisco and/or its affiliates.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package io.fd.vpp.jvpp;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.nio.file.Files;
22 import java.nio.file.Path;
23 import java.nio.file.StandardCopyOption;
24 import java.nio.file.attribute.PosixFilePermission;
25 import java.nio.file.attribute.PosixFilePermissions;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
31 * Utility class for loading JNI libraries.
33 public final class NativeLibraryLoader {
35 private static final Logger LOG = Logger.getLogger(NativeLibraryLoader.class.getName());
37 private NativeLibraryLoader() {
38 throw new UnsupportedOperationException("This utility class cannot be instantiated.");
42 * Loads JNI library using class loader of the given class.
44 * @param libName name of the library to be loaded
46 public static void loadLibrary(final String libName, final Class clazz) throws IOException {
47 java.util.Objects.requireNonNull(libName, "libName should not be null");
48 java.util.Objects.requireNonNull(clazz, "clazz should not be null");
49 try (final InputStream is = clazz.getResourceAsStream('/' + libName)) {
51 throw new IOException("Failed to open library resource " + libName);
53 loadStream(libName, is);
57 private static void loadStream(final String libName, final InputStream is) throws IOException {
58 final Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");
59 final Path p = Files.createTempFile(libName, null, PosixFilePermissions.asFileAttribute(perms));
61 Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
62 Runtime.getRuntime().load(p.toString());
63 } catch (Exception e) {
64 throw new IOException("Failed to load library " + p, e);
67 Files.deleteIfExists(p);
68 } catch (IOException e) {
69 LOG.log(Level.WARNING, String.format("Failed to delete temporary file %s.", p), e);