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.rest.arg;
018
019import static org.apache.juneau.commons.utils.Utils.*;
020
021import org.apache.juneau.commons.reflect.*;
022import org.apache.juneau.cp.*;
023import org.apache.juneau.rest.*;
024import org.apache.juneau.rest.annotation.*;
025
026/**
027 * Resolves method parameters on {@link RestOp}-annotated Java methods by retrieving them by type from the REST object bean store.
028 *
029 * <p>
030 * The parameter value is resolved using:
031 * <p class='bjava'>
032 *    <jv>opSession</jv>
033 *       .{@link RestOpSession#getBeanStore() getBeanStore}()
034 *       .{@link BeanStore#getBean(Class) getBean}(<jv>type</jv>);
035 * </p>
036 *
037 * <p>
038 * This is the default parameter resolver if no other applicable parameter resolvers could be found.
039 *
040 * <h5 class='section'>See Also:</h5><ul>
041 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JavaMethodParameters">Java Method Parameters</a>
042 * </ul>
043 */
044public class DefaultArg implements RestOpArg {
045
046   /**
047    * Static creator.
048    *
049    * @param paramInfo The Java method parameter being resolved.
050    * @return A new {@link DefaultArg}, never <jk>null</jk>.
051    */
052   public static DefaultArg create(ParameterInfo paramInfo) {
053      return new DefaultArg(paramInfo);
054   }
055
056   private final Class<?> type;
057   private final String qualifier;
058
059   private final ParameterInfo paramInfo;
060
061   /**
062    * Constructor.
063    *
064    * @param paramInfo The Java method parameter being resolved.
065    */
066   protected DefaultArg(ParameterInfo paramInfo) {
067      this.type = paramInfo.getParameterType().inner();
068      this.paramInfo = paramInfo;
069      this.qualifier = paramInfo.getResolvedQualifier();
070   }
071
072   @Override /* Overridden from RestOpArg */
073   public Object resolve(RestOpSession opSession) throws Exception {
074      return opSession.getBeanStore().getBean(type, qualifier).orElseThrow(() -> new ArgException(paramInfo, "Could not resolve bean type {0}", cn(type)));
075   }
076}