Line data Source code
1 : // Copyright (C) 2014 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.common; 16 : 17 : import static com.google.common.flogger.LazyArgs.lazy; 18 : import static com.google.gerrit.common.FileUtil.lastModified; 19 : import static java.util.stream.Collectors.joining; 20 : 21 : import com.google.common.collect.ComparisonChain; 22 : import com.google.common.collect.ImmutableList; 23 : import com.google.common.collect.Ordering; 24 : import com.google.common.flogger.FluentLogger; 25 : import java.io.IOException; 26 : import java.nio.file.DirectoryStream; 27 : import java.nio.file.Files; 28 : import java.nio.file.NoSuchFileException; 29 : import java.nio.file.Path; 30 : import java.util.List; 31 : 32 : public final class SiteLibraryLoaderUtil { 33 138 : private static final FluentLogger logger = FluentLogger.forEnclosingClass(); 34 : 35 : public static void loadSiteLib(Path libdir) { 36 : try { 37 138 : List<Path> jars = listJars(libdir); 38 138 : IoUtil.loadJARs(jars); 39 138 : logger.atFine().log("Loaded site libraries: %s", lazy(() -> jarList(jars))); 40 0 : } catch (IOException e) { 41 0 : logger.atSevere().withCause(e).log("Error scanning lib directory %s", libdir); 42 138 : } 43 138 : } 44 : 45 : private static String jarList(List<Path> jars) { 46 9 : return jars.stream().map(p -> p.getFileName().toString()).collect(joining(",")); 47 : } 48 : 49 : public static List<Path> listJars(Path dir) throws IOException { 50 138 : DirectoryStream.Filter<Path> filter = 51 : entry -> { 52 0 : String name = entry.getFileName().toString(); 53 0 : return (name.endsWith(".jar") || name.endsWith(".zip")) && Files.isRegularFile(entry); 54 : }; 55 15 : try (DirectoryStream<Path> jars = Files.newDirectoryStream(dir, filter)) { 56 15 : return new Ordering<Path>() { 57 : @Override 58 : public int compare(Path a, Path b) { 59 : // Sort by reverse last-modified time so newer JARs are first. 60 0 : return ComparisonChain.start() 61 0 : .compare(lastModified(b), lastModified(a)) 62 0 : .compare(a, b) 63 0 : .result(); 64 : } 65 15 : }.sortedCopy(jars); 66 138 : } catch (NoSuchFileException nsfe) { 67 138 : return ImmutableList.of(); 68 : } 69 : } 70 : 71 : private SiteLibraryLoaderUtil() {} 72 : }