001/* 002 * Copyright (C) 2014 Jörg Prante 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.xbib.elasticsearch.plugin.jdbc.classloader.directory; 017 018import org.xbib.elasticsearch.plugin.jdbc.classloader.AbstractURLResourceLocation; 019import org.xbib.elasticsearch.plugin.jdbc.classloader.ResourceHandle; 020 021import java.io.File; 022import java.io.FileInputStream; 023import java.io.IOException; 024import java.net.MalformedURLException; 025import java.util.jar.Manifest; 026 027public class DirectoryResourceLocation extends AbstractURLResourceLocation { 028 029 private final File baseDir; 030 031 private boolean manifestLoaded = false; 032 033 private Manifest manifest; 034 035 public DirectoryResourceLocation(File baseDir) throws MalformedURLException { 036 super(baseDir.toURI().toURL()); 037 this.baseDir = baseDir; 038 } 039 040 @Override 041 public ResourceHandle getResourceHandle(String resourceName) { 042 File file = new File(baseDir, resourceName); 043 if (!file.exists() || !isLocal(file)) { 044 return null; 045 } 046 try { 047 return new DirectoryResourceHandle(resourceName, file, baseDir, getManifestSafe()); 048 } catch (MalformedURLException e) { 049 return null; 050 } 051 } 052 053 private boolean isLocal(File file) { 054 try { 055 String base = baseDir.getCanonicalPath(); 056 String relative = file.getCanonicalPath(); 057 return (relative.startsWith(base)); 058 } catch (IOException e) { 059 return false; 060 } 061 } 062 063 @Override 064 public Manifest getManifest() throws IOException { 065 if (!manifestLoaded) { 066 File manifestFile = new File(baseDir, "META-INF/MANIFEST.MF"); 067 if (manifestFile.isFile() && manifestFile.canRead()) { 068 FileInputStream in = null; 069 try { 070 in = new FileInputStream(manifestFile); 071 manifest = new Manifest(in); 072 } finally { 073 if (in != null) { 074 try { 075 in.close(); 076 } catch (Exception ignored) { 077 } 078 } 079 } 080 } 081 manifestLoaded = true; 082 } 083 return manifest; 084 } 085 086 private Manifest getManifestSafe() { 087 Manifest m = null; 088 try { 089 m = getManifest(); 090 } catch (IOException e) { 091 // ignore 092 } 093 return m; 094 } 095}