001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. 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,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied. See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.commons.weaver.model;
020
021import java.util.Collections;
022import java.util.concurrent.ConcurrentNavigableMap;
023import java.util.concurrent.ConcurrentSkipListMap;
024
025/**
026 * {@link Weavable} {@link Package}.
027 */
028public class WeavablePackage extends Weavable<WeavablePackage, Package> {
029
030    private final ConcurrentNavigableMap<String, WeavableClass<?>> clazzes =
031        new ConcurrentSkipListMap<String, WeavableClass<?>>();
032
033    /**
034     * Create a new {@link WeavablePackage} instance.
035     * @param target package
036     */
037    public WeavablePackage(final Package target) {
038        super(target);
039    }
040
041    /**
042     * Get a {@link WeavableClass} representing {@code cls}.
043     * @param cls to wrap
044     * @param <T> generic type of {@code cls}
045     * @return {@link WeavableClass}
046     */
047    public synchronized <T> WeavableClass<T> getWeavable(final Class<T> cls) {
048        final String key = cls.getName();
049        if (clazzes.containsKey(key)) {
050            @SuppressWarnings("unchecked")
051            final WeavableClass<T> result = (WeavableClass<T>) clazzes.get(key);
052            return result;
053        }
054        final WeavableClass<T> result = new WeavableClass<T>(cls, this);
055        @SuppressWarnings("unchecked")
056        final WeavableClass<T> faster = (WeavableClass<T>) clazzes.putIfAbsent(key, result);
057        return faster == null ? result : faster;
058    }
059
060    /**
061     * Get enclosed {@link WeavableClass}es.
062     * @return {@link Iterable}
063     */
064    public Iterable<WeavableClass<?>> getClasses() {
065        return Collections.unmodifiableCollection(clazzes.values());
066    }
067
068    /**
069     * Implement {@link Comparable}.
070     * @param arg0 {@link WeavablePackage} to compare against
071     * @return int per {@link Comparable#compareTo(Object)} contract
072     */
073    @Override
074    public int compareTo(final WeavablePackage arg0) {
075        return getTarget().getName().compareTo(arg0.getTarget().getName());
076    }
077
078}