001// Copyright 2021 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014package org.apache.tapestry5.http.internal.services;
015
016import java.util.Optional;
017
018import javax.servlet.http.HttpServletRequest;
019
020import org.apache.tapestry5.http.services.HttpRequestBodyConverter;
021import org.apache.tapestry5.http.services.RestSupport;
022
023/**
024 * Default {@linkplain RestSupport} implementation.
025 */
026public class RestSupportImpl implements RestSupport 
027{
028    
029    final private HttpServletRequest request;
030    
031    final private HttpRequestBodyConverter converter;
032
033    public RestSupportImpl(final HttpServletRequest request, final HttpRequestBodyConverter converter) 
034    {
035        super();
036        this.request = request;
037        this.converter = converter;
038    }
039
040    @Override
041    public boolean isHttpGet() 
042    {
043        return isMethod("GET");
044    }
045
046    @Override
047    public boolean isHttpPost() 
048    {
049        return isMethod("POST");
050    }
051
052    @Override
053    public boolean isHttpHead() 
054    {
055        return isMethod("HEAD");
056    }
057
058    @Override
059    public boolean isHttpPut() 
060    {
061        return isMethod("PUT");
062    }
063
064    @Override
065    public boolean isHttpDelete() 
066    {
067        return isMethod("DELETE");
068    }
069
070    @Override
071    public boolean isHttpPatch() 
072    {
073        return isMethod("PATCH");
074    }
075
076    private boolean isMethod(String string) 
077    {
078        return request.getMethod().equals(string);
079    }
080
081    @Override
082    public <T> Optional<T> getRequestBodyAs(Class<T> type) 
083    {
084        return Optional.ofNullable(converter.convert(request, type));
085    }
086    
087}