001 /**
002 * $Id: ClasspathHelper.java,v 1.4 2011/07/09 21:43:22 oboehm Exp $
003 *
004 * Copyright (c) 2009 by Oliver Boehm
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 *
018 * (c)reated 27.07.2009 by oliver (ob@oasd.de)
019 */
020
021 package patterntesting.runtime.util;
022
023 import java.net.*;
024
025 import org.apache.commons.lang.StringUtils;
026 import org.slf4j.*;
027
028 /**
029 * This class contains some helper classes which are used inside
030 * ClasspathMonitor <b>and</b> ClasspathDigger.
031 * Some of the methods were formerly placed in ClasspathMonitor but also
032 * needed by ClasspathDigger. To avoid dependencies from ClasspathDigger to
033 * ClasspathMonitor the common methods were moved to this class here.
034 *
035 * @author oliver
036 * @since 27.07.2009
037 * @version $Revision: 1.4 $
038 */
039 public final class ClasspathHelper {
040
041 private static final Logger log = LoggerFactory.getLogger(ClasspathHelper.class);
042
043 /** to avoid instantiation */
044 private ClasspathHelper() {}
045
046 /**
047 * Don't use @ProfileMe here! This method is also used when
048 * ProfileStatistic is set up!
049 *
050 * @param path
051 * e.g. "jar:file:/a/b/c.jar!/d/e.class
052 * @param resource
053 * e.g. "/d/e.class"
054 * @return e.g. "jar:file:/a/b/c.jar"
055 */
056 public static URI getParent(final URI path, final String resource) {
057 String p = removeTrailingSlash(path.toString());
058 String res = removeTrailingSlash(resource);
059 String parent = StringUtils.removeEnd(p, res);
060 parent = removeTrailingSlash(parent);
061 if (parent.endsWith("!")) {
062 parent = parent.substring(0, (parent.length() - 1));
063 }
064 try {
065 return new URI(parent);
066 } catch (URISyntaxException canthappen) {
067 log.error("can't extract " + resource + " from " + path,
068 canthappen);
069 return path;
070 }
071 }
072
073 private static String removeTrailingSlash(final String s) {
074 if (s.endsWith("/") || s.endsWith("\\")) {
075 return s.substring(0, (s.length() - 1));
076 }
077 return s;
078 }
079
080 /**
081 * Gets the parent of the given class.
082 *
083 * @param path
084 * e.g. "jar:file:/a/b/c.jar!/d/e.class
085 * @param clazz
086 * e.gl. "d.e.class"
087 * @return e.g. "jar:file:/a/b/c.jar"
088 */
089 public static URI getParent(final URI path, final Class<?> clazz) {
090 String resource = Converter.toResource(clazz);
091 return getParent(path, resource);
092 }
093
094 }