001/** 002 * Copyright (C) 2006-2025 Talend Inc. - www.talend.com 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.talend.sdk.component.runtime.manager.service.http; 017 018import java.util.Collection; 019import java.util.Map; 020import java.util.Optional; 021import java.util.function.BiFunction; 022import java.util.function.Function; 023 024import org.talend.sdk.component.api.service.http.Configurer; 025 026import lombok.AllArgsConstructor; 027 028@AllArgsConstructor 029public class HttpRequestCreator implements BiFunction<String, Object[], HttpRequest> { 030 031 private final Function<Object[], String> httpMethodProvider; 032 033 private final Function<Object[], String> urlProvide; 034 035 private final Function<Object[], String> baseProvider; 036 037 private final String pathTemplate; 038 039 private final BiFunction<String, Object[], String> pathProvider; 040 041 private final Function<Object[], Collection<String>> queryParamsProvider; 042 043 private final Function<Object[], Map<String, String>> headersProvider; 044 045 private final BiFunction<String, Object[], Optional<byte[]>> payloadProvider; 046 047 private final Configurer configurer; 048 049 private final Map<String, Function<Object[], Object>> configurerOptions; 050 051 @Override 052 public HttpRequest apply(final String base, final Object[] params) { 053 return new HttpRequest(buildUrl(base, params), httpMethodProvider.apply(params), 054 queryParamsProvider.apply(params), headersProvider.apply(params), configurer, configurerOptions, 055 payloadProvider, params, null); 056 } 057 058 private String buildUrl(final String base, final Object[] params) { 059 if (urlProvide == null) { 060 final String path = pathProvider.apply(pathTemplate, params); 061 final String realBase = this.baseProvider != null ? this.baseProvider.apply(params) : base; 062 return this.appendPaths(realBase, path); 063 } 064 return pathProvider.apply(urlProvide.apply(params), params); 065 } 066 067 private String appendPaths(final String p1, final String p2) { 068 if (p1.endsWith("/") && p2.startsWith("/")) { 069 return p1 + p2.substring(1); 070 } 071 if (p1.endsWith("/") || p1.isEmpty() || p2.startsWith("/") || p2.isEmpty()) { 072 return p1 + p2; 073 } 074 return p1 + "/" + p2; 075 } 076}