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 java.lang.reflect.*;
020
021import org.apache.juneau.http.annotation.*;
022import org.apache.juneau.commons.lang.*;
023import org.apache.juneau.commons.reflect.*;
024import org.apache.juneau.rest.*;
025import org.apache.juneau.rest.annotation.*;
026
027/**
028 * Resolves method parameters annotated with {@link StatusCode} on {@link RestOp}-annotated Java methods.
029 *
030 * <h5 class='section'>See Also:</h5><ul>
031 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JavaMethodParameters">Java Method Parameters</a>
032 * </ul>
033 */
034public class ResponseCodeArg implements RestOpArg {
035
036   private static final AnnotationProvider AP = AnnotationProvider.INSTANCE;
037
038   /**
039    * Static creator.
040    *
041    * @param paramInfo The Java method parameter being resolved.
042    * @return A new {@link ResponseCodeArg}, or <jk>null</jk> if the parameter is not annotated with {@link StatusCode}.
043    */
044   public static ResponseCodeArg create(ParameterInfo paramInfo) {
045      if (AP.has(StatusCode.class, paramInfo))
046         return new ResponseCodeArg(paramInfo);
047      return null;
048   }
049
050   private final Type type;
051
052   /**
053    * Constructor.
054    *
055    * @param paramInfo The Java method parameter being resolved.
056    */
057   protected ResponseCodeArg(ParameterInfo paramInfo) {
058      this.type = paramInfo.getParameterType().innerType();
059      var c = type instanceof Class ? (Class<?>)type : type instanceof ParameterizedType ? (Class<?>)((ParameterizedType)type).getRawType() : null;
060      if (c != Value.class || Value.getParameterType(type) != Integer.class)
061         throw new ArgException(paramInfo, "Type must be Value<Integer> on parameter annotated with @StatusCode annotation");
062   }
063
064   @Override /* Overridden from RestOpArg */
065   public Object resolve(RestOpSession opSession) throws Exception {
066      var v = new Value<>();
067      v.listener(o -> opSession.getResponse().setStatus(Integer.parseInt(o.toString())));
068      return v;
069   }
070}