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