001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.commons;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.lang.annotation.*;
022import java.util.*;
023
024import org.apache.juneau.commons.reflect.*;
025
026/**
027 * Defines an invalid usage of an annotation.
028 *
029 *
030 * @serial exclude
031 */
032public class InvalidAnnotationException extends BasicRuntimeException {
033
034   private static final long serialVersionUID = 1L;
035
036   /**
037    * Throws an {@link InvalidAnnotationException} if the specified method contains any of the specified annotations.
038    *
039    * @param onMethod The method to check.
040    * @param types The annotations to check for.
041    * @throws InvalidAnnotationException Annotation was used in an invalid location.
042    */
043   @SafeVarargs
044   public static void assertNoInvalidAnnotations(MethodInfo onMethod, Class<? extends Annotation>...types) throws InvalidAnnotationException {
045      // @formatter:off
046      Arrays.stream(types)
047         .map(t -> onMethod.getAnnotations(t).findFirst().map(AnnotationInfo::inner).orElse(null))
048         .filter(Objects::nonNull)
049         .findFirst()
050         .ifPresent(a -> {
051            throw new InvalidAnnotationException("@%s annotation cannot be used in a @%s bean.  Method='%s'", cns(a), cns(onMethod.getDeclaringClass()), onMethod);
052         });
053      // @formatter:on
054   }
055
056   /**
057    * Constructor.
058    *
059    * @param message Message.
060    * @param args Arguments.
061    */
062   public InvalidAnnotationException(String message, Object...args) {
063      super(message, args);
064   }
065
066   @Override /* Overridden from BasicRuntimeException */
067   public InvalidAnnotationException setMessage(String message, Object...args) {
068      super.setMessage(message, args);
069      return this;
070   }
071}