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 */ 017 018package org.apache.commons.fileupload2.core; 019 020import java.util.Objects; 021import java.util.function.Function; 022import java.util.function.LongSupplier; 023 024public abstract class AbstractRequestContext<T> implements RequestContext { 025 026 /** 027 * Supplies the content length default. 028 */ 029 private final LongSupplier contentLengthDefault; 030 031 /** 032 * Supplies the content length string. 033 */ 034 private final Function<String, String> contentLengthString; 035 036 /** 037 * The request. 038 */ 039 private final T request; 040 041 /** 042 * Constructs a new instance. 043 * 044 * @param contentLengthString How to get the content length string. 045 * @param contentLengthDefault How to get the content length default. 046 * @param request The request. 047 */ 048 protected AbstractRequestContext(final Function<String, String> contentLengthString, final LongSupplier contentLengthDefault, final T request) { 049 this.contentLengthString = Objects.requireNonNull(contentLengthString, "contentLengthString"); 050 this.contentLengthDefault = Objects.requireNonNull(contentLengthDefault, "contentLengthDefault"); 051 this.request = Objects.requireNonNull(request, "request"); 052 } 053 054 /** 055 * Gets the content length of the request. 056 * 057 * @return The content length of the request. 058 */ 059 @Override 060 public long getContentLength() { 061 try { 062 return Long.parseLong(contentLengthString.apply(AbstractFileUpload.CONTENT_LENGTH)); 063 } catch (final NumberFormatException e) { 064 return contentLengthDefault.getAsLong(); 065 } 066 } 067 068 public T getRequest() { 069 return request; 070 } 071 072 /** 073 * Returns a string representation of this object. 074 * 075 * @return a string representation of this object. 076 */ 077 @Override 078 public String toString() { 079 return String.format("%s [ContentLength=%s, ContentType=%s]", getClass().getSimpleName(), getContentLength(), getContentType()); 080 } 081 082}