index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/konduit/serving/konduit-serving-tensorflow-config/0.3.0/ai/konduit/serving/models/tensorflow
java-sources/ai/konduit/serving/konduit-serving-tensorflow-config/0.3.0/ai/konduit/serving/models/tensorflow/step/TensorflowConfigModuleInfo.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.models.tensorflow.step; import ai.konduit.serving.annotation.module.ModuleInfo; @ModuleInfo("konduit-serving-tensorflow-config") //TODO AB 2020/05/29 Need to add required dependencies - CPU/GPU public class TensorflowConfigModuleInfo { private TensorflowConfigModuleInfo(){} }
0
java-sources/ai/konduit/serving/konduit-serving-tensorrt/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-tensorrt/0.3.0/ai/konduit/serving/tensorrt/KonduitServingTensorrtJsonMapping.java
package ai.konduit.serving.tensorrt;import ai.konduit.serving.pipeline.api.serde.JsonSubType; import ai.konduit.serving.pipeline.api.serde.JsonSubTypesMapping; import ai.konduit.serving.pipeline.api.serde.JsonSubType; import java.util.ArrayList; import java.util.List; //GENERATED CLASS DO NOT EDIT public class KonduitServingTensorrtJsonMapping implements JsonSubTypesMapping { @Override public List<JsonSubType> getSubTypesMapping() { List<JsonSubType> l = new ArrayList<>(); return l; } }
0
java-sources/ai/konduit/serving/konduit-serving-tensorrt/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-tensorrt/0.3.0/ai/konduit/serving/tensorrt/TensorRTModuleInfo.java
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.tensorrt; import ai.konduit.serving.annotation.module.ModuleInfo; @ModuleInfo("konduit-serving-tensorrt") public class TensorRTModuleInfo { }
0
java-sources/ai/konduit/serving/konduit-serving-tensorrt/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-tensorrt/0.3.0/ai/konduit/serving/tensorrt/TensorRTRunner.java
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.tensorrt; import ai.konduit.serving.annotation.runner.CanRun; import ai.konduit.serving.pipeline.api.context.Context; import ai.konduit.serving.pipeline.api.data.Data; import ai.konduit.serving.pipeline.api.data.NDArray; import ai.konduit.serving.pipeline.api.step.PipelineStep; import ai.konduit.serving.pipeline.api.step.PipelineStepRunner; import com.google.common.primitives.Longs; import lombok.extern.slf4j.Slf4j; import org.bytedeco.javacpp.PointerPointer; import org.bytedeco.tensorrt.global.nvonnxparser; import org.bytedeco.tensorrt.nvinfer.*; import org.bytedeco.tensorrt.nvonnxparser.IParser; import org.nd4j.common.base.Preconditions; import org.nd4j.common.util.ArrayUtil; import org.nd4j.linalg.api.buffer.DataType; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import java.io.File; import java.util.LinkedHashMap; import java.util.Map; import static org.bytedeco.cuda.global.cudart.*; import static org.bytedeco.tensorrt.global.nvinfer.OptProfileSelector; import static org.bytedeco.tensorrt.global.nvinfer.createInferBuilder; import static org.bytedeco.tensorrt.global.nvparsers.shutdownProtobufLibrary; import static org.bytedeco.tensorrt.nvinfer.ILogger.Severity.kINFO; @CanRun(TensorRTStep.class) @Slf4j public class TensorRTRunner implements PipelineStepRunner { private ICudaEngine engine; private IBuilder builder; private TensorRTStep tensorRTStep; private TensorRTLogger tensorRTLogger; private INetworkDefinition iNetworkDefinition; private IParser iParser; private IBuilderConfig builderConfig; private IOptimizationProfile optimizationProfile; private Map<String,long[]> outputDimensions; public TensorRTRunner(TensorRTStep tensorRTStep) { this.tensorRTStep = tensorRTStep; Preconditions.checkNotNull(tensorRTStep.outputDimensions(),"Output dimensions missing!"); Preconditions.checkNotNull(tensorRTStep.outputNames(),"Missing output names!"); Preconditions.checkState(tensorRTStep.outputDimensions().size() == tensorRTStep.outputNames().size(),"Output names and output dimensions must be the same size. Output names size was " + tensorRTStep.outputNames().size() + " and output dimensions size was " + tensorRTStep.outputDimensions().size()); outputDimensions = new LinkedHashMap<>(); tensorRTStep.outputDimensions().forEach(input -> { outputDimensions.put(input.name(),input.dimensions()); }); init(); } static void CHECK(int status) { if (status != 0) { System.out.println("Cuda failure: " + status); throw new IllegalStateException("Failure with status " + status); } } private void init() { tensorRTLogger = new TensorRTLogger(); builder = createInferBuilder(tensorRTLogger); iNetworkDefinition = builder.createNetworkV2(tensorRTStep.batchSize()); iParser = nvonnxparser.createParser(iNetworkDefinition,tensorRTLogger); Preconditions.checkNotNull(tensorRTStep.modelUri(),"No model found!"); File newFile = new File(tensorRTStep.modelUri()); if(!newFile.exists()) { throw new IllegalStateException("Unable to find model file " + tensorRTStep.modelUri()); } if(!iParser.parseFromFile(newFile.getAbsolutePath(),kINFO.value)) { throw new IllegalStateException("Unable to parse onnx model from " + tensorRTStep.modelUri()); } builder.setMaxBatchSize(tensorRTStep.batchSize()); optimizationProfile = builder.createOptimizationProfile(); if(tensorRTStep.minDimensions() != null) { for(NamedDimension dimensionsForName : tensorRTStep.minDimensions()) { optimizationProfile.setDimensions(dimensionsForName.name(),OptProfileSelector.kMIN,dims32For(dimensionsForName.dimensions())); } } if(tensorRTStep.maxDimensions() != null) { for(NamedDimension dimensionsForName : tensorRTStep.maxDimensions()) { optimizationProfile.setDimensions(dimensionsForName.name(),OptProfileSelector.kMAX,dims32For(dimensionsForName.dimensions())); } } if(tensorRTStep.optimalDimensions() != null) { for(NamedDimension dimensionsForName : tensorRTStep.optimalDimensions()) { optimizationProfile.setDimensions(dimensionsForName.name(),OptProfileSelector.kOPT,dims32For(dimensionsForName.dimensions())); } } builderConfig = builder.createBuilderConfig(); builderConfig.setMaxWorkspaceSize(tensorRTStep.maxWorkspaceSize()); builderConfig.addOptimizationProfile(optimizationProfile); builder.buildSerializedNetwork(iNetworkDefinition,builderConfig); engine = builder.buildEngineWithConfig(iNetworkDefinition, builderConfig); Preconditions.checkNotNull(engine,"Failed to create cuda engine!"); } private Dims32 dims32For(long[] input) { //Dimensions is 1 + (batch size) input.length Dims32 dims32 = null; switch(input.length) { case 4: dims32 = new Dims4(); break; case 1: dims32 = new Dims2(); break; case 2: dims32 = new Dims3(); break; default: dims32 = new Dims32(); } for(int i = 0; i < input.length; i++) { dims32.d(i,(int) input[i]); } return dims32; } // Logger for GIE info/warning/errors static class TensorRTLogger extends ILogger { @Override public void log(Severity severity, String msg) { severity = severity.intern(); // suppress info-level messages if (severity == kINFO) return; switch (severity) { case kINTERNAL_ERROR: log.error("INTERNAL_ERROR: " + msg); break; case kERROR: log.error("INTERNAL_ERROR: " + msg); break; case kWARNING: log.warn("INTERNAL_ERROR: " + msg); break; case kINFO: log.info("INTERNAL_ERROR: " + msg); break; default: log.info("UNKNOWN: " + msg); break; } } } @Override public void close() { engine.destroy(); builder.destroy(); shutdownProtobufLibrary(); } @Override public PipelineStep getPipelineStep() { return tensorRTStep; } @Override public Data exec(Context ctx, Data data) { Data ret = Data.empty(); IExecutionContext iExecutionContext = engine.createExecutionContext(); PointerPointer buffers = new PointerPointer(tensorRTStep.inputNames().size() + tensorRTStep.outputNames().size()); INDArray firstInput = data.getNDArray(tensorRTStep.inputNames().get(0)).getAs(INDArray.class); long batchSize = firstInput.size(0); for(int i = 0; i < tensorRTStep.inputNames().size(); i++) { INDArray input = data.getNDArray(tensorRTStep.inputNames().get(i)).getAs(INDArray.class); long bytes = input.length() * input.dataType().width(); CHECK(cudaMalloc(buffers.position(i),bytes)); CHECK(cudaMemcpy(buffers.position(i).get(), input.data().pointer(), bytes, cudaMemcpyHostToDevice)); } Preconditions.checkState(tensorRTStep.outputNames().size() == tensorRTStep.outputDimensions().size()); for(int i = 0; i < tensorRTStep.outputNames().size(); i++) { long[] outputShape = outputDimensions.get(tensorRTStep.outputNames().get(i)); int idx = tensorRTStep.inputNames().size() + i; long bytes = ArrayUtil.prod(outputShape) * firstInput.data().getElementSize(); CHECK(cudaMalloc(buffers.position( idx), bytes)); } if(!iExecutionContext.executeV2(buffers.position(0))) { throw new IllegalStateException("Execution did not work"); } for(int i = 0; i < tensorRTStep.outputNames().size(); i++) { long[] outputShape = tensorRTStep.outputDimensions().get(i).dimensions(); INDArray output = Nd4j.create(Longs.concat(new long[]{batchSize},outputShape)).castTo(DataType.FLOAT); int idx = tensorRTStep.inputNames().size() + i; long bytes = output.length() * output.data().getElementSize(); CHECK(cudaMemcpy( output.data().pointer(), buffers.position( idx).get(), bytes, cudaMemcpyDeviceToHost)); ret.put(tensorRTStep.outputNames().get(i), NDArray.create(output)); } for(int i = 0; i < tensorRTStep.inputNames().size() + tensorRTStep.outputNames().size(); i++) { cudaFree(buffers.position(i).get()); } return ret; } }
0
java-sources/ai/konduit/serving/konduit-serving-tensorrt/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-tensorrt/0.3.0/ai/konduit/serving/tensorrt/TensorRTRunnerFactory.java
package ai.konduit.serving.tensorrt; import ai.konduit.serving.pipeline.api.step.PipelineStep; import ai.konduit.serving.pipeline.api.step.PipelineStepRunner; import ai.konduit.serving.pipeline.api.step.PipelineStepRunnerFactory; public class TensorRTRunnerFactory implements PipelineStepRunnerFactory { @Override public boolean canRun(PipelineStep step) { return step instanceof TensorRTStep; } @Override public PipelineStepRunner create(PipelineStep step) { return new TensorRTRunner((TensorRTStep) step); } }
0
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving/tensorrt/KonduitServingTensorrtConfigJsonMapping.java
package ai.konduit.serving.tensorrt;import ai.konduit.serving.pipeline.api.serde.JsonSubType; import ai.konduit.serving.pipeline.api.serde.JsonSubTypesMapping; import ai.konduit.serving.pipeline.api.serde.JsonSubType; import java.util.ArrayList; import java.util.List; //GENERATED CLASS DO NOT EDIT public class KonduitServingTensorrtConfigJsonMapping implements JsonSubTypesMapping { @Override public List<JsonSubType> getSubTypesMapping() { List<JsonSubType> l = new ArrayList<>(); l.add(new JsonSubType("TENSORRT", ai.konduit.serving.tensorrt.TensorRTStep.class, ai.konduit.serving.pipeline.api.step.PipelineStep.class)); return l; } }
0
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving/tensorrt/NamedDimension.java
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.tensorrt; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import org.nd4j.shade.jackson.annotation.JsonCreator; import org.nd4j.shade.jackson.annotation.JsonProperty; import java.io.Serializable; @Data @Builder @Accessors(fluent = true) @NoArgsConstructor public class NamedDimension implements Serializable { private String name; private long[] dimensions; @JsonCreator public NamedDimension(@JsonProperty("name") String name, @JsonProperty("dimensions") long[] dimensions) { this.name = name; this.dimensions = dimensions; } }
0
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving/tensorrt/NamedDimensionList.java
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.tensorrt; import org.nd4j.shade.jackson.annotation.JsonCreator; import java.util.ArrayList; public class NamedDimensionList extends ArrayList<NamedDimension> { @JsonCreator public NamedDimensionList() { } }
0
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving/tensorrt/TensorRTConfigModuleInfo.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.tensorrt; import ai.konduit.serving.annotation.module.ModuleInfo; @ModuleInfo("konduit-serving-tensorrt-config") public class TensorRTConfigModuleInfo { private TensorRTConfigModuleInfo(){ } }
0
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-tensorrt-config/0.3.0/ai/konduit/serving/tensorrt/TensorRTStep.java
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.tensorrt; import ai.konduit.serving.annotation.json.JsonName; import ai.konduit.serving.pipeline.api.step.PipelineStep; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import org.nd4j.shade.jackson.annotation.JsonProperty; import java.util.List; @Data @Accessors(fluent = true) @JsonName("TENSORRT") @NoArgsConstructor @Schema(description = "A pipeline step that configures a tensorrt library for executing models..") public class TensorRTStep implements PipelineStep { @Schema(description = "Specifies the location of a saved model file.") private String modelUri; @Schema(description = "A list of names of the input placeholders ( computation graph, with multiple inputs. Where values from the input data keys are mapped to " + "the computation graph inputs).") private List<String> inputNames; @Schema(description = "A list of names of the output placeholders (computation graph, with multiple outputs. Where the values of these output keys are mapped " + "from the computation graph output - INDArray[] to data keys).") private List<String> outputNames; @Schema(description = "The batch size for the runtime") private int batchSize; @Schema(description = "Whether to use fp16 or not") private boolean useFp16; @Schema(description = "The max workspace size to use") private long maxWorkspaceSize; @Schema(description = "The min expected dimensions to optimize for. When specifying the dimensions from the CLI, the named dimensions are separated by a ; with the dimension name and numbers specified as name=1,2,3 where 1,2,3 is a comma separated list of values representing the dimensions.") private NamedDimensionList minDimensions; @Schema(description = "The max expected dimensions to optimize for. When specifying the dimensions from the CLI, the named dimensions are separated by a ; with the dimension name and numbers specified as name=1,2,3 where 1,2,3 is a comma separated list of values representing the dimensions.") private NamedDimensionList maxDimensions; @Schema(description = "The optimal expected dimensions to optimize for. When specifying the dimensions from the CLI, the named dimensions are separated by a ; with the dimension name and numbers specified as name=1,2,3 where 1,2,3 is a comma separated list of values representing the dimensions.") private NamedDimensionList optimalDimensions; @Schema(description = "The output dimensions for each output, minus the batch size, eg: if an image is NCHW only include CHW. When specifying the dimensions from the CLI, the named dimensions are separated by a ; with the dimension name and numbers specified as name=1,2,3 where 1,2,3 is a comma separated list of values representing the dimensions.") private NamedDimensionList outputDimensions; public TensorRTStep(@JsonProperty("modelUri") String modelUri, @JsonProperty("inputNames") List<String> inputNames, @JsonProperty("outputNames") List<String> outputNames, @JsonProperty("batchSize") int batchSize, @JsonProperty("useFp16") boolean useFp16, @JsonProperty("maxWorkspaceSize") long maxWorkspaceSize, @JsonProperty("minDimensions") List<NamedDimension> minDimensions, @JsonProperty("maxDimensions") List<NamedDimension> maxDimensions, @JsonProperty("optimalDimensions") List<NamedDimension> optimalDimensions, @JsonProperty("outputDimensions") List<NamedDimension> outputDimensions) { this.modelUri = modelUri; this.inputNames = inputNames; this.outputNames = outputNames; this.batchSize = batchSize; this.useFp16 = useFp16; this.maxWorkspaceSize = maxWorkspaceSize; this.minDimensions = new NamedDimensionList(); if(minDimensions != null) this.minDimensions.addAll(minDimensions); this.maxDimensions = new NamedDimensionList(); if(maxDimensions != null) this.maxDimensions.addAll(maxDimensions); this.optimalDimensions = new NamedDimensionList(); if(optimalDimensions != null) this.optimalDimensions.addAll(optimalDimensions); this.outputDimensions = new NamedDimensionList(); if(outputDimensions != null) { this.outputDimensions.addAll(outputDimensions); } } }
0
java-sources/ai/konduit/serving/konduit-serving-tvm/0.3.0/ai/konduit/serving/models
java-sources/ai/konduit/serving/konduit-serving-tvm/0.3.0/ai/konduit/serving/models/tvm/KonduitServingTvmJsonMapping.java
package ai.konduit.serving.models.tvm;import ai.konduit.serving.pipeline.api.serde.JsonSubType; import ai.konduit.serving.pipeline.api.serde.JsonSubTypesMapping; import ai.konduit.serving.pipeline.api.serde.JsonSubType; import java.util.ArrayList; import java.util.List; //GENERATED CLASS DO NOT EDIT public class KonduitServingTvmJsonMapping implements JsonSubTypesMapping { @Override public List<JsonSubType> getSubTypesMapping() { List<JsonSubType> l = new ArrayList<>(); return l; } }
0
java-sources/ai/konduit/serving/konduit-serving-tvm/0.3.0/ai/konduit/serving/models
java-sources/ai/konduit/serving/konduit-serving-tvm/0.3.0/ai/konduit/serving/models/tvm/TVMModuleInfo.java
package ai.konduit.serving.models.tvm; import ai.konduit.serving.annotation.module.ModuleInfo; @ModuleInfo("konduit-serving-tvm") public class TVMModuleInfo { private TVMModuleInfo() {} }
0
java-sources/ai/konduit/serving/konduit-serving-tvm/0.3.0/ai/konduit/serving/models/tvm
java-sources/ai/konduit/serving/konduit-serving-tvm/0.3.0/ai/konduit/serving/models/tvm/step/TVMPipelineStepRunnerFactory.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.models.tvm.step; import ai.konduit.serving.pipeline.api.step.PipelineStep; import ai.konduit.serving.pipeline.api.step.PipelineStepRunner; import ai.konduit.serving.pipeline.api.step.PipelineStepRunnerFactory; import org.nd4j.common.base.Preconditions; public class TVMPipelineStepRunnerFactory implements PipelineStepRunnerFactory { @Override public boolean canRun(PipelineStep step) { return step instanceof TVMStep; } @Override public PipelineStepRunner create(PipelineStep step) { Preconditions.checkState(canRun(step), "Unable to run step of type: %s", step.getClass()); return new TVMRunner((TVMStep) step); } }
0
java-sources/ai/konduit/serving/konduit-serving-tvm/0.3.0/ai/konduit/serving/models/tvm
java-sources/ai/konduit/serving/konduit-serving-tvm/0.3.0/ai/konduit/serving/models/tvm/step/TVMRunner.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.models.tvm.step; import ai.konduit.serving.annotation.runner.CanRun; import ai.konduit.serving.pipeline.api.context.Context; import ai.konduit.serving.pipeline.api.data.Data; import ai.konduit.serving.pipeline.api.data.NDArray; import ai.konduit.serving.pipeline.api.data.ValueType; import ai.konduit.serving.pipeline.api.protocol.URIResolver; import ai.konduit.serving.pipeline.api.step.PipelineStep; import ai.konduit.serving.pipeline.api.step.PipelineStepRunner; import ai.konduit.serving.pipeline.impl.data.ValueNotFoundException; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.bytedeco.javacpp.Loader; import org.bytedeco.tvm.presets.tvm; import org.nd4j.common.base.Preconditions; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.tvm.runner.TvmRunner; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @Slf4j @CanRun(TVMStep.class) public class TVMRunner implements PipelineStepRunner { private final TVMStep step; private TvmRunner tvmRunner; static { //ensure native libraries get loaded Loader.load(tvm.class); } public TVMRunner(@NonNull TVMStep step) { this.step = step; if(!step.lazyInit()) { init(); } else { log.warn("Lazy initialization of tvm model specified. Model will be initialized first time pipeline step is executed."); } } @Override public void close() { tvmRunner.close(); } @Override public PipelineStep getPipelineStep() { return step; } @Override public Data exec(Context ctx, Data data) { if(tvmRunner == null) { log.info("Lazy initialization of model found. Initializing model on first run."); init(); } Preconditions.checkState(step.inputNames() != null, "TVMStep input array names are not set (null)"); Map<String,INDArray> input = new HashMap<>(); for (String s : step.inputNames()) { if(!data.has(s)){ throw new ValueNotFoundException( "Error in TVMStep: Input data does not have a value corresponding to TensorFlowStep.inputNames value \"" + s + "\" - data keys = " + data.keys()); } if(data.type(s) != ValueType.NDARRAY) { String listType = data.type(s) == ValueType.LIST ? data.listType(s).toString() : null; throw new ValueNotFoundException( "Error in TVMStep (" + name() + "): Input data value corresponding to TensorFlowStep.inputNames value \"" + s + "\" is not an NDArray type - is " + (listType == null ? data.type(s) : "List<" + listType + ">")); } NDArray arr = data.getNDArray(s); INDArray arr2 = arr.getAs(INDArray.class); input.put(s,arr2); } Data out = Data.empty(); List<String> outNames = step.outputNames(); Map<String, INDArray> exec = tvmRunner.exec(input); for(Map.Entry<String,INDArray> outputValues : exec.entrySet()) { if(!outNames.contains(outputValues.getKey())) { throw new IllegalStateException("Output names " + outNames + " did not contain value output from tvm " + outputValues.getKey() + " - please ensure the output names are the same as the target model being run."); } out.put(outputValues.getKey(),NDArray.create(outputValues.getValue())); } return out; } protected void init() { try { initHelper(); } catch (Throwable t) { throw new RuntimeException("Error loading TVM model", t); } } protected void initHelper() throws Exception { String uri = step.modelUri(); File origFile = URIResolver.getFile(uri); Preconditions.checkState(origFile.exists(), "Model file does not exist: " + uri); System.out.println("Files " + Arrays.toString(origFile.getParentFile().list()) + " with parent directory " + origFile.getParentFile().getAbsolutePath()); tvmRunner = TvmRunner.builder().modelUri(origFile.getAbsolutePath()).build(); } }
0
java-sources/ai/konduit/serving/konduit-serving-tvm-config/0.3.0/ai/konduit/serving/models/tvm
java-sources/ai/konduit/serving/konduit-serving-tvm-config/0.3.0/ai/konduit/serving/models/tvm/step/KonduitServingTvmConfigJsonMapping.java
package ai.konduit.serving.models.tvm.step;import ai.konduit.serving.pipeline.api.serde.JsonSubType; import ai.konduit.serving.pipeline.api.serde.JsonSubTypesMapping; import ai.konduit.serving.pipeline.api.serde.JsonSubType; import java.util.ArrayList; import java.util.List; //GENERATED CLASS DO NOT EDIT public class KonduitServingTvmConfigJsonMapping implements JsonSubTypesMapping { @Override public List<JsonSubType> getSubTypesMapping() { List<JsonSubType> l = new ArrayList<>(); l.add(new JsonSubType("TVM", ai.konduit.serving.models.tvm.step.TVMStep.class, ai.konduit.serving.pipeline.api.step.PipelineStep.class)); return l; } }
0
java-sources/ai/konduit/serving/konduit-serving-tvm-config/0.3.0/ai/konduit/serving/models/tvm
java-sources/ai/konduit/serving/konduit-serving-tvm-config/0.3.0/ai/konduit/serving/models/tvm/step/TVMConfigModuleInfo.java
package ai.konduit.serving.models.tvm.step; import ai.konduit.serving.annotation.module.ModuleInfo; @ModuleInfo("konduit-serving-tvm-config") public class TVMConfigModuleInfo { private TVMConfigModuleInfo() {} }
0
java-sources/ai/konduit/serving/konduit-serving-tvm-config/0.3.0/ai/konduit/serving/models/tvm
java-sources/ai/konduit/serving/konduit-serving-tvm-config/0.3.0/ai/konduit/serving/models/tvm/step/TVMStep.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.models.tvm.step; import ai.konduit.serving.annotation.json.JsonName; import ai.konduit.serving.pipeline.api.step.PipelineStep; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import lombok.experimental.Tolerate; import java.util.Arrays; import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor @Accessors(fluent = true) @JsonName("TVM") @Schema(description = "A pipeline step that configures a TVM model that is to be executed.") public class TVMStep implements PipelineStep { @Schema(description = "A list of names of the input placeholders.") private List<String> inputNames; @Schema(description = "A list of names of the output arrays - i.e., what should be predicted.") private List<String> outputNames; @Schema(description = "Uniform Resource Identifier of model") private String modelUri; @Schema(description = "Lazy initialization of the step. Useful when model is being created within the pipeline.") private boolean lazyInit; @Tolerate public TVMStep inputNames(String... inputNames) { return this.inputNames(Arrays.asList(inputNames)); } @Tolerate public TVMStep outputNames(String... outputNames) { return this.outputNames(Arrays.asList(outputNames)); } }
0
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving/vertx/KonduitServingVertxJsonMapping.java
package ai.konduit.serving.vertx;import ai.konduit.serving.pipeline.api.serde.JsonSubType; import ai.konduit.serving.pipeline.api.serde.JsonSubTypesMapping; import ai.konduit.serving.pipeline.api.serde.JsonSubType; import java.util.ArrayList; import java.util.List; //GENERATED CLASS DO NOT EDIT public class KonduitServingVertxJsonMapping implements JsonSubTypesMapping { @Override public List<JsonSubType> getSubTypesMapping() { List<JsonSubType> l = new ArrayList<>(); return l; } }
0
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving/vertx/VertxModuleInfo.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.vertx; import ai.konduit.serving.annotation.module.ModuleInfo; @ModuleInfo("konduit-serving-vertx") public class VertxModuleInfo { private VertxModuleInfo(){ } }
0
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving/vertx
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving/vertx/api/DeployKonduitServing.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.vertx.api; import ai.konduit.serving.pipeline.settings.constants.Constants; import ai.konduit.serving.pipeline.util.ObjectMappers; import ai.konduit.serving.vertx.config.InferenceConfiguration; import ai.konduit.serving.vertx.config.InferenceDeploymentResult; import ai.konduit.serving.vertx.config.ServerProtocol; import io.vertx.core.*; import io.vertx.core.impl.VertxImpl; import io.vertx.core.json.JsonObject; import io.vertx.core.spi.VerticleFactory; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.text.SimpleDateFormat; import java.util.EnumMap; import java.util.Map; import java.util.concurrent.TimeUnit; import static ai.konduit.serving.vertx.config.ServerProtocol.*; @Slf4j @NoArgsConstructor(access = AccessLevel.PRIVATE) public class DeployKonduitServing { public static final String SERVICE_PREFIX = "konduit"; public static final String INFERENCE_SERVICE_IDENTIFIER = SERVICE_PREFIX + ":ai.konduit.serving:inference"; protected static final Map<ServerProtocol, String> PROTOCOL_SERVICE_MAP = new EnumMap<>(ServerProtocol.class); static { ObjectMappers.json().setDateFormat(new SimpleDateFormat(Constants.DATE_FORMAT)); // Service classes that corresponds to the ServerProtocol enums PROTOCOL_SERVICE_MAP.put(HTTP, "ai.konduit.serving.vertx.protocols.http.verticle.InferenceVerticleHttp"); PROTOCOL_SERVICE_MAP.put(GRPC, "ai.konduit.serving.vertx.protocols.grpc.verticle.InferenceVerticleGrpc"); PROTOCOL_SERVICE_MAP.put(MQTT, "ai.konduit.serving.vertx.protocols.mqtt.verticle.InferenceVerticleMqtt"); PROTOCOL_SERVICE_MAP.put(KAFKA, "ai.konduit.serving.vertx.protocols.kafka.verticle.InferenceVerticleKafka"); } public static Vertx deploy(VertxOptions vertxOptions, DeploymentOptions deploymentOptions, InferenceConfiguration inferenceConfiguration, Handler<AsyncResult<InferenceDeploymentResult>> eventHandler) { Vertx vertx = Vertx.vertx(vertxOptions .setMaxEventLoopExecuteTime(60) .setMaxEventLoopExecuteTimeUnit(TimeUnit.SECONDS)); registerInferenceVerticleFactory(vertx); JsonObject jsonConfiguration; try { jsonConfiguration = new JsonObject(inferenceConfiguration.toJson()); } catch (Throwable throwable) { log.error("Failed while converting inference configuration to a json string." + "Possible causes could be missing classes for pipeline steps.", throwable); eventHandler.handle(Future.failedFuture(throwable)); vertx.close(); return vertx; } deploymentOptions.setConfig(jsonConfiguration); vertx.deployVerticle(INFERENCE_SERVICE_IDENTIFIER + ":" + inferenceConfiguration.protocol().name().toLowerCase(), deploymentOptions, handler -> { if (handler.failed()) { log.error("Unable to deploy server for configuration \n{}", jsonConfiguration.encodePrettily(), handler.cause()); if (eventHandler != null) { eventHandler.handle(Future.failedFuture(handler.cause())); } vertx.close(); } else { log.info("Deployed {} server with configuration \n{}", inferenceConfiguration.protocol(), jsonConfiguration.encodePrettily()); if (eventHandler != null) { VertxImpl vertxImpl = (VertxImpl) vertx; DeploymentOptions inferenceDeploymentOptions = vertxImpl.getDeployment(handler.result()).deploymentOptions(); eventHandler.handle(Future.succeededFuture( new InferenceDeploymentResult( inferenceDeploymentOptions.getConfig().getInteger("port"), handler.result() ))); } } }); return vertx; } public Map<ServerProtocol, String> getProtocolServiceMap() { return PROTOCOL_SERVICE_MAP; } public static void registerInferenceVerticleFactory(Vertx vertx) { vertx.registerVerticleFactory(new ServiceVerticleFactory(vertx)); } }
0
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving/vertx
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving/vertx/api/ServiceVerticleFactory.java
package ai.konduit.serving.vertx.api; import ai.konduit.serving.vertx.config.ServerProtocol; import io.vertx.core.Verticle; import io.vertx.core.Vertx; import io.vertx.core.spi.VerticleFactory; import org.apache.commons.lang3.StringUtils; import static ai.konduit.serving.vertx.api.DeployKonduitServing.PROTOCOL_SERVICE_MAP; import static ai.konduit.serving.vertx.api.DeployKonduitServing.SERVICE_PREFIX; public class ServiceVerticleFactory implements VerticleFactory { private Vertx vertx; public ServiceVerticleFactory(Vertx vertx) { this.vertx = vertx; } @Override public String prefix() { return SERVICE_PREFIX; } @Override public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception { return createInferenceVerticleFromProtocolName(verticleName.substring(verticleName.lastIndexOf(':') + 1)); } private Verticle createInferenceVerticleFromProtocolName(String protocolName) throws Exception { ServerProtocol serverProtocol = ServerProtocol.valueOf(protocolName.toUpperCase()); if(PROTOCOL_SERVICE_MAP.containsKey(serverProtocol)) { try { return (Verticle) Thread.currentThread().getContextClassLoader() .loadClass(PROTOCOL_SERVICE_MAP.get(serverProtocol)) .getConstructor().newInstance(); } catch (ClassNotFoundException classNotFoundException) { vertx.close(); throw new IllegalStateException( String.format("Missing classes for protocol service %s. Make sure the binaries contain the '%s' module.", protocolName, "konduit-serving-" + serverProtocol.name().toLowerCase()) ); } } else { vertx.close(); throw new IllegalStateException( String.format("No inference service found for type: %s. Available service types are: [%s]", protocolName, StringUtils.join(PROTOCOL_SERVICE_MAP.keySet(), ", ") ) ); } } }
0
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving/vertx
java-sources/ai/konduit/serving/konduit-serving-vertx/0.3.0/ai/konduit/serving/vertx/verticle/InferenceVerticle.java
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.vertx.verticle; import ai.konduit.serving.pipeline.api.pipeline.Pipeline; import ai.konduit.serving.pipeline.api.pipeline.PipelineExecutor; import ai.konduit.serving.vertx.config.InferenceConfiguration; import ai.konduit.serving.pipeline.settings.DirectoryFetcher; import io.vertx.core.AbstractVerticle; import io.vertx.core.Promise; import io.vertx.core.impl.ContextInternal; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.nio.charset.StandardCharsets; @Slf4j public abstract class InferenceVerticle extends AbstractVerticle { protected ai.konduit.serving.pipeline.api.context.Context pipelineContext; protected InferenceConfiguration inferenceConfiguration; protected Pipeline pipeline; protected PipelineExecutor pipelineExecutor; protected void initialize() throws Exception { inferenceConfiguration = InferenceConfiguration.fromJson(context.config().encode()); pipeline = inferenceConfiguration.pipeline(); pipelineExecutor = pipeline.executor(); log.info("\n\n" + "####################################################################\n" + "# #\n" + "# | / _ \\ \\ | _ \\ | | _ _| __ __| | / | / #\n" + "# . < ( | . | | | | | | | . < . < #\n" + "# _|\\_\\ \\___/ _|\\_| ___/ \\__/ ___| _| _|\\_\\ _) _|\\_\\ _) #\n" + "# #\n" + "####################################################################\n"); log.info("Pending server start, please wait..."); } @Override public void stop(Promise<Void> stopPromise) { if (vertx != null) { vertx.close(handler -> { if(handler.succeeded()) { log.debug("Shut down server."); stopPromise.complete(); } else { stopPromise.fail(handler.cause()); } }); } else { stopPromise.complete(); } } protected long getPid() { return Long.parseLong(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]); } protected void saveInspectionDataIfRequired(long pid) { try { File processConfigFile = new File(DirectoryFetcher.getServersDataDir(), pid + ".data"); String inferenceConfigurationJson = ((ContextInternal) context).getDeployment() .deploymentOptions().getConfig().encodePrettily(); if(processConfigFile.exists()) { if(!FileUtils.readFileToString(processConfigFile, StandardCharsets.UTF_8).contains(inferenceConfigurationJson)) { FileUtils.writeStringToFile(processConfigFile, inferenceConfigurationJson, StandardCharsets.UTF_8); } } else { FileUtils.writeStringToFile(processConfigFile, inferenceConfigurationJson, StandardCharsets.UTF_8); log.info("Writing inspection data at '{}' with configuration: \n{}", processConfigFile.getAbsolutePath(), inferenceConfiguration.toJson()); } processConfigFile.deleteOnExit(); } catch (IOException exception) { log.error("Unable to save konduit server inspection information", exception); } } }
0
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx/KonduitServingVertxConfigJsonMapping.java
package ai.konduit.serving.vertx;import ai.konduit.serving.pipeline.api.serde.JsonSubType; import ai.konduit.serving.pipeline.api.serde.JsonSubTypesMapping; import ai.konduit.serving.pipeline.api.serde.JsonSubType; import java.util.ArrayList; import java.util.List; //GENERATED CLASS DO NOT EDIT public class KonduitServingVertxConfigJsonMapping implements JsonSubTypesMapping { @Override public List<JsonSubType> getSubTypesMapping() { List<JsonSubType> l = new ArrayList<>(); return l; } }
0
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx/VertxConfigModuleInfo.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.vertx; import ai.konduit.serving.annotation.module.ModuleInfo; @ModuleInfo("konduit-serving-vertx-config") public class VertxConfigModuleInfo { private VertxConfigModuleInfo(){ } }
0
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx/config/InferenceConfiguration.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.vertx.config; import ai.konduit.serving.pipeline.api.TextConfig; import ai.konduit.serving.pipeline.api.pipeline.Pipeline; import ai.konduit.serving.pipeline.util.ObjectMappers; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Data @Accessors(fluent=true) @NoArgsConstructor @AllArgsConstructor @Schema(description = "The main object that's used to configure the whole konduit serving pipeline and the server itself.") public class InferenceConfiguration implements Serializable, TextConfig { @Schema(description = "Server host", defaultValue = "localhost") private String host = "localhost"; @Schema(description = "Server port. 0 means that a random port will be selected.", defaultValue = "0") private int port = 0; @Schema(description = "Server port. 0 means that a random port will be selected.", defaultValue = "0") private boolean useSsl = false; @Schema(description = "Server port. 0 means that a random port will be selected.", defaultValue = "0") private String sslKeyPath = null; @Schema(description = "Server port. 0 means that a random port will be selected.", defaultValue = "0") private String sslCertificatePath = null; @Schema(description = "Server type.", defaultValue = "HTTP") private ServerProtocol protocol = ServerProtocol.HTTP; @Schema(description = "Static HTTP content root.", defaultValue = "static-content") private String staticContentRoot = "static-content"; @Schema(description = "Static HTTP content URL.", defaultValue = "/static-content") private String staticContentUrl = "/static-content"; @Schema(description = "Static HTTP content index page", defaultValue = "index.html") private String staticContentIndexPage = "/index.html"; @Schema(description = "Kafka related configuration.", defaultValue = "{}") private KafkaConfiguration kafkaConfiguration = new KafkaConfiguration(); @Schema(description = "Mqtt related configuration.", defaultValue = "{}") private MqttConfiguration mqttConfiguration = new MqttConfiguration(); @Schema(description = "List of custom endpoint class names that are configured to " + "provide custom endpoints functionality (fully qualified Java path - for example com.mycompany.MyEndpointsClass).") private List<String> customEndpoints = new ArrayList<>(); @Schema(description = "The main konduit serving pipeline configuration.") private Pipeline pipeline; public static InferenceConfiguration fromJson(String json) { return ObjectMappers.fromJson(json, InferenceConfiguration.class); } public static InferenceConfiguration fromYaml(String yaml){ return ObjectMappers.fromYaml(yaml, InferenceConfiguration.class); } }
0
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx/config/InferenceDeploymentResult.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.vertx.config; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class InferenceDeploymentResult { private int actualPort; private String deploymentId; }
0
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx/config/KafkaConfiguration.java
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.vertx.config; import ai.konduit.serving.pipeline.settings.constants.Constants; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @Data @Accessors(fluent=true) @NoArgsConstructor @AllArgsConstructor @Schema(description = "Kafka related configuration.") public class KafkaConfiguration { @Schema(description = "Whether to start an http server alongside the kafka server for some standard endpoints.", defaultValue = "true") private boolean startHttpServerForKafka = Constants.DEFAULT_START_HTTP_SERVER_FOR_KAFKA; @Schema(description = "Whether to start an http server alongside the kafka server for some standard endpoints.", defaultValue = Constants.DEFAULT_HTTP_KAFKA_HOST) private String httpKafkaHost = Constants.DEFAULT_HTTP_KAFKA_HOST; @Schema(description = "Whether to start an http server alongside the kafka server for some standard endpoints.", defaultValue = "0") private int httpKafkaPort = Constants.DEFAULT_HTTP_KAFKA_PORT; @Schema(description = "Topic name for the consumer.", defaultValue = Constants.DEFAULT_CONSUMER_TOPIC_NAME) private String consumerTopicName = Constants.DEFAULT_CONSUMER_TOPIC_NAME; @Schema(description = "Deserializer class for key that implements the <code>org.apache.kafka.common.serialization.Deserializer</code> interface.", defaultValue = Constants.DEFAULT_KAFKA_CONSUMER_KEY_DESERIALIZER_CLASS) private String consumerKeyDeserializerClass = Constants.DEFAULT_KAFKA_CONSUMER_KEY_DESERIALIZER_CLASS; @Schema(description = "Deserializer class for value that implements the <code>org.apache.kafka.common.serialization.Deserializer</code> interface.", defaultValue = Constants.DEFAULT_KAFKA_CONSUMER_VALUE_DESERIALIZER_CLASS) private String consumerValueDeserializerClass = Constants.DEFAULT_KAFKA_CONSUMER_VALUE_DESERIALIZER_CLASS; @Schema(description = "A unique string that identifies the consumer group this consumer belongs to. This property is required if the consumer uses either the group management functionality by using <code>subscribe(topic)</code> or the Kafka-based offset management strategy.", defaultValue = Constants.DEFAULT_CONSUMER_GROUP_ID) private String consumerGroupId = Constants.DEFAULT_CONSUMER_GROUP_ID; @Schema(description = "What to do when there is no initial offset in Kafka or if the current offset does not exist any more on the server (e.g. because that data has been deleted): <ul><li>earliest: automatically reset the offset to the earliest offset<li>latest: automatically reset the offset to the latest offset</li><li>none: throw exception to the consumer if no previous offset is found for the consumer's group</li><li>anything else: throw exception to the consumer.</li></ul>", defaultValue = Constants.DEFAULT_CONSUMER_AUTO_OFFSET_RESET) private String consumerAutoOffsetReset = Constants.DEFAULT_CONSUMER_AUTO_OFFSET_RESET; @Schema(description = "If true the consumer's offset will be periodically committed in the background.", defaultValue = Constants.DEFAULT_CONSUMER_AUTO_COMMIT) private String consumerAutoCommit = Constants.DEFAULT_CONSUMER_AUTO_COMMIT; @Schema(description = "Topic name for producer", defaultValue = Constants.DEFAULT_PRODUCER_TOPIC_NAME) private String producerTopicName = Constants.DEFAULT_PRODUCER_TOPIC_NAME; @Schema(description = "Serializer class for key that implements the <code>org.apache.kafka.common.serialization.Serializer</code> interface.", defaultValue = Constants.DEFAULT_KAFKA_PRODUCER_KEY_SERIALIZER_CLASS) private String producerKeySerializerClass = Constants.DEFAULT_KAFKA_PRODUCER_KEY_SERIALIZER_CLASS; @Schema(description = "Serializer class for value that implements the <code>org.apache.kafka.common.serialization.Serializer</code> interface.", defaultValue = Constants.DEFAULT_KAFKA_PRODUCER_VALUE_SERIALIZER_CLASS) private String producerValueSerializerClass = Constants.DEFAULT_KAFKA_PRODUCER_VALUE_SERIALIZER_CLASS; @Schema(description = "The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the " + " durability of records that are sent. The following settings are allowed: " + " <ul>" + " <li><code>acks=0</code> If set to zero then the producer will not wait for any acknowledgment from the" + " server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be" + " made that the server has received the record in this case, and the <code>retries</code> configuration will not" + " take effect (as the client won't generally know of any failures). The offset given back for each record will" + " always be set to <code>-1</code>." + " <li><code>acks=1</code> This will mean the leader will write the record to its local log but will respond" + " without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after" + " acknowledging the record but before the followers have replicated it then the record will be lost." + " <li><code>acks=all</code> This means the leader will wait for the full set of in-sync replicas to" + " acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica" + " remains alive. This is the strongest available guarantee. This is equivalent to the acks=-1 setting." + "</ul>", defaultValue = Constants.DEFAULT_PRODUCER_ACKS) private String producerAcks = Constants.DEFAULT_PRODUCER_ACKS; }
0
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx/config/MqttConfiguration.java
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.vertx.config; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @Data @Accessors(fluent=true) @NoArgsConstructor @Schema(description = "Mqtt configuration") public class MqttConfiguration { }
0
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx
java-sources/ai/konduit/serving/konduit-serving-vertx-config/0.3.0/ai/konduit/serving/vertx/config/ServerProtocol.java
/* * ****************************************************************************** * * Copyright (c) 2022 Konduit K.K. * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package ai.konduit.serving.vertx.config; import io.swagger.v3.oas.annotations.media.Schema; @Schema(description = "An enum that determines the server type. <br><br>" + "HTTP -> starts an http server, <br>" + "MQTT -> starts an mqtt server, <br>" + "GRPC -> start a grpc server, <br>" + "KAFKA -> connect to a kafka message queue.") public enum ServerProtocol { HTTP, MQTT, GRPC, KAFKA }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/Asset.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; /** * Object model for Asset elements */ @lombok.Data @lombok.ToString @lombok.EqualsAndHashCode @lombok.NoArgsConstructor @lombok.AllArgsConstructor @lombok.Builder @lombok.Getter @lombok.Setter public class Asset { @JsonProperty("name") String name; @JsonProperty("type") String type; @JsonProperty("size") Integer size; @JsonProperty("description") String description; @JsonProperty("url") String url; @JsonProperty("width") String width; @JsonProperty("height") String height; @JsonProperty("renditions") Map<String, AssetRendition> renditions; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/AssetRendition.java
/* * MIT License * * Copyright (c) 2019 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Object model for asset rendition */ @lombok.Data @lombok.NoArgsConstructor @lombok.AllArgsConstructor @lombok.Builder public class AssetRendition { @JsonProperty("rendition_id") String renditionId; @JsonProperty("preset_id") String presetId; @JsonProperty("width") String width; @JsonProperty("height") String height; @JsonProperty("query") String query; /** * Asset rendition ID * * @return rendition ID */ public String getRenditionId() { return renditionId; } void setRenditionId(String renditionId) { this.renditionId = renditionId; } /** * Asset rendition preset ID * * @return rendition preset ID */ public String getPresetId() { return presetId; } void setPresetId(String presetId) { this.presetId = presetId; } /** * Width of the asset rendition * * @return Width of the asset rendition */ public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } /** * Height of the asset rendition * * @return Height of the asset rendition */ public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } /** * Asset rendition query * * @return rendition query */ public String getQuery() { return query; } void setQuery(String query) { this.query = query; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/AssetsElement.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Object model for Assets elements. * * @see Asset * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Asset-element">Kontent.ai API reference - Asset</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class AssetsElement extends Element<List<Asset>> { static final String TYPE_VALUE = "asset"; /** * When used in content items, Asset elements can contain multiple assets. The value in the JSON response for an * Asset element consists of a list of {@link Asset} objects. * * @param value New value for this element's List of Assets. * @return This element's list of assets. */ @JsonProperty("value") List<Asset> value; public AssetsElement() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/AsyncCacheManager.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.databind.JsonNode; import java.util.List; import java.util.concurrent.CompletionStage; import org.thymeleaf.cache.ICacheManager; /** * Cache responses against the Kontent.ai Delivery API. * * @see AsyncCacheManager * @see DeliveryClient#setCacheManager(AsyncCacheManager) */ public interface AsyncCacheManager { /** * Returns the cached data or fetches the data and caches it before returning. * * @param url URL for retrieving data. * @return Returned data. */ CompletionStage<JsonNode> get(final String url); /** * Put the data to cache. * * @param url URL for retrieving the data. * @param jsonNode Plain data to cache. * @param containedContentItems Strongly typed data. * @return Status of the operation. */ CompletionStage put(final String url, JsonNode jsonNode, List<ContentItem> containedContentItems); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/BrokenLinkUrlResolver.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; /** * Interface to provide for rendering broken content item links in rich text. * <p> * An implementation of this can be provided to via * {@link DeliveryClient#setBrokenLinkUrlResolver(BrokenLinkUrlResolver)} to resolve links to a content item that are * not published. This is passed on to the {@link RichTextElementConverter} to update {@code href} attributes in links * when no {@code data-item-id} is available on the link. * <p> * This is a {@link FunctionalInterface} to simplify implementation. * <p> * For example, the following implementation will render {@code <a href="/404">Some text</a>}: * <pre>{@code * DeliveryClient deliveryClient = new DeliveryClient("02a70003-e864-464e-b62c-e0ede97deb8c"); * deliveryClient.setBrokenLinkUrlResolver(() -> "/404"); * }</pre> * * @see RichTextElementConverter * @see RichTextElement * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Linked-items-element"> * Kontent.ai API reference - Link to a content item</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Rich-text-element/links-single-object"> * Kontent.ai API reference - Rich text links</a> */ @FunctionalInterface public interface BrokenLinkUrlResolver { /** * Returns a String to be placed in the href attribute of any links to content items that are not published within * {@link RichTextElement}s. * * @return The String to place in the href attribute of any links to content items that are not published. */ String resolveBrokenLinkUrl(); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/CacheManager.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.databind.JsonNode; import java.util.List; /** * Interface to provide caching to the {@link DeliveryClient}. * <p> * An implementation of this can be provided via {@link DeliveryClient#setCacheManager(CacheManager)} and it is invoked * before every API request. It is expected to return a {@link JsonNode} representation of the API response. * <p> * It is up to the CacheManager to determine how to key it's cache, and how much it will introspect the JsonNode, * however due to varying operations that can be done with the {@link DeliveryParameterBuilder}, it is highly * recommended to key off the {@code requestUri}. * <p> * A CacheManager also can leverage notifications from Kontent's webhooks that can be sent when the project's * content is changed. * <p> * By default, if no CacheManager is provided, the DeliveryClient will use it's default, which just passes through. * * @see DeliveryClient#setCacheManager(CacheManager) * @see <a href="https://kontent.ai/learn/tutorials/develop-apps/integrate/using-webhooks-for-automatic-updates"> * Kontent.ai API reference - Webhooks and notifications</a> */ public interface CacheManager { /** * Retrieve an earlier cached response from the Kontent.ai Delivery API. * * @param url The url that would be used to retrieve the response from Kontent.ai Delivery API. * @return JsonNode response or null if no value is available in the cache for the given url. */ JsonNode get(final String url); /** * Cache a response from the Kontent.ai Delivery API. * * @param url the URL that was used to retrieve the response from the Kontent.ai Delivery API. * @param jsonNode the JsonNode created from the response from the Kontent.ai Delivery API. * @param containedContentItems (null allowed) can be used to inspect the original contents of the JsonNode and allow for precise cache invalidation (if implemented). */ void put(final String url, JsonNode jsonNode, List<ContentItem> containedContentItems); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/ContentItem.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Collections; import java.util.List; import java.util.Map; /** * Object model description of a single content item object. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> */ @lombok.Data @lombok.NoArgsConstructor @lombok.AllArgsConstructor @lombok.Builder @lombok.EqualsAndHashCode(exclude = {"linkedItemProvider", "stronglyTypedContentItemConverter"}) @lombok.ToString(exclude = {"linkedItemProvider", "stronglyTypedContentItemConverter"}) public class ContentItem { /** * {@link System} attributes of the content item. * * @param system New value for System attributes of this content item. * @return The System attributes of this content item. */ @JsonProperty("system") System system; /** * Content type elements in the content item. These are keyed by the codename of the element. * <p> * Note: The order of the {@link Element} objects might not match the order in the Kontent.ai UI. * * @return Map of this ContentItem's {@link Element} objects. */ @JsonProperty("elements") Map<String, Element> elements; @JsonIgnore LinkedItemProvider linkedItemProvider; @JsonIgnore private StronglyTypedContentItemConverter stronglyTypedContentItemConverter; /** * Content type elements in the content item. These are keyed by the codename of the element. * <p> * Note: The order of the {@link Element} objects might not match the order in the Kontent.ai UI. * * @param elements New value for this ContentItem's {@link Element} objects. */ public void setElements(Map<String, Element> elements) { this.elements = elements; elements.forEach((s, element) -> element.setParent(this)); } /** * Convenience method to get the value of a Text or Rich text element without traversing the Elements map. * * @param codename The element codename to retrieve the String rendering of from this ContentItem. * @return The value of the element. Returns null if the element does not exist, or if it is not a * {@link TextElement} or {@link RichTextElement}. */ public String getString(String codename) { Element element = elements.get(codename); if (element == null) { return null; } if (!(element instanceof TextElement)) { return null; } return ((TextElement) element).getValue(); } /** * Convenience method to get the value of an Assets element without traversing the Elements map. * * @param codename The element codename to get the Asset list of from this ContentItem. * @return A list of {@link Asset} objects. Returns an empty collection if the element does not exist, or * if it is not an {@link AssetsElement}. */ public List<Asset> getAssets(String codename) { Element element = elements.get(codename); if (element == null) { return Collections.emptyList(); } if (!(element instanceof AssetsElement)) { return Collections.emptyList(); } return ((AssetsElement) element).getValue(); } /** * Convenience method to retrieve the ContentItem from linked items. * * @param codename The {@link ContentItem} codename of the linked item. * @return The {@link ContentItem}. Returns null if it was not included in the response. */ public ContentItem getLinkedItem(String codename) { //This shouldn't happen if this is de-serialized from Jackson, but protecting against the NPE for unexpected //usages. if (linkedItemProvider == null) { return null; } return linkedItemProvider.getLinkedItems().get(codename); } /** * Returns a new instance of T by mapping fields to elements in this content item. Element fields are mapped * by automatically CamelCasing and checking for equality, unless otherwise annotated by an {@link ElementMapping} * annotation. T must have a default constructor and have standard setter methods. * When passing in Object.class, the type returned will be an instance of the class registered with the * {@link DeliveryClient} that is annotated with {@link ContentItemMapping} that matches the * {@link System#type} of this ContentItem (however still returned as type Object). * <p> * If {@link Object} is passed in, the {@link StronglyTypedContentItemConverter} will cast this ContentItem to a * type that is mapped this ContentItem's {@link System#type} from a previous registration via the registration has * been done, then this same instance of ContentItem will be returned. Invoking {@link #castToDefault()} is the * same as invoking this method with {@link Object}. * * @param tClass The class which a new instance should be returned from using this ContentItem. * @param <T> The type of class which will be returned. * @return An instance of T with data mapped from this {@link ContentItem}. * @see DeliveryClient#registerType(Class) * @see DeliveryClient#registerType(String, Class) * @see ContentItemMapping * @see ElementMapping * @see StronglyTypedContentItemConverter */ public <T> T castTo(Class<T> tClass) { return stronglyTypedContentItemConverter.convert(this, linkedItemProvider.getLinkedItems(), tClass); } /** * Returns a new instance by mapping fields to elements in this content item. Element fields are mapped * by automatically CamelCasing and checking for equality, unless otherwise annotated by an {@link ElementMapping} * annotation. The type returned will be an instance of the class registered with the {@link DeliveryClient} that * is annotated with {@link ContentItemMapping} that matches the {@link System#type} of this ContentItem * (however still returned as type Object). * <p> * If no registration has been done, then this same instance of ContentItem will be returned. * * @return An instance with data mapped from this {@link ContentItem}. * @see #castTo(Class) * @see DeliveryClient#registerType(Class) * @see DeliveryClient#registerType(String, Class) * @see ContentItemMapping * @see ElementMapping * @see StronglyTypedContentItemConverter */ public Object castToDefault() { return this.castTo(Object.class); } /** * Returns a new instance by mapping fields to elements in this content item. Element fields are mapped * by automatically CamelCasing and checking for equality, unless otherwise annotated by an {@link ElementMapping} * annotation. The type returned will be an instance of the class registered with the {@link DeliveryClient} that * that matches the {@link System#type} provided. * <p> * If no registration has been done, then this same instance of ContentItem will be returned. * * @param contentItemSystemType The contentItemSystemType to match this ContentItem too. * @return An instance with data mapped from this {@link ContentItem}. * @see #castTo(Class) * @see DeliveryClient#registerType(Class) * @see DeliveryClient#registerType(String, Class) * @see ContentItemMapping * @see ElementMapping * @see StronglyTypedContentItemConverter */ public Object castTo(String contentItemSystemType) { return stronglyTypedContentItemConverter.convert( this, linkedItemProvider.getLinkedItems(), contentItemSystemType); } void setLinkedItemProvider(LinkedItemProvider linkedItemProvider) { this.linkedItemProvider = linkedItemProvider; } void setStronglyTypedContentItemConverter(StronglyTypedContentItemConverter stronglyTypedContentItemConverter) { this.stronglyTypedContentItemConverter = stronglyTypedContentItemConverter; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/ContentItemMapping.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is used by the {@link StronglyTypedContentItemConverter} to convert {@link ContentItem}s into any * plain old Java object of your choosing. * <p> * When registering a custom type with {@link DeliveryClient#registerType(Class)}, this annotation is required to be on * the class, and the {@link #value()} is used to register the type with {@link ContentItem}s with the same value set * for it's {@link System#type}. If you do not wish to annotate your class, you can still use * {@link DeliveryClient#registerType(String, Class)}. * <p> * For example, the following will map to {@link ContentItem}s with a {@link System#type} of 'article': * <pre> * &#64;ContentItemMapping("article") * public class ArticleItem { * ... * } * </pre> * <p> * When this annotation is placed on a field and the {@link #value()} matches a key in the {@link ContentItem}'s linked * items, then the {@link ContentItem} from the linked item will be cast to the field. If you do not wish to * annotate the field, you can name the field (using CamelCase) the same as the codename of the linked item * {@link ContentItem}. If using a custom type, the {@link ContentItem} will be recursively converted it until the * depth of the original query is exhausted or loops back. Note, that because this maps to a specific codename, it will * generally be of limited use unless you know that instance of linked item will always be referenced. * <p> * For example, the following will map a field to a linked item with the codename 'origins_of_arabica_bourbon': * <pre> * &#64;ContentItemMapping("origins_of_arabica_bourbon") * ContentItem arabicaBourbonOrigin; * </pre> * <p> * When this annotation is placed on a field of type List or Map, the {@link #value()} is used to map to the matching * key from {@link ContentItem#getElements()} and if the {@link Element} is of type {@link LinkedItem}, the * {@link ContentItem}s contained will be cast to the type of the List or type of the Map's value entry. If using a * custom type, any {@link ContentItem}s with a {@link System#type} that is not registered for the type will be * excluded from the List or Map. If you do not wish to annotate the List or Map, you can name the field (using * CamelCase) to the name of the {@link Element} codename. Keys to maps will be the {@link System#codename} of the * {@link ContentItem} instances. * <p> * For example, the following will map to the 'related_articles' element if it's of type {@link LinkedItem}: * <pre> * &#64;ContentItemMapping("related_articles") * List&#60;ContentItem&#62; relatedArticles; * * &#64;ContentItemMapping("related_articles") * Map&#60;String, ContentItem&#62; relatedArticlesMap; * </pre> * <p> * Custom types may also be registered with {@link DeliveryClient#scanClasspathForMappings(String)}. * * @see ContentItem * @see System * @see DeliveryClient#registerType(Class) * @see DeliveryClient#scanClasspathForMappings(String) * @see DeliveryParameterBuilder#linkedItemsDepth(Integer) * @see ElementMapping * @see LinkedItem * @see StronglyTypedContentItemConverter * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Linked-items-element"> * Kontent.ai API reference - Linked items</a> */ @Target({ElementType.TYPE, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface ContentItemMapping { /** * When placed on a Class, this maps to a {@link ContentItem}'s {@link System#type}. * <p> * When placed on a field, this maps to the linked {@link ContentItem} with a matching {@link System#codename} * if it was included with the {@link ContentItem}. * <p> * When placed on a List or Map, this maps to linked {@link ContentItem}s that are linked by a {@link LinkedItem} * with the same name. * * @return The {@link System#type} or codename this annotation is referencing. See the documentation on this * annotation. */ String value(); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/ContentItemResponse.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Map; /** * Content item listing response from an invocation of {@link DeliveryClient#getItem(String)}, or * {@link DeliveryClient#getItem(String, List)}. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/retrieve-a-content-item"> * Kontent.ai API reference - View a content item</a> * @see ContentItem * @see DeliveryClient#getItem(String) * @see DeliveryClient#getItem(String, List) */ @lombok.Getter @lombok.ToString(exclude = "stronglyTypedContentItemConverter") @lombok.EqualsAndHashCode(exclude = "stronglyTypedContentItemConverter") @lombok.NoArgsConstructor @lombok.AllArgsConstructor @lombok.Builder public class ContentItemResponse implements LinkedItemProvider { /** * The {@link ContentItem} returned by this ContentItemResponse. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/retrieve-a-content-item"> * Kontent.ai API reference - View a content item</a> * @return The {@link ContentItem} of this ContentItemResponse. */ @JsonProperty("item") ContentItem item; /** * A map of content items used in linked item and Rich text elements. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Linked-items-element"> * Kontent.ai API reference - Linked items</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/retrieve-a-content-item"> * Kontent.ai API reference - View a content item</a> * @return The linked {@link ContentItem}s referenced in this response. */ @JsonProperty("modular_content") Map<String, ContentItem> linkedItems; @JsonIgnore private StronglyTypedContentItemConverter stronglyTypedContentItemConverter; /** * Returns a new instance of T by mapping fields to elements in this response's {@link #getItem()}. Element fields * are mapped by automatically CamelCasing and checking for equality, unless otherwise annotated by an * {@link ElementMapping} annotation. T must have a default constructor and have standard setter methods. When * passing in Object.class, the type returned will be an instance of the class registered with the * {@link DeliveryClient} that is annotated with {@link ContentItemMapping} that matches the * {@link System#type} of this ContentItem (however still returned as type Object). * <p> * If {@link Object} is passed in, the {@link StronglyTypedContentItemConverter} will cast this ContentItem to a * type that is mapped this ContentItem's {@link System#type} from a previous registration via the * {@link DeliveryClient#registerType(Class)} or {@link DeliveryClient#registerType(String, Class)} methods. If no * registration has been done, then this same instance of ContentItem will be returned. * * @param tClass The class which a new instance should be returned from using this ContentItem. * @param <T> The type of class which will be returned. * @return An instance of T with data mapped from the {@link ContentItem} in this response. * @see DeliveryClient#registerType(Class) * @see DeliveryClient#registerType(String, Class) * @see ContentItemMapping * @see ElementMapping * @see StronglyTypedContentItemConverter */ public <T> T castTo(Class<T> tClass) { return stronglyTypedContentItemConverter.convert(item, this.getLinkedItems(), tClass); } void setItem(ContentItem item) { this.item = item; item.setLinkedItemProvider(this); } void setLinkedItems(Map<String, ContentItem> linkedItems) { this.linkedItems = linkedItems; linkedItems.values().forEach(contentItem -> contentItem.setLinkedItemProvider(this)); } ContentItemResponse setStronglyTypedContentItemConverter(StronglyTypedContentItemConverter stronglyTypedContentItemConverter) { this.stronglyTypedContentItemConverter = stronglyTypedContentItemConverter; item.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); if (linkedItems != null) { for (ContentItem linkedItem : linkedItems.values()) { linkedItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); } } return this; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/ContentItemsListingResponse.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Content item listing response from an invocation of {@link DeliveryClient#getItems()}, or * {@link DeliveryClient#getItems(List)}. * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-content-items"> * Kontent.ai API reference - List content items</a> * @see ContentItem * @see DeliveryClient#getItem(String) * @see DeliveryClient#getItem(String, List) */ @lombok.Getter @lombok.ToString(exclude = "stronglyTypedContentItemConverter") @lombok.EqualsAndHashCode(exclude = "stronglyTypedContentItemConverter") @lombok.NoArgsConstructor @lombok.AllArgsConstructor @lombok.Builder public class ContentItemsListingResponse implements LinkedItemProvider { /** * The {@link ContentItem}s returned by this ContentItemsListingResponse. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-content-items"> * Kontent.ai API reference - List content items</a> * @return The {@link ContentItem}s of this ContentItemsListingResponse. */ @JsonProperty("items") List<ContentItem> items; /** * A map of content items used in linked item and Rich text elements. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Linked-items-element"> * Kontent.ai API reference - Linked items</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-content-items"> * Kontent.ai API reference - List content items</a> * @return The linked {@link ContentItem}s referenced in this response. */ @JsonProperty("modular_content") Map<String, ContentItem> linkedItems; /** * Information about the retrieved page. Used for iterating a large result set if using limit query parameters. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-content-items"> * Kontent.ai API reference - Listing response paging</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-content-items"> * Kontent.ai API reference - Pagination object</a> * @return The {@link Pagination} for this ContentItemsListingResponse identifying the current page. */ @JsonProperty("pagination") Pagination pagination; @JsonIgnore private StronglyTypedContentItemConverter stronglyTypedContentItemConverter; /** * Returns a new instance of {@code List<T>} by mapping fields to elements in this content item. Element fields are * mapped by automatically CamelCasing and checking for equality, unless otherwise annotated by an * {@link ElementMapping} annotation. T must have a default constructor and have standard setter methods. * * @param tClass The class which a new instance should be returned from * @param <T> The type of class * @return An instance of {@code List<T>} with data mapped from the {@link ContentItem} list in this * response. */ public <T> List<T> castTo(Class<T> tClass) { ArrayList<T> tItems = new ArrayList<>(); for (ContentItem item : getItems()) { tItems.add(stronglyTypedContentItemConverter.convert(item, this.getLinkedItems(), tClass)); } return tItems; } void setItems(List<ContentItem> items) { this.items = items; items.forEach(contentItem -> contentItem.setLinkedItemProvider(this)); } void setLinkedItems(Map<String, ContentItem> linkedItems) { this.linkedItems = linkedItems; linkedItems.values().forEach(contentItem -> contentItem.setLinkedItemProvider(this)); } void setPagination(Pagination pagination) { this.pagination = pagination; } ContentItemsListingResponse setStronglyTypedContentItemConverter(StronglyTypedContentItemConverter stronglyTypedContentItemConverter) { this.stronglyTypedContentItemConverter = stronglyTypedContentItemConverter; for (ContentItem item : getItems()) { item.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); } if (linkedItems != null) { for (ContentItem linkedItem : linkedItems.values()) { linkedItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); } } return this; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/ContentLinkUrlResolver.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; /** * Interface to provide for rendering content item links in rich text. * <p> * An implementation of this can be provided to via * {@link DeliveryClient#setContentLinkUrlResolver(ContentLinkUrlResolver)} to resolve links to a content item that are * published. This is passed on to the {@link RichTextElementConverter} to update {@code href} attributes in links when * a {@code data-item-id} is available on the link. * <p> * This is a {@link FunctionalInterface} to simplify implementation. * <p> * For example, the following implementation will render {@code <a href="/LINK_TYPE/LINK_URL_SLUG">Some text</a>}: * <pre>{@code * DeliveryClient deliveryClient = new DeliveryClient("02a70003-e864-464e-b62c-e0ede97deb8c"); * deliveryClient.setContentLinkUrlResolver(link -> String.format("/%s/%s", link.getType(), link.getUrlSlug())); * }</pre> * * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Linked-items-element"> * Kontent.ai API reference - Link to a content item</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Rich-text-element/links-single-object"> * Kontent.ai API reference - Rich text links</a> * @see Link * @see RichTextElementConverter * @see RichTextElement */ @FunctionalInterface public interface ContentLinkUrlResolver { /** * Returns a String to be placed in the href attribute of any links to content items that are published within * {@link RichTextElement}s. * * @param link The link that needs to be resolved to a url. * @return The String to place in the href attribute of any links to content items that are published. */ String resolveLinkUrl(Link link); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/ContentType.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; /** * Object model description of a single content type object. * <p> * Also serves as the response from an invocation of {@link DeliveryClient#getType(String)}. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-type-object"> * Kontent.ai API reference - Content type object</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/retrieve-a-content-type"> * Kontent.ai API reference - View a content type</a> */ @lombok.Data @lombok.NoArgsConstructor @lombok.AllArgsConstructor @lombok.Builder public class ContentType { /** * {@link System} attributes of the content type. * * @param system New value for System attributes of this content type. * @return The System attributes of this content type. */ @JsonProperty("system") System system; /** * Content type elements in the content type. These are keyed by the codename of the element. * <p> * Note: The order of the {@link Element} objects might not match the order in the Kontent.ai UI. * * @param elements New value of this ContentType's {@link Element} objects. * @return Map of this ContentType's {@link Element} objects. */ @JsonProperty("elements") Map<String, Element> elements; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/ContentTypesListingResponse.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Content type listing response from an invocation of {@link DeliveryClient#getTypes()}, or * {@link DeliveryClient#getTypes(List)}. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-content-types"> * Kontent.ai API reference - List content types</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-type-object"> * Kontent.ai API reference - Content type object</a> * @see ContentType * @see DeliveryClient#getTypes() * @see DeliveryClient#getTypes(List) */ @lombok.Data @lombok.NoArgsConstructor @lombok.AllArgsConstructor @lombok.Builder public class ContentTypesListingResponse { /** * The {@link ContentType}s returned by this ContentTypesListingResponse. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-content-types"> * Kontent.ai API reference - List content types</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-type-object"> * Kontent.ai API reference - Content type object</a> * @see ContentType * @param types New value for the {@link ContentType}s of this ContentTypesListingResponse. * @return The {@link ContentType}s of this ContentTypesListingResponse. */ @JsonProperty("types") List<ContentType> types; /** * Information about the retrieved page. Used for iterating a large result set if using limit query parameters. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-content-items"> * Kontent.ai API reference - Listing response paging</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-content-items"> * Kontent.ai API reference - Pagination object</a> * @param pagination New value for the {@link Pagination} of this ContentTypesListingResponse * @return The {@link Pagination} for this ContentTypesListingResponse identifying the current page. */ @JsonProperty("pagination") Pagination pagination; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/CustomElement.java
/* * MIT License * * Copyright (c) 2020 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Object model for custom elements */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class CustomElement extends Element<String> { static final String TYPE_VALUE = "custom"; /** * The value of a custom element is a string. * * @param value Sets the value of this. * @return The element value of this. */ @JsonProperty("value") String value; public CustomElement() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/DateTimeElement.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.ZonedDateTime; /** * Object model for Date &amp; time elements. * * @see Asset * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Date-and-time-element"> * Kontent.ai API reference - Date time</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Content-item-object"> * Kontent.ai API reference - Content item object</a> */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class DateTimeElement extends Element<ZonedDateTime> { static final String TYPE_VALUE = "date_time"; /** * The value of a Date &amp; time element is a string in the ISO 8601 format. If empty, the value is null. * * @param value New value of the {@link ZonedDateTime} of this element. * @return A {@link ZonedDateTime} instance representing the original ISO 8601 string. */ @JsonProperty("value") ZonedDateTime value; public DateTimeElement() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/DelegatingRichTextElementResolver.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import java.util.ArrayList; import java.util.List; /** * Implementation of {@link RichTextElementResolver} that iterates over a list of resolvers sequentially. * * @see DeliveryClient#addRichTextElementResolver(RichTextElementResolver) * @see DeliveryClient#setRichTextElementResolver(RichTextElementResolver) * @see RichTextElementConverter */ public class DelegatingRichTextElementResolver implements RichTextElementResolver { List<RichTextElementResolver> resolvers = new ArrayList<>(); /** * {@inheritDoc} */ @Override public String resolve(String content) { if (resolvers.isEmpty()) { return content; } String resolvedContent = content; for (RichTextElementResolver resolver : resolvers) { resolvedContent = resolver.resolve(resolvedContent); } return resolvedContent; } /** * Adds a {@link RichTextElementResolver} to the list of resolvers this resolver will delegate to. * * @param resolver The {@link RichTextElementResolver} to add to the delegate list. */ public void addResolver(RichTextElementResolver resolver) { resolvers.add(resolver); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/DeliveryClient.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import kontent.ai.delivery.template.TemplateEngineConfig; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** * Executes requests against the Kontent.ai Delivery API. */ @Slf4j public class DeliveryClient { public static final String HEADER_X_KC_WAIT_FOR_LOADING_NEW_CONTENT = "X-KC-Wait-For-Loading-New-Content"; public static final String HEADER_X_KC_SDK_ID = "X-KC-SDKID"; public static final String HEADER_AUTHORIZATION = "Authorization"; public static final String HEADER_ACCEPT = "Accept"; private static final String[] RESERVED_HEADERS = new String[]{HEADER_ACCEPT, HEADER_X_KC_SDK_ID, HEADER_AUTHORIZATION, HEADER_X_KC_WAIT_FOR_LOADING_NEW_CONTENT}; private static String sdkId; static { try { Properties buildProps = new Properties(); buildProps.load(DeliveryClient.class.getResourceAsStream("version.properties")); String repositoryHost = buildProps.getProperty("repository-host"); String version = buildProps.getProperty("version"); String packageId = buildProps.getProperty("package-id"); repositoryHost = repositoryHost == null ? "localBuild" : repositoryHost; version = version == null ? "0.0.0" : version; packageId = packageId == null ? "ai.kontent:delivery-sdk" : packageId; sdkId = String.format( "%s;%s;%s", repositoryHost, packageId, version); log.info("SDK ID: {}", sdkId); } catch (IOException e) { log.info("Jar manifest read error, setting developer build SDK ID"); sdkId = "localBuild;ai.kontent:delivery-sdk;0.0.0"; } } private static final String ITEMS = "items"; private static final String TYPES = "types"; private static final String ELEMENTS = "elements"; private static final String TAXONOMIES = "taxonomies"; private static final String URL_CONCAT = "%s/%s"; private static final List<Integer> RETRY_STATUSES = Collections.unmodifiableList(Arrays.asList(408, 429, 500, 502, 503, 504)); private ObjectMapper objectMapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); private DeliveryOptions deliveryOptions; private ContentLinkUrlResolver contentLinkUrlResolver; private BrokenLinkUrlResolver brokenLinkUrlResolver; private RichTextElementResolver richTextElementResolver = new DelegatingRichTextElementResolver(); private StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); private TemplateEngineConfig templateEngineConfig; private OkHttpClient httpClient; private AsyncCacheManager cacheManager = new AsyncCacheManager() { @Override public CompletionStage<JsonNode> get(String url) { return CompletableFuture.completedFuture(null); } @Override public CompletionStage put(String url, JsonNode jsonNode, List<ContentItem> containedContentItems) { return CompletableFuture.completedFuture(null); } }; static final ScheduledExecutorService SCHEDULER = new ScheduledThreadPoolExecutor(0); /** * Please use this constructor when you need to initialize client with default template configuration - so when you are using template engine. For i.e. Android platform use {@link DeliveryClient#DeliveryClient(DeliveryOptions, TemplateEngineConfig)} and set second parameter to null. * * @param deliveryOptions delivery options {@link DeliveryOptions} */ @SuppressWarnings("WeakerAccess") public DeliveryClient(DeliveryOptions deliveryOptions) { this(deliveryOptions, new TemplateEngineConfig()); } @SuppressWarnings({"ResultOfMethodCallIgnored", "WeakerAccess"}) public DeliveryClient(DeliveryOptions deliveryOptions, TemplateEngineConfig templateEngineConfig) { if (deliveryOptions == null) { throw new IllegalArgumentException("The Delivery options object is not specified."); } if (deliveryOptions.getProjectId() == null || deliveryOptions.getProjectId().isEmpty()) { throw new IllegalArgumentException("Kontent.ai project identifier is not specified."); } try { UUID.fromString(deliveryOptions.getProjectId()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format( "Provided string is not a valid project identifier (%s). Have you accidentally passed " + "the Preview API key instead of the project identifier?", deliveryOptions.getProjectId()), e); } if (deliveryOptions.isUsePreviewApi() && (deliveryOptions.getPreviewApiKey() == null || deliveryOptions.getPreviewApiKey().isEmpty())) { throw new IllegalArgumentException("The Preview API key is not specified."); } if (deliveryOptions.isUsePreviewApi() && deliveryOptions.getProductionApiKey() != null) { throw new IllegalArgumentException("Cannot provide both a preview API key and a production API key."); } if (deliveryOptions.getRetryAttempts() < 0) { throw new IllegalArgumentException("Cannot retry connections less than 0 times."); } this.deliveryOptions = deliveryOptions; if (templateEngineConfig != null) { templateEngineConfig.init(); this.templateEngineConfig = templateEngineConfig; } reconfigureDeserializer(); OkHttpClient.Builder builder = new OkHttpClient.Builder(); if (deliveryOptions.getProxyServer() != null) { builder.proxy(deliveryOptions.getProxyServer()); } this.httpClient = builder.build(); } @SuppressWarnings("unused") public DeliveryClient(String projectId) { this(new DeliveryOptions(projectId)); } @SuppressWarnings("unused") public DeliveryClient(String projectId, String previewApiKey) { this(new DeliveryOptions(projectId, previewApiKey)); } public CompletionStage<ContentItemsListingResponse> getItems() { return getItems(Collections.emptyList()); } @SuppressWarnings("WeakerAccess") public CompletionStage<ContentItemsListingResponse> getItems(List<NameValuePair> params) { return executeRequest(ITEMS, params, ContentItemsListingResponse.class) .thenApply(contentItemsListingResponse -> contentItemsListingResponse .setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter)) .thenApply(response -> { createRichTextElementConverter().process(response.items); return response; }); } @SuppressWarnings("WeakerAccess") public <T> CompletionStage<List<T>> getItems(Class<T> tClass, List<NameValuePair> params) { return getItems(addTypeParameterIfNecessary(tClass, params)) .thenApply(contentItemsListingResponse -> contentItemsListingResponse.castTo(tClass)); } @SuppressWarnings("unused") public CompletionStage<ContentItemResponse> getItem(String contentItemCodename) { return getItem(contentItemCodename, Collections.emptyList()); } @SuppressWarnings("unused") public <T> CompletionStage<List<T>> getItems(Class<T> tClass) { return getItems(tClass, Collections.emptyList()); } @SuppressWarnings("WeakerAccess") public <T> CompletionStage<Page<T>> getPageOfItems(Class<T> tClass, List<NameValuePair> params) { return getItems(params) .thenApply(response -> response.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter)) .thenApply(response -> new Page<>(response, tClass)); } @SuppressWarnings("WeakerAccess") public <T> CompletionStage<Page<T>> getNextPage(Page<T> currentPage) { final Pagination pagination = currentPage.getPagination(); if (pagination.getNextPage() == null || pagination.getNextPage().isEmpty()) { return CompletableFuture.completedFuture(null); } return executeRequest(pagination.getNextPage(), ContentItemsListingResponse.class) .thenApply(response -> response.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter)) .thenApply(response -> { createRichTextElementConverter().process(response.items); return response; }) .thenApply(response -> new Page<>(response, currentPage.getType())); } @SuppressWarnings("unused") public <T> CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass) { return getItem(contentItemCodename, tClass, Collections.emptyList()); } @SuppressWarnings("WeakerAccess") public CompletionStage<ContentItemResponse> getItem(String contentItemCodename, List<NameValuePair> params) { final String apiCall = String.format(URL_CONCAT, ITEMS, contentItemCodename); return executeRequest(apiCall, params, ContentItemResponse.class) .thenApply(response -> response.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter)) .thenApply(response -> { createRichTextElementConverter().process(response.item); return response; }); } @SuppressWarnings("WeakerAccess") public <T> CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass, List<NameValuePair> params) { return getItem(contentItemCodename, addTypeParameterIfNecessary(tClass, params)) .thenApply(contentItemResponse -> contentItemResponse.castTo(tClass)); } public CompletionStage<ContentTypesListingResponse> getTypes() { return getTypes(Collections.emptyList()); } @SuppressWarnings("WeakerAccess") public CompletionStage<ContentTypesListingResponse> getTypes(List<NameValuePair> params) { return executeRequest(TYPES, params, ContentTypesListingResponse.class); } public CompletionStage<ContentType> getType(String contentTypeCodeName) { final String apiCall = String.format(URL_CONCAT, TYPES, contentTypeCodeName); return executeRequest(apiCall, Collections.emptyList(), ContentType.class); } @SuppressWarnings("unused") public CompletionStage<Element> getContentTypeElement(String contentTypeCodeName, String elementCodeName) { return getContentTypeElement(contentTypeCodeName, elementCodeName, Collections.emptyList()); } @SuppressWarnings("WeakerAccess") public CompletionStage<Element> getContentTypeElement( String contentTypeCodeName, String elementCodeName, List<NameValuePair> params) { final String apiCall = String.format("%s/%s/%s/%s", TYPES, contentTypeCodeName, ELEMENTS, elementCodeName); return executeRequest(apiCall, params, Element.class); } @SuppressWarnings("unused") public CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups() { return getTaxonomyGroups(Collections.emptyList()); } @SuppressWarnings("WeakerAccess") public CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(List<NameValuePair> params) { return executeRequest(TAXONOMIES, params, TaxonomyGroupListingResponse.class); } @SuppressWarnings("unused") public CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename) { return getTaxonomyGroup(taxonomyGroupCodename, Collections.emptyList()); } @SuppressWarnings("WeakerAccess") public CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename, List<NameValuePair> params) { final String apiCall = String.format(URL_CONCAT, TAXONOMIES, taxonomyGroupCodename); return executeRequest(apiCall, params, TaxonomyGroup.class); } @SuppressWarnings("WeakerAccess") public ContentLinkUrlResolver getContentLinkUrlResolver() { return contentLinkUrlResolver; } @SuppressWarnings("WeakerAccess") public void setContentLinkUrlResolver(ContentLinkUrlResolver contentLinkUrlResolver) { this.contentLinkUrlResolver = contentLinkUrlResolver; } @SuppressWarnings("WeakerAccess") public BrokenLinkUrlResolver getBrokenLinkUrlResolver() { return brokenLinkUrlResolver; } @SuppressWarnings("WeakerAccess") public void setBrokenLinkUrlResolver(BrokenLinkUrlResolver brokenLinkUrlResolver) { this.brokenLinkUrlResolver = brokenLinkUrlResolver; } @SuppressWarnings("WeakerAccess") public RichTextElementResolver getRichTextElementResolver() { return richTextElementResolver; } @SuppressWarnings("WeakerAccess") public void setRichTextElementResolver(RichTextElementResolver richTextElementResolver) { this.richTextElementResolver = richTextElementResolver; } @SuppressWarnings("WeakerAccess") public void addRichTextElementResolver(RichTextElementResolver richTextElementResolver) { if (this.richTextElementResolver instanceof DelegatingRichTextElementResolver) { ((DelegatingRichTextElementResolver) this.richTextElementResolver).addResolver(richTextElementResolver); } else if (this.richTextElementResolver == null) { setRichTextElementResolver(richTextElementResolver); } else { DelegatingRichTextElementResolver delegatingResolver = new DelegatingRichTextElementResolver(); delegatingResolver.addResolver(this.richTextElementResolver); delegatingResolver.addResolver(richTextElementResolver); setRichTextElementResolver(delegatingResolver); } } @SuppressWarnings("WeakerAccess") public void registerType(String contentType, Class<?> clazz) { stronglyTypedContentItemConverter.registerType(contentType, clazz); } @SuppressWarnings("WeakerAccess") public void registerType(Class<?> clazz) { stronglyTypedContentItemConverter.registerType(clazz); } @SuppressWarnings("WeakerAccess") public void registerInlineContentItemsResolver(InlineContentItemsResolver resolver) { stronglyTypedContentItemConverter.registerInlineContentItemsResolver(resolver); } /** * Not working on Android platform because of JVM and Dalvik differences, please use {@link DeliveryClient#registerType(Class)} instead * Register by scanning the classpath for annotated classes by {@link ContentItemMapping} annotation. * * @param basePackage name of the base package */ @SuppressWarnings("WeakerAccess") public void scanClasspathForMappings(String basePackage) { stronglyTypedContentItemConverter.scanClasspathForMappings(basePackage); } @SuppressWarnings("WeakerAccess") public void setCacheManager(AsyncCacheManager cacheManager) { this.cacheManager = cacheManager; } /** * Sets the {@link CacheManager} for this client. * * @param cacheManager A {@link CacheManager} implementation for this client to use. * @see CacheManager */ public void setCacheManager(final CacheManager cacheManager) { final AsyncCacheManager bridgedCacheManager = new AsyncCacheManager() { @Override public CompletionStage<JsonNode> get(String url) { return CompletableFuture.supplyAsync(() -> cacheManager.get(url) ); } @Override public CompletionStage put(String url, JsonNode jsonNode, List<ContentItem> containedContentItems) { return CompletableFuture.runAsync(() -> cacheManager.put(url, jsonNode, containedContentItems)); } }; this.setCacheManager(bridgedCacheManager); } private <T> CompletionStage<T> executeRequest(final String apiCall, final List<NameValuePair> queryParams, Class<T> tClass) { return executeRequest(createUrl(apiCall, queryParams), tClass); } private <T> CompletionStage<T> executeRequest(final String url, Class<T> tClass) { final Request request = buildNewRequest(url); log.debug("Request to url: {}", url); final boolean skipCache = Optional.ofNullable(request.header(HEADER_X_KC_WAIT_FOR_LOADING_NEW_CONTENT)) .map(Boolean::valueOf) .orElse(false); if (skipCache) { return retrieveFromKontent(request, url, tClass, 0); } else { return cacheManager.get(url).thenApply(jsonNode -> { try { if (jsonNode == null) { return null; } return objectMapper.treeToValue(jsonNode, tClass); } catch (JsonProcessingException e) { log.error("JsonProcessingException parsing Kontent.ai object: {}", e.toString()); } return null; }).thenCompose(result -> { if (result != null) { return CompletableFuture.completedFuture(result); } else { return retrieveFromKontent(request, url, tClass, 0); } }); } } private <T> CompletionStage<T> retrieveFromKontent(Request request, final String url, Class<T> tClass, int retryTurn) { return send(request) .thenApply(this::logResponseInfo) .thenApply(this::handleErrorIfNecessary) .thenApply(Response::body) .thenApply((responseBody) -> { try { return responseBody.string(); } catch (IOException e) { log.error("IOException when converting responseBody to body string: {}", e.toString()); throw new CompletionException(e); } }) .thenApply((bodyString) -> { try { return objectMapper.readValue(bodyString, JsonNode.class); } catch (IOException e) { log.error("IOException when mapping body string to the JsonNode: {}", e.toString()); throw new CompletionException(e); } }) .thenCompose((jsonNode) -> { try { return convertAndPutInCache(url, tClass, jsonNode); } catch (JsonProcessingException e) { log.error("JsonProcessingException when converting JsonNode to typed class: {}", e.toString()); throw new CompletionException(e); } }) .exceptionally((error) -> { final AtomicInteger counter = new AtomicInteger(retryTurn); if (error instanceof CompletionException) { Throwable cause = error.getCause(); // Don't retry when when not KontentException or not set to retry boolean retry = cause instanceof KontentException && ((KontentException) cause).shouldRetry(); if (!retry) { throw (CompletionException) error; } } if (counter.incrementAndGet() > deliveryOptions.getRetryAttempts()) { KontentRetryException ex = new KontentRetryException(deliveryOptions.getRetryAttempts()); ex.initCause(error.getCause()); throw ex; } //Perform a binary exponential backoff int wait = (int) (100 * Math.pow(2, retryTurn)); log.info("Reattempting request after {}ms (re-attempt {} out of max {})", wait, counter.get(), deliveryOptions.getRetryAttempts()); try { return CompletableFuture.supplyAsync( () -> { try { return retrieveFromKontent(request, url, tClass, counter.get()) .toCompletableFuture().get(); } catch (InterruptedException e) { log.error(String.format("InterruptedException have been raised on retial no. %d", counter.get())); throw new CompletionException(e); } catch (ExecutionException e) { log.error(String.format("ExecutionException have been raised on retrial no. %d", counter.get())); if (e.getCause() instanceof KontentRetryException) { KontentRetryException exception = new KontentRetryException(((KontentRetryException) e.getCause()).getMaxRetryAttempts()); exception.initCause(error.getCause()); throw exception; } throw new CompletionException(e); } }, r -> SCHEDULER.schedule( () -> ForkJoinPool.commonPool().execute(r), wait, TimeUnit.MILLISECONDS) ).toCompletableFuture() .get(); } catch (InterruptedException e) { log.error("InterruptedException have been raised for timeout"); throw new CompletionException(e); } catch (ExecutionException e) { log.error("ExecutionException have been raised for timeout"); if (e.getCause() instanceof KontentRetryException) { KontentRetryException exception = new KontentRetryException(((KontentRetryException) e.getCause()).getMaxRetryAttempts()); exception.initCause(error.getCause()); throw exception; } throw new CompletionException(e); } }); } private Response handleErrorIfNecessary(Response response) throws KontentIOException, KontentErrorException { final int status = response.code(); if (RETRY_STATUSES.contains(status)) { log.error("Kontent.ai API retry status returned: {} (one of {})", status, RETRY_STATUSES.toString()); try { KontentError kontentError = objectMapper.readValue(response.body().bytes(), KontentError.class); throw new KontentErrorException(kontentError, true); } catch (IOException e) { log.error("IOException when trying to parse the error response body: {}", e.toString()); throw new KontentIOException(String.format("Kontent.ai API retry status returned: %d (one of %s)", status, RETRY_STATUSES.toString()), true); } } else if (status >= 500) { log.error("Kontent.ai API server error, status: {}", status); log.info("Request URL: ", response.request().url().toString()); String message = String.format( "Unknown error with Kontent.ai API. Kontent.ai is likely suffering site issues. Status: %s", status); throw new CompletionException(new KontentIOException(message, false)); } else if (status >= 400) { log.error("Kontent.ai API server error, status: {}", status); try { KontentError kontentError = objectMapper.readValue(response.body().bytes(), KontentError.class); throw new CompletionException(new KontentErrorException(kontentError, false)); } catch (IOException e) { log.error("IOException connecting to Kontent.ai: {}", e.toString()); throw new CompletionException(new KontentIOException(e, false)); } } return response; } private CompletionStage<Response> send(Request request) { final CompletableFuture<Response> future = new CompletableFuture<>(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { log.error("Request call failed with IO Exception: {}", e.getMessage()); future.completeExceptionally(e); } @Override public void onResponse(Call call, Response response) throws IOException { log.debug("Request call succeeded with response message:", response.message()); future.complete(response); } }); return future; } private Request buildNewRequest(String url) { Request.Builder requestBuilder = new Request.Builder().url(url); requestBuilder.header(HEADER_ACCEPT, "application/json"); requestBuilder.header(HEADER_X_KC_SDK_ID, sdkId); if (deliveryOptions.getProductionApiKey() != null) { requestBuilder.header(HEADER_AUTHORIZATION, String.format("Bearer %s", deliveryOptions.getProductionApiKey())); } else if (deliveryOptions.isUsePreviewApi()) { requestBuilder.header(HEADER_AUTHORIZATION, String.format("Bearer %s", deliveryOptions.getPreviewApiKey())); } if (deliveryOptions.isWaitForLoadingNewContent()) { requestBuilder.header(HEADER_X_KC_WAIT_FOR_LOADING_NEW_CONTENT, "true"); } if (deliveryOptions.getCustomHeaders() != null){ for (Header header : deliveryOptions.getCustomHeaders()) { if (Arrays.stream(RESERVED_HEADERS).anyMatch(header.getName()::equals)) { log.info("Custom header with name {} will be ignored", header.getName()); } else { requestBuilder.header(header.getName(), header.getValue()); } } } return requestBuilder.build(); } private String createUrl(final String apiCall, final List<NameValuePair> queryParams) { final String queryStr = Optional.ofNullable(queryParams) .filter(params -> !params.isEmpty()) .map(params -> params.stream() .map(pair -> pair.getValue() != null ? String.format("%s=%s", pair.getName(), pair.getValue()) : pair.getName()) .collect(Collectors.joining("&"))) .map("?"::concat) .orElse(""); final String endpoint = deliveryOptions.isUsePreviewApi() ? deliveryOptions.getPreviewEndpoint() : deliveryOptions.getProductionEndpoint(); return String.format("%s/%s/%s%s", endpoint, deliveryOptions.getProjectId(), apiCall, queryStr); } private Response logResponseInfo(Response response) { log.info("{} - {}", response.message(), response.request().url()); log.debug("{} - {}:\n{}", response.code(), response.request().url(), response.body()); return response; } private <T> CompletionStage<T> convertAndPutInCache(String url, Class<T> tClass, JsonNode jsonNode) throws JsonProcessingException { final T t = objectMapper.treeToValue(jsonNode, tClass); final List<ContentItem> containedContentItems; if (t instanceof ContentItemResponse) { containedContentItems = Collections.singletonList(((ContentItemResponse) t).getItem()); } else if (t instanceof ContentItemsListingResponse) { containedContentItems = new ArrayList<>(((ContentItemsListingResponse) t).getItems()); } else { containedContentItems = Collections.emptyList(); } return cacheManager.put(url, jsonNode, containedContentItems) .thenApply((result) -> t); } private List<NameValuePair> addTypeParameterIfNecessary(Class tClass, List<NameValuePair> params) { Optional<NameValuePair> any = params.stream() .filter(nameValuePair -> nameValuePair.getName().equals("system.type")) .findAny(); if (!any.isPresent()) { String contentType = stronglyTypedContentItemConverter.getContentType(tClass); if (contentType != null) { List<NameValuePair> updatedParams = new ArrayList<>(params); updatedParams.add(new NameValuePair("system.type", contentType)); return updatedParams; } } return params; } private void reconfigureDeserializer() { objectMapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); SimpleModule module = new SimpleModule(); objectMapper.registerModule(new JavaTimeModule()); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.registerModule(module); } private RichTextElementConverter createRichTextElementConverter() { return new RichTextElementConverter( getContentLinkUrlResolver(), getBrokenLinkUrlResolver(), getRichTextElementResolver(), templateEngineConfig, stronglyTypedContentItemConverter); } DeliveryOptions getDeliveryOptions() { return deliveryOptions; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/DeliveryOptions.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import lombok.Builder; import java.net.Proxy; import java.util.List; /** * Keeps settings which are provided by customer or have default values, used in {@link DeliveryClient}. * * @see DeliveryClient * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Authentication"> * Kontent.ai API reference - Authentication</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api"> * Kontent.ai API reference - Delivery API</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#tag/Secure-access"> * Kontent.ai API reference - Secure access</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#tag/Secure-access"> * Kontent.ai API reference - Securing public access</a> */ @lombok.Data @lombok.NoArgsConstructor @lombok.AllArgsConstructor @lombok.Builder public class DeliveryOptions { /** * The Production endpoint address. Mainly useful to change for mocks in unit tests, or if you are establishing a * proxy. * <p> * This defaults to "https://deliver.kontent.ai" * * @param productionEndpoint New value for the productionEndpoint in this DeliveryOptions instance. * @return The value of the pstring used as the production endpoint to * Kontent. * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Production-vs.-Preview"> * Kontent.ai API reference - Production vs. preview</a> * @see java.util.Formatter */ @Builder.Default String productionEndpoint = "https://deliver.kontent.ai"; /** * The Preview endpoint address. Mainly useful to change for mocks in unit tests, or if you are establishing a * proxy. * <p> * This defaults to "https://assets-us-01.kc-usercontent.com/" * * @param previewEndpoint New value for the productionEndpoint in this DeliveryOptions instance. * @return The value of the string used as the preview endpoint to Kontent. * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Production-vs.-Preview"> * Kontent.ai API reference - Production vs. preview</a> * @see java.util.Formatter */ @Builder.Default String previewEndpoint = "https://preview-deliver.kontent.ai"; /** * The Project ID associated with your Kontent.ai account. Must be in the format of an {@link java.util.UUID}. * * @param projectId The Project ID associated with your Kontent.ai account. Must be in the format of an * {@link java.util.UUID}. * @return The Project identifier set in this DeliveryOptions instance. * @see <a href="https://kontent.ai/learn/reference/delivery-api"> * Kontent.ai API reference - Delivery API</a> */ String projectId; /** * The Production API key (Secured access API key) configured with your Kontent.ai account. * * * @param productionApiKey Sets the value of the production API key (Secured access API key) in this DeliveryOptions instance. * @return The value of the production API key in this DeliveryOptions instance. * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Production-vs.-Preview"> * Kontent.ai API reference - Production vs. preview</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#tag/Secure-access"> * Secure access</a> */ @Builder.Default String productionApiKey = null; /** * The Preview API key configured with your Kontent.ai account. * * @return The value of the preview API key in this DeliveryOptions instance. * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Production-vs.-Preview"> * Kontent.ai API reference - Production vs. preview</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Authentication"> * Kontent.ai API reference - Authentication</a> */ String previewApiKey; /** * This boolean flag determines if this client will use the preview API instead of the production API. Defaults to * 'false'. * * @param usePreviewApi Whether the preview API should be used instead of the production API. Defaults to 'false'. * @return Whether this DeliveryOptions instance is set to use the preview API instead of the * production API. * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Production-vs.-Preview"> * Kontent.ai API reference - Production vs. preview</a> */ @Builder.Default boolean usePreviewApi = false; /** * If the requested content has changed since the last request, the header determines whether to wait while fetching * content. This can be useful when retrieving changed content in reaction to a webhook call. By default, when set * to false, the API serves old content (if cached by the CDN) while it's fetching the new content to minimize wait * time. To always fetch new content, set the header to true. * * @param waitForLoadingNewContent New value for this DeliveryOptions instance. * @return Whether this DeliveryOptions instance is set to always fetch new content. */ @Builder.Default boolean waitForLoadingNewContent = false; /** * Sets the number of retry attempts the client should make when a request to the API fails. * Defaults to 3, meaning 1 normal request + 3 retrials. * * @param retryAttempts New value for this DeliveryOptions instance. * @return The number of retry attempts configured per request in this DeliveryOptions instance. */ @Builder.Default int retryAttempts = 3; /** * Sets the proxy server used by the http client. See {@link Proxy}. * * @param proxyServer The {@link Proxy} instance to use with the client each request. * @return The ProxyServer configured for this instance, or null. */ @Builder.Default Proxy proxyServer = null; /** * Include custom request headers. Headers with name {@link DeliveryClient#HEADER_ACCEPT}, {@link DeliveryClient#HEADER_AUTHORIZATION}, {@link DeliveryClient#HEADER_X_KC_SDK_ID}, {@link DeliveryClient#HEADER_X_KC_WAIT_FOR_LOADING_NEW_CONTENT} will be ignored. */ @Builder.Default List<Header> customHeaders = null; /** * Constructs a setting instance of {@link DeliveryOptions} using your Kontent.ai Project identifier. * * @param projectId The Project ID associated with your Kontent.ai account. Must be in the format of an * {@link java.util.UUID}. */ public DeliveryOptions(String projectId) { this(); this.setProjectId(projectId); } /** * Constructs a settings instance of {@link DeliveryOptions} using your Kontent.ai Project identifier and using * the preview API. * * @param projectId The Project ID associated with your Kontent.ai account. Must be in the format of an * {@link java.util.UUID}. * @param previewApiKey The Preview API key configured with your Kontent.ai account. */ public DeliveryOptions(String projectId, String previewApiKey) { this(projectId); this.setPreviewApiKey(previewApiKey); this.setUsePreviewApi(true); } /** * The Preview API key configured with your Kontent.ai account. * * @param previewApiKey Sets the value of the preview API key in this DeliveryOptions instance. If not null, * automatically sets {@link #setUsePreviewApi(boolean)} to 'true'. * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Production-vs.-Preview"> * Kontent.ai API reference - Production vs. preview</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Authentication"> * Kontent.ai API reference - Authentication</a> */ public void setPreviewApiKey(String previewApiKey) { this.previewApiKey = previewApiKey; setUsePreviewApi(previewApiKey != null); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/DeliveryParameterBuilder.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; /** * Convenience class to help construct query parameters for any Listing * Response. * <p> * For example given the following criteria: * <ul> * <li>Only 'article' types</li> * <li>Only return the 'title', 'summary', 'post_date', and 'teaser_image' * elements</li> * <li>Only return items where the 'personas' selected include * 'coffee_lover'</li> * <li>Order by 'post_date' desc order</li> * <li>Returning no linked items (0 levels of depth)</li> * <li>Returning only the first 3 items</li> * </ul> * The DeliveryParameterBuilder will look like this: * * <pre>{@code * DeliveryClient deliveryClient = new DeliveryClient("02a70003-e864-464e-b62c-e0ede97deb8c"); * List<ArticleItem> articles = deliveryClient.getItems( * ArticleItem.class, * DeliveryParameterBuilder.params() * .filterEquals("system.type", "article") * .projection("title", "summary", "post_date", "teaser_image") * .filterContains("elements.personas", "coffee_lover") * .orderByDesc("elements.post_date") * .linkedItemsDepth(0) * .page(null, 3) * .build()); * }</pre> * * Note: When using {@link DeliveryClient#getItems(Class, List)}, if the type is * registered with the client via * {@link DeliveryClient#registerType(Class)}, * {@link DeliveryClient#registerType(String, Class)}, or * {@link DeliveryClient#scanClasspathForMappings(String)}, the operator * {@code .filterEquals("system.type", your_mapped_type} will automatically be * added prior to the request if * 'system_type' is not part of any other parameter in the request already. * <p> * <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content">Filtering * Operators</a> * <p> * When retrieving a list of content items from your project with * {@link DeliveryClient#getItems(List)} and/or * {@link DeliveryClient#getItems(Class, List)}, you can filter large sets of * content items by building query operators * from content elements and system attributes. Note that the query operators do * not apply to linked items * represented by the {@link ContentItemsListingResponse#getLinkedItems()} field * in the response. * <p> * If you want to limit the listing response only to certain elements, see * {@link #projection(String...)}. * <p> * <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-by-system-values">Filtering * by system * values</a> * <p> * To filter by system attribute values, you need to use a query attribute in * the {@code 'system.<attribute_name>'} * format. The system attributes include 'id', 'name', 'codename', 'type', * 'sitemap_locations', and 'last_modified'. For * example, to retrieve only content items based on the Article content type, * you can use * {@code .filterEquals("system.type", "article"} as a query operator. * <p> * <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-by-element-values">Filtering * by element * values</a> * <p> * To filter by content element values, you need to use a query attribute in the * {@code 'elements.<element_codename>'} format. For example, to retrieve only * content items whose * {@link NumberElement} named 'Price' has a value of 16, you can use * {@code .filterEquals("elements.price", "13"} as * a query operator. * <p> * <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators">Filtering * operators</a> * <p> * You can use the following filtering operators both with the system attributes * and element values: * <ul> * <li>{@link #filterEquals(String, String)}</li> * <li>{@link #filterLessThan(String, String)}</li> * <li>{@link #filterLessThanEquals(String, String)}</li> * <li>{@link #filterGreaterThan(String, String)}</li> * <li>{@link #filterGreaterThanEquals(String, String)}</li> * <li>{@link #filterRange(String, String, String)}</li> * <li>{@link #filterIn(String, String...)}</li> * <li>{@link #filterIn(String, Collection)}</li> * <li>{@link #filterContains(String, String)}</li> * <li>{@link #filterAny(String, String...)}</li> * <li>{@link #filterAny(String, Collection)}</li> * <li>{@link #filterAll(String, String...)}</li> * <li>{@link #filterAll(String, Collection)}</li> * </ul> * <p> * <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/arrays-vs-simple-types">Arrays * vs. simple types</a> * <p> * You can use the {@link #filterContains(String, String)}, * {@link #filterAny(String, String...)}, * {@link #filterAny(String, Collection)}, * {@link #filterAny(String, String...)}, and * {@link #filterAny(String, Collection)} filtering operators only with arrays. * Array attributes in Kontent * include the sitemap locations system object * ({@link System#getSitemapLocations()}), and the {@link AssetsElement}, * {@link LinkedItem}, {@link MultipleChoiceElement}, and * {@link TaxonomyElement} content elements. All the * other system attributes and content type elements are simple types, such as * strings or numbers. * <p> * <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/comparing-values">Comparing * values</a> * <p> * The filtering operators {@link #filterLessThan(String, String)}, * {@link #filterLessThanEquals(String, String)}, * {@link #filterGreaterThan(String, String)}, * {@link #filterGreaterThanEquals(String, String)}, and * {@link #filterRange(String, String, String)} work best with numbers. For * example, you can retrieve products with * price larger or equal to 15 by using * {@code .filterGreaterThanEquals("elements.price", "15")}. Attributes that * store * dates (such as the last_modified system attribute or * {@link DateTimeElement}s) are represented as strings. * <p> * If you use the filters on attributes with string values, the Delivery API * tries to perform a string comparison. For * example, to retrieve content items modified during February and March you'd * need to use a query such as * {@code .filterRange("system.last_modified", "2018-02-01", "2018-03-31")}, * specifying both the start and end dates. * <p> * Paging * You can get only a small subset of a large collection of content items with * the {@link #page(Integer, Integer)} * operator. The first argument is the number of pages to skip, with the second * being the page size. Using these * argument, you can display a specific page of results and iterate over a list * of content items or types. * <p> * For example, when you have a * {@link ContentItemsListingResponse#getPagination()} with a * {@link Pagination#getCount()} * of 10 items, you can use {@code .page(10, 10)} to retrieve the second page of * results. * <p> * For details about the pagination data in each listing response, see the * {@link Pagination} object. * <p> * <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Projection">Projection</a> * <p> * Choose which parts of content to retrieve with the * {@link #projection(String...)} operator. * <p> * For example, to retrieve only the elements with codenames 'title', 'summary', * and 'related_articles': * {@code .projection("title", "summary", "related_articles")} * <p> * <a href= * "https://kontent.ai/learn/reference/delivery-api#section/Linked-items-element">Linked * items</a> * <p> * Content items might reference linked items using the {@link LinkedItem}. * Recursively, these * linked items can reference another {@link LinkedItem} element. By default, * only one level of * linked items are returned. * <p> * If you want to include more than one level of linked items in a response, use * the * {@link #linkedItemsDepth(Integer)} operator. * <p> * If you want to exclude all linked items, use the * {@link #excludeLinkedItems()} operator. * <p> * Note: When retrieving content items, linked items cannot be filtered. * * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#operation/list-content-items"> * Kontent.ai API reference - Listing response</a> */ public class DeliveryParameterBuilder { static final String LANGUAGE = "language"; static final String ELEMENTS = "elements"; static final String ORDER = "order"; static final String DEPTH = "depth"; static final String SKIP = "skip"; static final String LIMIT = "limit"; static final String INCLUDE_TOTAL_COUNT = "includeTotalCount"; static final String NOT_EQUALS = "[neq]"; static final String EMPTY = "[empty]"; static final String NOT_EMPTY = "[nempty]"; static final String LESS_THAN = "[lt]"; static final String LESS_THAN_OR_EQUALS = "[lte]"; static final String GREATER_THAN = "[gt]"; static final String GREATER_THAN_OR_EQUALS = "[gte]"; static final String RANGE = "[range]"; static final String IN = "[in]"; static final String NOT_IN = "[nin]"; static final String CONTAINS = "[contains]"; static final String ANY = "[any]"; static final String ALL = "[all]"; static final String ASC = "[asc]"; static final String DESC = "[desc]"; List<NameValuePair> nameValuePairs = new ArrayList<>(); /** * Constructs a new DeliveryParameterBuilder. * * @return A newly constructed DeliveryParameterBuilder. */ public static DeliveryParameterBuilder params() { return new DeliveryParameterBuilder(); } /** * Attribute value is the same as the specified value. * * @param attribute The attribute. * @param value The value. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> */ public DeliveryParameterBuilder filterEquals(String attribute, String value) { if (attribute != null) { nameValuePairs.add(new NameValuePair(attribute, value)); } return this; } /** * Attribute value is not the same as the specified value. * * @param attribute The attribute. * @param value The value. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> */ public DeliveryParameterBuilder filterNotEquals( String attribute, String value) { if (attribute != null) { nameValuePairs.add( new NameValuePair(String.format("%s%s", attribute, NOT_EQUALS), value)); } return this; } /** * Attribute value is empty. * * @param attribute The attribute. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> */ public DeliveryParameterBuilder filterEmpty(String attribute) { if (attribute != null) { nameValuePairs.add( new NameValuePair(String.format("%s%s", attribute, EMPTY), null)); } return this; } /** * Attribute value is not empty. * * @param attribute The attribute. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> */ public DeliveryParameterBuilder filterNotEmpty(String attribute) { if (attribute != null) { nameValuePairs.add( new NameValuePair(String.format("%s%s", attribute, NOT_EMPTY), null)); } return this; } /** * Attribute value is less than the specified value. * * @param attribute The attribute. * @param value The value. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/comparing-values"> * More in Comparing values.</a> */ public DeliveryParameterBuilder filterLessThan( String attribute, String value) { if (attribute != null) { nameValuePairs.add( new NameValuePair(String.format("%s%s", attribute, LESS_THAN), value)); } return this; } /** * Attribute value is less than or equals the specified value. * * @param attribute The attribute. * @param value The value. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/comparing-values"> * More in Comparing values.</a> */ public DeliveryParameterBuilder filterLessThanEquals( String attribute, String value) { if (attribute != null) { nameValuePairs.add( new NameValuePair( String.format("%s%s", attribute, LESS_THAN_OR_EQUALS), value)); } return this; } /** * Attribute value is greater than the specified value. * * @param attribute The attribute. * @param value The value. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/comparing-values"> * More in Comparing values.</a> */ public DeliveryParameterBuilder filterGreaterThan( String attribute, String value) { if (attribute != null) { nameValuePairs.add( new NameValuePair(String.format("%s%s", attribute, GREATER_THAN), value)); } return this; } /** * Attribute value is greater than or equals the specified value. * * @param attribute The attribute. * @param value The value. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/comparing-values"> * More in Comparing values.</a> */ public DeliveryParameterBuilder filterGreaterThanEquals( String attribute, String value) { if (attribute != null) { nameValuePairs.add( new NameValuePair( String.format("%s%s", attribute, GREATER_THAN_OR_EQUALS), value)); } return this; } /** * Attribute value falls in the specified range of two values, both inclusive. * * @param attribute The attribute. * @param lower The lower bound value. * @param upper The upper bound value. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/comparing-values"> * More in Comparing values.</a> */ public DeliveryParameterBuilder filterRange( String attribute, String lower, String upper) { if (attribute != null) { nameValuePairs.add( new NameValuePair( String.format("%s%s", attribute, RANGE), String.join(",", lower, upper))); } return this; } /** * Attribute value is in the specified list of values. * * @param attribute The attribute. * @param values The values. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> */ public DeliveryParameterBuilder filterIn(String attribute, String... values) { if (attribute != null) { nameValuePairs.add( new NameValuePair( String.format("%s%s", attribute, IN), String.join(",", values))); } return this; } /** * Attribute value is in the specified list of values. * * @param attribute The attribute. * @param values The values. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> */ public DeliveryParameterBuilder filterIn( String attribute, Collection<String> values) { return filterIn(attribute, values.toArray(new String[0])); } /** * Attribute value is not in the specified list of values. * * @param attribute The attribute. * @param values The values. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> */ public DeliveryParameterBuilder filterNotIn( String attribute, String... values) { if (attribute != null) { nameValuePairs.add( new NameValuePair( String.format("%s%s", attribute, NOT_IN), String.join(",", values))); } return this; } /** * Attribute value is not in the specified list of values. * * @param attribute The attribute. * @param values The values. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> */ public DeliveryParameterBuilder filterNotIn( String attribute, Collection<String> values) { return filterNotIn(attribute, values.toArray(new String[0])); } /** * Attribute with an array of values contains the specified value. * * @param attribute The attribute. * @param value The value. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/arrays-vs-simple-types"> * More in Arrays vs. simple types.</a> */ public DeliveryParameterBuilder filterContains( String attribute, String value) { if (attribute != null) { nameValuePairs.add( new NameValuePair(String.format("%s%s", attribute, CONTAINS), value)); } return this; } /** * Attribute with an array of values contains any value from the specified list * of values. * * @param attribute The attribute. * @param values The values. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/arrays-vs-simple-types"> * More in Arrays vs. simple types.</a> */ public DeliveryParameterBuilder filterAny( String attribute, String... values) { if (attribute != null) { nameValuePairs.add( new NameValuePair( String.format("%s%s", attribute, ANY), String.join(",", values))); } return this; } /** * Attribute with an array of values contains any value from the specified list * of values. * * @param attribute The attribute. * @param values The values. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/arrays-vs-simple-types"> * More in Arrays vs. simple types.</a> */ public DeliveryParameterBuilder filterAny( String attribute, Collection<String> values) { return filterAny(attribute, values.toArray(new String[0])); } /** * Attribute with an array of values contains the specified list of values. * * @param attribute The attribute. * @param values The values. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/arrays-vs-simple-types"> * More in Arrays vs. simple types.</a> */ public DeliveryParameterBuilder filterAll( String attribute, String... values) { if (attribute != null) { nameValuePairs.add( new NameValuePair( String.format("%s%s", attribute, ALL), String.join(",", values))); } return this; } /** * Attribute with an array of values contains the specified list of values. * * @param attribute The attribute. * @param values The values. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/filtering-operators"> * More in Filtering operators.</a> * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Filtering-content/arrays-vs-simple-types"> * More in Arrays vs. simple types.</a> */ public DeliveryParameterBuilder filterAll( String attribute, Collection<String> values) { return filterAll(attribute, values.toArray(new String[0])); } /** * Sort the {@link ContentItemsListingResponse} by the attribute in ascending * order. As with filtering, you can use * both the 'system' and 'elements' attributes to sort data. * * @param attribute The attribute to sort on. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/tutorials/develop-apps/get-content/getting-content?tech=rest#a-ordering-content-items"> * More on Content Ordering</a> */ public DeliveryParameterBuilder orderByAsc(String attribute) { if (attribute != null) { nameValuePairs.add( new NameValuePair(ORDER, String.format("%s%s", attribute, ASC))); } return this; } /** * Sort the {@link ContentItemsListingResponse} by the attribute in descending * order. As with filtering, you can * use both the 'system' and 'elements' attributes to sort data. * * @param attribute The attribute to sort on. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/tutorials/develop-apps/get-content/getting-content?tech=rest#a-ordering-content-items"> * More on Content Ordering</a> */ public DeliveryParameterBuilder orderByDesc(String attribute) { if (attribute != null) { nameValuePairs.add( new NameValuePair(ORDER, String.format("%s%s", attribute, DESC))); } return this; } /** * Allows a subset of a query. This can be used with * {@link DeliveryClient#getItems(List)} and * {@link DeliveryClient#getItems(Class, List)}. If the {@link Page} convention * is desired, use * {@link DeliveryClient#getPageOfItems(Class, List)}. * * @param skip The number of items to skip. For the second page of 10, use the * value '10' and limit of '10'. * The API treats 'null' as a '0' skip value. * @param limit The size of the page. * @return This DeliveryParameterBuilder with the added operator. * @see Pagination * @see Page * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#operation/list-content-items">More * on Paging</a> */ public DeliveryParameterBuilder page(Integer skip, Integer limit) { if (skip != null) { nameValuePairs.add(new NameValuePair(SKIP, skip.toString())); } if (limit != null) { nameValuePairs.add(new NameValuePair(LIMIT, limit.toString())); } return this; } /** * Choose which parts of content to retrieve. * * For example, to retrieve only the elements with codenames 'title', 'summary', * and 'related_articles': * {@code .projection("title", "summary", "related_articles")} * * @param elements The elements to retrieve. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#tag/Projection">More on * Projection</a> */ public DeliveryParameterBuilder projection(String... elements) { if (elements != null) { nameValuePairs.add( new NameValuePair(ELEMENTS, String.join(",", elements))); } return this; } /** * Choose the depth of linked items to return. * * @param depth The number of levels of depth to return. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#section/Linked-items-element"> * More on Linked items</a> */ public DeliveryParameterBuilder linkedItemsDepth(Integer depth) { if (depth != null) { nameValuePairs.add(new NameValuePair(DEPTH, depth.toString())); } return this; } /** * Excludes all linked items. Analogous to {@code .linkedItemsDepth(0)} * * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#section/Linked-items-element">More * on Linked items</a> */ public DeliveryParameterBuilder excludeLinkedItems() { nameValuePairs.add(new NameValuePair(DEPTH, "0")); return this; } /** * Determines which language variant of content to return. By default, the API * returns content in the default * project language. If the requested content is not available in the specified * language variant, the API follows * the language fallbacks as configured in the Localization settings of the * project. Example: en-US. * * @param language The language variant to return. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/tutorials/manage-kontent-ai/projects/set-up-languages/">More * on Localization</a> * @see <a * href= * "https://kontent.ai/learn/tutorials/manage-kontent-ai/projects/set-up-languages/#section-language-fallbacks"> * Language fallbacks</a> */ public DeliveryParameterBuilder language(String language) { if (language != null) { nameValuePairs.add(new NameValuePair(LANGUAGE, language)); } return this; } /** * Determines which language variant of content to return. By default, the API * returns content in the default * project language. If the requested content is not available in the specified * language variant, the API follows * the language fallbacks as configured in the Localization settings of the * project. Example: en-US. * * @param language The language variant to return. * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/tutorials/manage-kontent-ai/projects/set-up-languages/">More * on Localization</a> * @see <a href= * "https://kontent.ai/learn/tutorials/manage-kontent-ai/projects/set-up-languages/#section-language-fallbacks"> * Language fallbacks</a> */ public DeliveryParameterBuilder language(Locale language) { if (language != null) { nameValuePairs.add( new NameValuePair(LANGUAGE, language.toString().replace('_', '-'))); } return this; } /** * Adds the information about the total number of content items matching your * query. * The number doesn't include linked items returned as part of the * modular_content property. * For the total number of items returned within the response, see the * X-Request-Charge header. * * Asking for the total number of content items might increase the response * time. * * When set to true, the pagination object returned in the API response contains * an additional total_count property. * * @return This DeliveryParameterBuilder with the added operator. * @see <a href= * "https://kontent.ai/learn/reference/delivery-api#section/Content-item-object">Content * items</a> */ public DeliveryParameterBuilder includeTotalCount() { nameValuePairs.add(new NameValuePair(INCLUDE_TOTAL_COUNT, "true")); return this; } /** * Builds the query parameters to pass into the {@link DeliveryClient} from this * DeliveryParametersBuilder. * * @return A list of NameValuePairs representing API query parameters. */ public List<NameValuePair> build() { return nameValuePairs; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/Element.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import java.util.List; /** * Parent object model of individual elements * <p> * When retrieving content items or content types, you get an elements collection as a part of the retrieved item or * type. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = TextElement.class, name = TextElement.TYPE_VALUE), @JsonSubTypes.Type(value = RichTextElement.class, name = RichTextElement.TYPE_VALUE), @JsonSubTypes.Type(value = MultipleChoiceElement.class, name = MultipleChoiceElement.TYPE_VALUE), @JsonSubTypes.Type(value = NumberElement.class, name = NumberElement.TYPE_VALUE), @JsonSubTypes.Type(value = DateTimeElement.class, name = DateTimeElement.TYPE_VALUE), @JsonSubTypes.Type(value = AssetsElement.class, name = AssetsElement.TYPE_VALUE), @JsonSubTypes.Type(value = LinkedItem.class, name = LinkedItem.TYPE_VALUE), @JsonSubTypes.Type(value = TaxonomyElement.class, name = TaxonomyElement.TYPE_VALUE), @JsonSubTypes.Type(value = UrlSlugElement.class, name = UrlSlugElement.TYPE_VALUE), @JsonSubTypes.Type(value = CustomElement.class, name = CustomElement.TYPE_VALUE) }) @lombok.Getter @lombok.Setter @lombok.ToString(exclude = "parent") @lombok.EqualsAndHashCode(exclude = "parent") @lombok.NoArgsConstructor public abstract class Element<T> { /** * Type of the element * <p> * Valid values: text, rich_text, number, multiple_choice, date_time, asset, modular_content * ({@link LinkedItem}), taxonomy, url_slug. * * @param type the type of element * @return the codename for this element type */ @JsonProperty("type") String type; /** * Display name of the element * * @param name the name of this element * @return the display name of this element */ @JsonProperty("name") String name; /** * The codename for this element * <p> * Note: This is only populated when querying an individual content type element. * * @param codeName the codename of this element * @return codename for this content type element as defined in a content type * @see DeliveryClient#getContentTypeElement(String, String) * @see DeliveryClient#getContentTypeElement(String, String, List) */ @JsonProperty("codename") String codeName; /** * A reference to the parent ContentItem to this element. * * @param parent the parent to this * @return the parent to this */ @JsonIgnore ContentItem parent; /** * Returns the value of the element. * @return The value of the element. */ public abstract T getValue(); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/ElementMapping.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Can be placed on fields of POJOs to indicate that it should be mapped to an element in a {@link ContentItem}. * * @see ContentItemResponse#castTo(Class) * @see ContentItemsListingResponse#castTo(Class) */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface ElementMapping { /** * The codename of a {@link Element} to map this field onto. * * @return an {@link Element} codename */ String value(); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/Header.java
package kontent.ai.delivery; @lombok.Data @lombok.AllArgsConstructor public class Header { private String name; private String value; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/Image.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Object model for Image elements * <p> * Images associated with rich text elements * * @see RichTextElement */ @lombok.Getter @lombok.Setter @lombok.ToString @lombok.EqualsAndHashCode @lombok.NoArgsConstructor public class Image { /** * ID of the image * * @param imageId Sets the imageId of this * @return This imageId */ @JsonProperty("image_id") String imageId; /** * Description of the image * <p> * Used for the alt attribute of an &lt;img&gt; tag. * * @param description Sets the description of this * @return The image description of this */ @JsonProperty("description") String description; /** * Absolute URL for the image * * @param url Sets the url of this * @return An absolute URL image hosted by Kontent.ai */ @JsonProperty("url") String url; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/InlineContentItemsResolver.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * Concrete implementations of this can resolve strongly typed content types included inline rich text. * * @param <T> The strongly typed content type model this resolver supports. */ public abstract class InlineContentItemsResolver<T> { //Neil Gafter Super Type Token, http://gafter.blogspot.com/2006/12/super-type-tokens.html private final Type type; public InlineContentItemsResolver() { Type superclass = getClass().getGenericSuperclass(); if (superclass instanceof Class) { throw new IllegalArgumentException("Missing type parameter."); } this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0]; } /** * Returns the raw text of what to insert into the rich text with the given inline strongly typed content type of * type T. * * @param data An instance of a strongly typed content item. * @return Raw text to insert into the rich text. */ public abstract String resolve(T data); protected Type getType() { return type; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/KontentError.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Kontent.ai error response * <p> * Kontent.ai returns standard HTTP status codes to indicate success or failure of a request. In general, codes in * the 2xx range indicate a successful request, codes in the 4xx range indicate errors caused by an incorrect input * (for example, providing incorrect API key), and codes in the 5xx range indicate an error on our side. * <p> * For troubleshooting failed requests, the Kontent.ai APIs provide error messages defined in a consumable format to * help you identify and fix the issue. For example, when you request a content item that does not exist (e.g., you * mistype its codename), the API returns a 404 HTTP error along with a JSON message. * <p> * If you cannot identify and resolve an issue with your API call, you can contact us with the response status and the * unique error ID. Hint: use the chat button in the bottom right corner of * <a href="https://kontent.ai/learn/reference">this page</a>. */ @lombok.Getter @lombok.Setter @lombok.ToString @lombok.EqualsAndHashCode @lombok.NoArgsConstructor public class KontentError implements java.io.Serializable { /** * Returns the error message provided by Kontent.ai detailing the error. * * @param message Sets the message of this. * @return The error message from Kontent.ai. */ @JsonProperty("message") String message; /** * Returns a unique ID that can be provided to Kontent.ai for support in relation to the error. * * @param requestId Sets the request ID of this. * @return The unique ID for this error */ @JsonProperty("request_id") String requestId; /** * Returns the HTTP error code returned by Kontent.ai. * <table> * <caption>HTTP error codes</caption> * <tr><td>400 - Bad Request</td><td>The request was not understood. Check for a missing required parameter, or an * invalid parameter value.</td></tr> * <tr><td>401 - Unauthorized</td><td>The provided API key is invalid or missing. See * {@link DeliveryClient#DeliveryClient(String, String)}.</td></tr> * <tr><td>403 - Forbidden</td><td>The provided API key is invalid for the requested project.</td></tr> * <tr><td>404 - Not Found</td><td>The requested resource doesn't exist. Try checking the resource name for typos. * </td></tr> * </table> * * @param errorCode Sets the errorCode of this. * @return The http error code. */ @JsonProperty("error_code") int errorCode; /** * Returns the specific code returned by the Kontent.ai error response. * * @param specificCode Sets the specific code of this. * @return The specific code returned by the Kontent.ai error response. */ @JsonProperty("specific_code") int specificCode; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/KontentErrorException.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; /** * Thrown to indicate failure of a Kontent.ai request. * * @see KontentError */ public class KontentErrorException extends RuntimeException implements KontentException { private final KontentError kontentError; private boolean shouldRetry; /** * Thrown to indicate failure of a Kontent.ai request * * @param kontentError The original KontentError */ public KontentErrorException(KontentError kontentError, boolean shouldRetry) { super(kontentError.getMessage()); this.kontentError = kontentError; this.shouldRetry = shouldRetry; } /** * Returns the original error provided by Kontent.ai. Useful for debugging. * * @return The original KontentError * @see KontentError */ public KontentError getKontentError() { return kontentError; } @Override public boolean shouldRetry() { return this.shouldRetry; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/KontentException.java
package kontent.ai.delivery; public interface KontentException { boolean shouldRetry(); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/KontentIOException.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import java.io.IOException; /** * Thrown when an {@link IOException} is thrown when executing against the Kontent.ai API. Generally means * connectivity problems with Kontent.ai of problem parsing {@link KontentError} from body. */ public class KontentIOException extends RuntimeException implements KontentException { private boolean shouldRetry; KontentIOException(String message, boolean shouldRetry) { super(message); this.shouldRetry = shouldRetry; } KontentIOException(IOException cause, boolean shouldRetry) { super(cause); this.shouldRetry = shouldRetry; } @Override public boolean shouldRetry() { return this.shouldRetry; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/KontentRetryException.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; /** * Thrown when retry attempts are is thrown when executing against the Kontent.ai API. Generally means * connectivity problems with Kontent.ai. */ public class KontentRetryException extends RuntimeException implements KontentException { private final int maxRetryAttempts; KontentRetryException(int maxRetryAttempts) { super(String.format("Retry attempty reached max retry attempts (%d) ", maxRetryAttempts)); this.maxRetryAttempts = maxRetryAttempts; } public int getMaxRetryAttempts() { return maxRetryAttempts; } @Override public boolean shouldRetry() { return false; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/Link.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Object model for Link elements * <p> * Links associated with rich text elements * * @see RichTextElement */ @lombok.Getter @lombok.Setter @lombok.ToString @lombok.EqualsAndHashCode @lombok.NoArgsConstructor public class Link { /** * Content type of the content item * * @param type Sets the type of this. * @return The content item type codename. */ @JsonProperty("type") String type; /** * Display name of the element * * @param codename Sets the codename of this. * @return The codename of the link element. */ @JsonProperty("codename") String codename; /** * URL slug of the content item * <p> * Empty string if the content item's type does not use a URL slug element * * @param urlSlug Sets the urlSlug of this. * @return URL slug of the content item. */ @JsonProperty("url_slug") String urlSlug; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/LinkedItem.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Object model for Linked Item elements */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class LinkedItem extends Element<List<String>> { // The API refers to linked items by their old name static final String TYPE_VALUE = "modular_content"; /** * A list of {@link ContentItem} codenames * <p> * The relations to content items saved in a linked item element are represented as a list of strings. Each * string being a codename of a content item. * * @param value Sets the value of this. * @return A list of codenames referencing {@link ContentItem}. */ @JsonProperty("value") List<String> value; public LinkedItem() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/LinkedItemProvider.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import java.util.Map; interface LinkedItemProvider { Map<String, ContentItem> getLinkedItems(); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/MultipleChoiceElement.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Object model for Multiple choice elements */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class MultipleChoiceElement extends Element<List<Option>> { static final String TYPE_VALUE = "multiple_choice"; /** * The value of the selected elements. * <p> * The value of a Multiple choice element is a list of option objects. Each option object has a name and codename. * <p> * Note, this is not returned when querying for the element by type. * * @param value Sets the value of this * @return A list of selected elements. * @see Option */ @JsonProperty("value") List<Option> value; /** * The available option elements on this content type element. * <p> * The value of a Multiple choice element is a list of option objects. Each option object has a name and codename. * <p> * Note, this is only returned when querying for the element by type. * * @param options Sets the options of this. * @return A list of option elements. * @see Option */ @JsonProperty("options") List<Option> options; public MultipleChoiceElement() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/NameValuePair.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import lombok.AllArgsConstructor; import lombok.Data; import java.io.Serializable; @Data @AllArgsConstructor public class NameValuePair implements Serializable { private String name; private String value; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/NumberElement.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Object model for Number elements */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class NumberElement extends Element<Double> { static final String TYPE_VALUE = "number"; /** * The value of a Number element is a decimal number. If empty, the value is null. * * @param value Sets the value of this. * @return The value of the number. */ @JsonProperty("value") Double value; public NumberElement() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/Option.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Object model for option values in a {@link MultipleChoiceElement} */ @lombok.Getter @lombok.Setter @lombok.ToString @lombok.EqualsAndHashCode @lombok.NoArgsConstructor public class Option { /** * The display name of the option * * @param name Sets the display name of this. * @return The name of the option. */ @JsonProperty("name") String name; /** * The codename of the option * * @param codename Sets the codename of this. * @return The codename of the option. */ @JsonProperty("codename") String codename; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/Page.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import java.util.List; /** * Represents a page of results from the Kontent.ai API. * * @param <T> The type of results. */ public class Page<T> { Pagination pagination; List<T> contentItems; Class<T> tClass; public Page(ContentItemsListingResponse response, Class<T> tClass) { this.pagination = response.getPagination(); this.contentItems = response.castTo(tClass); this.tClass = tClass; } /** * Returns the size of the page. * * @return the size of the page. */ public int getSize() { return pagination.getCount(); } /** * Returns the page content as {@link List}. * * @return the list of content */ public List<T> getContent() { return contentItems; } /** * Returns whether the page has content at all. * * @return true if the page has content */ public boolean hasContent() { return contentItems != null && !contentItems.isEmpty(); } /** * Returns whether the current page is the first one. * * @return true if it is the first */ public boolean isFirst() { return pagination.skip == 0; } /** * Returns whether the current page is the last one. * * @return if this is the last page. */ public boolean isLast() { return pagination.nextPage.isEmpty(); } /** * Returns if there is a next page. * * @return if there is a next page. */ public boolean hasNext() { return !pagination.nextPage.isEmpty(); } /** * Returns if there is a previous page. * * @return if there is a previous page. */ public boolean hasPrevious() { return pagination.skip > 0; } /** * Returns the pagination information from the request * * @return a pagination object */ public Pagination getPagination() { return pagination; } protected Class<T> getType() { return tClass; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/Pagination.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Pagination object */ @lombok.Getter @lombok.Setter @lombok.ToString @lombok.EqualsAndHashCode @lombok.NoArgsConstructor public class Pagination { /** * Number of content items skipped from the response * * @param skip Sets skip on this. * @return Reflects the value set by the {@link DeliveryParameterBuilder#page(Integer, Integer)} query * parameter. */ @JsonProperty("skip") Integer skip; /** * Number of content items returned from the response * * @param limit Sets limit on this. * @return Reflects the value set by the {@link DeliveryParameterBuilder#page(Integer, Integer)} query * parameter. */ @JsonProperty("limit") Integer limit; /** * Number of retrieved content items * <p> * If the limit and skip query parameters ({@link DeliveryParameterBuilder#page(Integer, Integer)}) aren't set, the * count attribute will contain the total number of content items matching the specified filtering parameters. * * @param count Sets count on this. * @return Number of retrieved content items. */ @JsonProperty("count") Integer count; /** * Number of total items matching the search criteria * <p> * Is set only when {@link DeliveryParameterBuilder#includeTotalCount()} used for loading {@link ContentItemsListingResponse}. * * @param totalCount Sets total_count on this. * @return Number of total content items matching the search criteria or null. */ @JsonProperty("total_count") Integer totalCount; /** * URL to the next page of results. Generally speaking, this value will not be needed. * Consider using {@link DeliveryClient#getNextPage(Page)}. * * @param nextPage Sets nextPage on this. * @return URL to the next page of results. */ @JsonProperty("next_page") String nextPage; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/RichTextElement.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Map; /** * Object model for Rich text elements. * <p> * The value of a Rich text element is formatted text. * <p> * Besides formatted text in the element's value attribute, Rich text elements can contain inline images and links * to other content items. */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class RichTextElement extends TextElement { static final String TYPE_VALUE = "rich_text"; /** * Images associated with this rich text element. * * @param images Sets the images of this. * @return A map of {@link Image} objects. * @see Image */ @JsonProperty("images") Map<String, Image> images; /** * Links associated with this rich text element. * <p> * Each object in the links collection represents a content item ID in the GUID format, * e.g., f4b3fc05-e988-4dae-9ac1-a94aba566474. * * @param links Sets the links of this. * @return A map of {@link Link} objects. */ @JsonProperty("links") Map<String, Link> links; @JsonProperty("modular_content") List<String> linkedItems; public RichTextElement() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/RichTextElementConverter.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import kontent.ai.delivery.template.TemplateEngineConfig; import kontent.ai.delivery.template.TemplateEngineInlineContentItemsResolver; import kontent.ai.delivery.template.TemplateEngineModel; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RichTextElementConverter { ContentLinkUrlResolver contentLinkUrlResolver; BrokenLinkUrlResolver brokenLinkUrlResolver; RichTextElementResolver richTextElementResolver; TemplateEngineConfig templateEngineConfig; StronglyTypedContentItemConverter stronglyTypedContentItemConverter; /* Regex prior to the Java \ escapes: <a[^>]+?data-item-id=\"(?<id>[^\"]+)\"[^>]*> Regex explanation: <a matches the characters <a literally (case sensitive) Match a single character not present in the list below [^>]+? +? Quantifier — Matches between one and unlimited times, as few times as possible, expanding as needed (lazy) > matches the character > literally (case sensitive) data-item-id= matches the characters data-item-id= literally (case sensitive) \" matches the character " literally (case sensitive) Named Capture Group id (?<id>[^\"]+) Match a single character not present in the list below [^\"]+ + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) \" matches the character " literally (case sensitive) \" matches the character " literally (case sensitive) Match a single character not present in the list below [^>]* * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy) > matches the character > literally (case sensitive) > matches the character > literally (case sensitive) Global pattern flags g modifier: global. All matches (don't return after first match) */ private Pattern linkPattern = Pattern.compile("<a[^>]+?data-item-id=\"(?<id>[^\"]+)\"[^>]*>"); private Pattern linkedItemPattern = Pattern.compile("<object type=\"application/kenticocloud\" " + "(?<attrs>[^>]+)></object>"); public RichTextElementConverter( ContentLinkUrlResolver contentLinkUrlResolver, BrokenLinkUrlResolver brokenLinkUrlResolver, RichTextElementResolver richTextElementResolver, TemplateEngineConfig templateEngineConfig, StronglyTypedContentItemConverter stronglyTypedContentItemConverter) { this.contentLinkUrlResolver = contentLinkUrlResolver; this.brokenLinkUrlResolver = brokenLinkUrlResolver; this.richTextElementResolver = richTextElementResolver; this.templateEngineConfig = templateEngineConfig; this.stronglyTypedContentItemConverter = stronglyTypedContentItemConverter; } public void process(List<ContentItem> orig) { for (ContentItem contentItem : orig) { process(contentItem); } } public void process(ContentItem orig) { for (Map.Entry<String, Element> entry : orig.getElements().entrySet()) { Element element = entry.getValue(); if (element instanceof RichTextElement) { RichTextElement richTextElement = (RichTextElement) element; richTextElement.setValue(resolveLinks(richTextElement)); richTextElement.setValue(resolveLinkedItems(richTextElement)); if (richTextElementResolver != null) { richTextElement.setValue(richTextElementResolver.resolve(richTextElement.getValue())); } } } } public RichTextElement convert(RichTextElement orig) { if (orig.getValue() == null) { return orig; } orig.setValue(resolveLinks(orig)); orig.setValue(resolveLinkedItems(orig)); if (richTextElementResolver != null) { orig.setValue(richTextElementResolver.resolve(orig.getValue())); } return orig; } private String resolveLinks(RichTextElement element) { if (element.links == null) { return element.getValue(); } Matcher matcher = linkPattern.matcher(element.getValue()); StringBuffer buffer = new StringBuffer(); while (matcher.find()) { Link link = element.links.get(matcher.group("id")); String url = ""; if (link != null && contentLinkUrlResolver != null) { url = contentLinkUrlResolver.resolveLinkUrl(link); } else if (brokenLinkUrlResolver != null){ url = brokenLinkUrlResolver.resolveBrokenLinkUrl(); } matcher.appendReplacement(buffer, resolveMatch(matcher.group(0), url)); } matcher.appendTail(buffer); return buffer.toString(); } private String resolveLinkedItems(RichTextElement element) { return resolveLinkedItemsRecursively(element, element.getValue(), new ArrayList<>()); } private String resolveLinkedItemsRecursively( RichTextElement element, String content, Collection<String> itemsAlreadyResolved) { if (element.getLinkedItems() == null || element.getParent() == null) { return element.getValue(); } Matcher matcher = linkedItemPattern.matcher(content); StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String attrs = matcher.group("attrs"); InlineModularContentDataAttributes dataAttributes = InlineModularContentDataAttributes.fromAttrs(attrs); String codename = dataAttributes.getCodename(); ContentItem linkedItem = element.getParent().getLinkedItem(codename); InternalInlineContentItemResolver resolver = null; // Check to see if we encountered a cycle in our tree, if so, halt resolution if (!itemsAlreadyResolved.contains(codename)) { resolver = resolveMatch(element, linkedItem); } if (resolver == null) { // The linked item isn't fetched, doesn't exist, we encountered a cycle, or there is no resolver, // preserve the <object> tag matcher.appendReplacement(buffer, matcher.group(0)); } else { String resolvedString = resolver.resolve(); // The resolved String may have an inline linked item object element, so recursively call, but add // the resolved linked item to the blacklist below to avoid an infinite cyclic loop ArrayList<String> resolvedItems = new ArrayList<>(itemsAlreadyResolved); resolvedItems.add(codename); resolvedString = resolveLinkedItemsRecursively(element, resolvedString, resolvedItems); // Make resolved replacement string a literal string to make sure dollar signs are not interpreted as // capturing groups and add resolved string to the buffer matcher.appendReplacement(buffer, Matcher.quoteReplacement(resolvedString)); } } matcher.appendTail(buffer); return buffer.toString(); } private InternalInlineContentItemResolver resolveMatch(RichTextElement element, ContentItem linkedItem) { if (linkedItem != null) { for (Element linkedItemElement : linkedItem.getElements().values()) { if (linkedItemElement instanceof RichTextElement) { RichTextElement embeddedRichTextElement = (RichTextElement) linkedItemElement; embeddedRichTextElement.setValue(resolveLinks(embeddedRichTextElement)); } } InlineContentItemsResolver resolverForType = stronglyTypedContentItemConverter.getResolverForType(linkedItem); if (resolverForType != null) { Object convertedLinkedItem = linkedItem.castTo((Class) resolverForType.getType()); return () -> resolverForType.resolve(convertedLinkedItem); } else if (templateEngineConfig != null) { TemplateEngineInlineContentItemsResolver supportedResolver; Object linkedItemModel = linkedItem.castToDefault(); TemplateEngineModel model = new TemplateEngineModel(); model.setInlineContentItem(linkedItemModel); // TODO: Add support for adding Locale from query if it exists model.addVariable("parent", element); model.addVariables(templateEngineConfig.getDefaultModelVariables()); supportedResolver = getTemplateResolver(model); if (supportedResolver != null) { return () -> supportedResolver.resolve(model); } } } return null; } private String resolveMatch(String match, String url) { return match.replace("href=\"\"", String.format("href=\"%s\"", StringUtils.escapeHtml(url))); } private TemplateEngineInlineContentItemsResolver getTemplateResolver(TemplateEngineModel model) { if (templateEngineConfig == null) { return null; } List<TemplateEngineInlineContentItemsResolver> templateResolvers = templateEngineConfig.getResolvers(); if (templateResolvers != null) { for (TemplateEngineInlineContentItemsResolver templateResolver : templateResolvers) { if (templateResolver.supports(model)) { return templateResolver; } } } return null; } private interface InternalInlineContentItemResolver { String resolve(); } @lombok.Getter @lombok.Setter @lombok.Builder private static class InlineModularContentDataAttributes { private static Pattern DATA_ATTRIBUTE_PATTERN = Pattern.compile("(data-\\w+)=\"(\\w+)\""); private String type; private String rel; private String codename; private static InlineModularContentDataAttributes fromAttrs(String attrs) { Matcher matcher = DATA_ATTRIBUTE_PATTERN.matcher(attrs); InlineModularContentDataAttributesBuilder builder = InlineModularContentDataAttributes.builder(); while (matcher.find()) { String key = matcher.group(1); String value = matcher.group(2); switch (key) { case "data-type": builder.type(value); break; case "data-rel": builder.rel(value); break; case "data-codename": builder.codename(value); break; default: break; } } return builder.build(); } } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/RichTextElementResolver.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; /** * RichTextElementResolvers added to the {@link DeliveryClient} will be invoked when resolving any * {@link RichTextElement}. */ public interface RichTextElementResolver { /** * The current state of the rich text element's value is provided. This may have been changed from the original by * the {@link ContentLinkUrlResolver}, {@link BrokenLinkUrlResolver}, {@link InlineContentItemsResolver}s, and/or * previously ordered {@link RichTextElementResolver}s. * <p> * It is expected to return the state of the rich text element, even if no manipulation is performed. * * @param content The current state of the rich text element's value. * @return The new state of the rich text element's value. */ String resolve(String content); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/SimpleInMemoryCacheManager.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.databind.JsonNode; import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** * Uses the JVM memory to cache results. * It also allows cache to be invalidated based on both the codename and language of content items. * This makes it easy to invalidate the cache for incoming webhooks. * <p> * This implementation mainly serves as an example. * Do not use this cache manager when your application is deployed as multiple replicas! * In that case a centralized cache (e.g. Redis) is advisable. */ @Slf4j public class SimpleInMemoryCacheManager implements CacheManager { final protected Map<String, JsonNode> cache = Collections.synchronizedMap(new HashMap<>()); final protected Map<String, Set<String>> tagsForUrls = Collections.synchronizedMap(new HashMap<>()); final protected AtomicInteger queries = new AtomicInteger(0); final protected AtomicInteger hits = new AtomicInteger(0); final protected AtomicInteger puts = new AtomicInteger(0); @Override public JsonNode get(final String url) { log.debug("Cache get"); queries.incrementAndGet(); JsonNode jsonNode = cache.computeIfPresent(url, (key, val) -> { log.debug("Cache hit"); hits.incrementAndGet(); return val; }); return jsonNode; } @Override public void put(final String url, final JsonNode jsonNode, final List<ContentItem> containedContentItems) { puts.incrementAndGet(); cache.put(url, jsonNode); // Store tags that point to the given url. // Tags are created for every code_name+language combination that can be determined from the given containedContentItems Optional.ofNullable(containedContentItems) .map(this::createCacheTags) .orElse(Collections.emptySet()) .forEach(cacheTag -> getUrlsForTag(cacheTag).add(url)); } public void invalidate(final String url) { cache.remove(url); } public void invalidate(final CacheTag cacheTag) { // Possible race condition Set<String> urls = getUrlsForTag(cacheTag); urls.forEach(url -> { invalidate(url); urls.remove(url); }); } private Set<String> getUrlsForTag(final CacheTag cacheTag) { tagsForUrls.putIfAbsent(cacheTag.toString(), Collections.synchronizedSet(new HashSet<>())); return tagsForUrls.get(cacheTag.toString()); } private Set<CacheTag> createCacheTags(final List<ContentItem> containedContentItems) { return containedContentItems.stream() .map(this::createCacheTags) .flatMap(Set::stream) .collect(Collectors.toSet()); } private Set<CacheTag> createCacheTags(final ContentItem contentItem) { Set<CacheTag> tags = new HashSet<>(); tags.add(new CacheTag(contentItem)); tags.addAll( contentItem.getLinkedItemProvider().getLinkedItems().values().stream() .map(CacheTag::new) .collect(Collectors.toSet()) ); return tags; } @Data @AllArgsConstructor public static class CacheTag { String codeName; String language; public CacheTag(ContentItem contentItem) { codeName = contentItem.getSystem().getCodename(); language = contentItem.getSystem().getLanguage(); } @Override public String toString() { return String.format("%s#%s", codeName, language); } } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/StringUtils.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; public class StringUtils { private StringUtils() { throw new IllegalStateException("Utility class"); } public static String escapeHtml(String s) { StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') { out.append("&#"); out.append((int) c); out.append(';'); } else { out.append(c); } } return out.toString(); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/StronglyTypedContentItemConverter.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.madrobot.beans.BeanInfo; import com.madrobot.beans.IntrospectionException; import com.madrobot.beans.Introspector; import com.madrobot.beans.PropertyDescriptor; import io.github.classgraph.ClassGraph; import io.github.classgraph.ClassInfoList; import io.github.classgraph.ScanResult; import org.jetbrains.annotations.NotNull; import java.lang.reflect.*; import java.util.*; @lombok.extern.slf4j.Slf4j public class StronglyTypedContentItemConverter { private HashMap<String, String> contentTypeToClassNameMapping = new HashMap<>(); private HashMap<String, String> classNameToContentTypeMapping = new HashMap<>(); private HashMap<String, InlineContentItemsResolver> typeNameToInlineResolverMapping = new HashMap<>(); protected StronglyTypedContentItemConverter() { //protected constructor } protected void registerType(String contentType, Class<?> clazz) { contentTypeToClassNameMapping.put(contentType, clazz.getName()); classNameToContentTypeMapping.put(clazz.getName(), contentType); } protected void registerType(Class<?> clazz) { ContentItemMapping clazzContentItemMapping = clazz.getAnnotation(ContentItemMapping.class); if (clazzContentItemMapping == null) { throw new IllegalArgumentException("Passed in class must be annotated with @ContentItemMapping, " + "if this is not possible, please use registerType(String, Class)"); } registerType(clazzContentItemMapping.value(), clazz); log.debug("Registered type for {}", clazz.getSimpleName()); } protected String getContentType(Class tClass) { if (classNameToContentTypeMapping.containsKey(tClass.getName())) { return classNameToContentTypeMapping.get(tClass.getName()); } return null; } protected void registerInlineContentItemsResolver(InlineContentItemsResolver resolver) { typeNameToInlineResolverMapping.put(resolver.getType().getTypeName(), resolver); } protected InlineContentItemsResolver getResolverForType(String contentType) { if (contentTypeToClassNameMapping.containsKey(contentType) && typeNameToInlineResolverMapping.containsKey(contentTypeToClassNameMapping.get(contentType))) { return typeNameToInlineResolverMapping.get(contentTypeToClassNameMapping.get(contentType)); } return null; } protected InlineContentItemsResolver getResolverForType(ContentItem contentItem) { System system = contentItem.getSystem(); if (system != null) { return getResolverForType(system.getType()); } return null; } /** * Not working on Android platform because of JVM and Dalvik differences, please use {@link DeliveryClient#registerType(Class)} instead * @param basePackage name of the base package */ protected void scanClasspathForMappings(String basePackage) { try (ScanResult scanResult = new ClassGraph() .enableAllInfo() .acceptPackages(basePackage) .scan()) { ClassInfoList mappings = scanResult.getClassesWithAnnotation(ContentItemMapping.class.getName()); mappings.loadClasses().forEach(classWithAnnotation -> { ContentItemMapping contentItemMapping = classWithAnnotation.getAnnotation(ContentItemMapping.class); registerType(contentItemMapping.value(), classWithAnnotation); }); ClassInfoList inlineResolvers = scanResult.getSubclasses(InlineContentItemsResolver.class.getName()); inlineResolvers.loadClasses(InlineContentItemsResolver.class).forEach(subclass -> { try { registerInlineContentItemsResolver(subclass.getConstructor().newInstance()); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) { // No default constructor, no InlineContentItemsResolver. } }); } } Object convert(ContentItem item, Map<String, ContentItem> linkedItems, String contentType) { String className = contentTypeToClassNameMapping.get(contentType); Class<?> mappingClass; try { mappingClass = Class.forName(className); } catch (ClassNotFoundException e) { return item; } if (mappingClass == null) { return item; } return convert(item, linkedItems, mappingClass); } <T> T convert(ContentItem item, Map<String, ContentItem> linkedItems, Class<T> tClass) { if (tClass == Object.class) { String className = contentTypeToClassNameMapping.get(item.getSystem().getType()); if (className == null) { return (T) item; } Class<?> mappingClass = null; try { mappingClass = Class.forName(className); } catch (ClassNotFoundException e) { return (T) item; } if (mappingClass == null) { return (T) item; } return (T) convert(item, linkedItems, mappingClass); } if (tClass == ContentItem.class) { return (T) item; } T bean = null; try { //Invoke the default constructor bean = tClass.getConstructor().newInstance(); //Get the bean properties Field[] fields = tClass.getDeclaredFields(); //Inject mappings for (Field field : fields) { Object value = getValueForField(item, linkedItems, bean, field); if (value != null) { Optional<PropertyDescriptor> propertyDescriptor = getPropertyDescriptor(bean, field); if (propertyDescriptor.isPresent()) { propertyDescriptor.get().getWriteMethod().invoke(bean, value); } } } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) { handleReflectionException(e); } //Return bean return bean; } private Object getValueForField( ContentItem item, Map<String, ContentItem> linkedItems, Object bean, Field field) { //Inject System object if (field.getType() == System.class) { return item.getSystem(); } //Explicit checks //Check to see if this is an explicitly mapped Element ElementMapping elementMapping = field.getAnnotation(ElementMapping.class); if (elementMapping != null && item.getElements().containsKey(elementMapping.value())) { return item.getElements().get(elementMapping.value()).getValue(); } //Check to see if this is an explicitly mapped ContentItem ContentItemMapping contentItemMapping = field.getAnnotation(ContentItemMapping.class); if (contentItemMapping != null && isListOrMap(field.getType()) && item.getElements().containsKey(contentItemMapping.value()) && item.getElements().get(contentItemMapping.value()) instanceof LinkedItem) { LinkedItem linkedItemElement = (LinkedItem) item.getElements().get(contentItemMapping.value()); Map<String, ContentItem> referencedLinkedItems = new LinkedHashMap<>(); for (String codename : linkedItemElement.getValue()) { referencedLinkedItems.put(codename, linkedItems.get(codename)); } return getCastedLinkedItemsForListOrMap(bean, field, referencedLinkedItems); } if (contentItemMapping != null && linkedItems.containsKey(contentItemMapping.value())) { return getCastedLinkedItemsForField(field.getType(), contentItemMapping.value(), linkedItems); } //Implicit checks String candidateCodename = fromCamelCase(field.getName()); //Check to see if this is an implicitly mapped Element if (item.getElements().containsKey(candidateCodename)) { return item.getElements().get(candidateCodename).getValue(); } //Check to see if this is an implicitly mapped ContentItem if (linkedItems.containsKey(candidateCodename)) { return getCastedLinkedItemsForField(field.getType(), candidateCodename, linkedItems); } //Check to see if this is a collection of implicitly mapped ContentItem if (isListOrMap(field.getType())) { return getCastedLinkedItemsForListOrMap(bean, field, linkedItems); } return null; } private Object getCastedLinkedItemsForField( Class<?> clazz, String codename, Map<String, ContentItem> linkedItems) { ContentItem linkedItemsItem = linkedItems.get(codename); if (clazz == ContentItem.class) { return linkedItemsItem; } Map<String, ContentItem> linkedItemsForRecursion = copyLinkedItemsWithExclusion(linkedItems, codename); return convert(linkedItemsItem, linkedItemsForRecursion, clazz); } private Object getCastedLinkedItemsForListOrMap( Object bean, Field field, Map<String, ContentItem> linkedItems) { Type type = getType(bean, field); if (type == null) { // We have failed to get the type, probably due to a missing setter, skip this field log.debug("Failed to get type from {} (probably due to a missing setter), {} skipped", bean, field); return null; } if (type == ContentItem.class) { return castCollection(field.getType(), linkedItems); } Class<?> listClass = (Class<?>) type; String contentType = null; ContentItemMapping clazzContentItemMapping = listClass.getAnnotation(ContentItemMapping.class); if (clazzContentItemMapping != null) { contentType = clazzContentItemMapping.value(); } if (contentType == null && classNameToContentTypeMapping.containsKey(listClass.getName())) { contentType = classNameToContentTypeMapping.get(listClass.getName()); } if (contentType != null) { HashMap convertedLinkedItems = new HashMap<>(); for (Map.Entry<String, ContentItem> entry : linkedItems.entrySet()) { if (entry.getValue() != null && contentType.equals(entry.getValue().getSystem().getType())) { Map<String, ContentItem> linkedItemsForRecursion = copyLinkedItemsWithExclusion(linkedItems, entry.getKey()); convertedLinkedItems.put(entry.getKey(), convert(entry.getValue(), linkedItemsForRecursion, listClass)); } } return castCollection(field.getType(), convertedLinkedItems); } return null; } private static String fromCamelCase(String s) { String regex = "([a-z])([A-Z]+)"; String replacement = "$1_$2"; return s.replaceAll(regex, replacement).toLowerCase(); } // This function copies the linked item map while excluding an item, useful for a recursive stack protected Map<String, ContentItem> copyLinkedItemsWithExclusion( Map<String, ContentItem> orig, String excludedContentItem) { HashMap<String, ContentItem> target = new HashMap<>(); for (Map.Entry<String, ContentItem> entry : orig.entrySet()) { if (!excludedContentItem.equals(entry.getKey())) { target.put(entry.getKey(), entry.getValue()); } } return target; } private static boolean isListOrMap(Class<?> type) { return List.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type); } private static Object castCollection(Class<?> type, Map<String, ?> items) { if (List.class.isAssignableFrom(type)) { return new ArrayList(items.values()); } if (Map.class.isAssignableFrom(type)) { return items; } return items; } private static Type getType(Object bean, Field field) { //Because of type erasure, we will find the setter method and get the generic types off it's arguments Optional<PropertyDescriptor> propertyDescriptor = getPropertyDescriptor(bean, field); if (!propertyDescriptor.isPresent()) { //Likely no accessors log.debug("Property descriptor for object {} with field {} is null", bean, field); return null; } Method writeMethod = propertyDescriptor.get().getWriteMethod(); if (writeMethod == null) { log.debug("No write method for property {}", propertyDescriptor); return null; } Type[] actualTypeArguments = ((ParameterizedType) writeMethod.getGenericParameterTypes()[0]) .getActualTypeArguments(); Type type = (Map.class.isAssignableFrom(field.getType())) ? actualTypeArguments[1] : actualTypeArguments[0]; log.debug("Got type {} from {}", type.getTypeName(), String.format("%s#%s", bean.getClass().getSimpleName(), field.getName())); return type; } @NotNull private static Optional<PropertyDescriptor> getPropertyDescriptor(Object bean, Field field) { BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(bean.getClass()); } catch (IntrospectionException e) { log.debug("IntrospectionException from com.madrobot.beans for object {} with field {} is null", bean, field); return null; } PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors(); Optional<PropertyDescriptor> propertyDescriptor = Arrays.stream(properties).filter(descriptor -> descriptor.getName().equals(field.getName())).findFirst(); return propertyDescriptor; } private static void handleReflectionException(Exception ex) { log.error("Reflection exception", ex); if (ex instanceof NoSuchMethodException) { throw new IllegalStateException("Method not found: " + ex.getMessage()); } if (ex instanceof IllegalAccessException) { throw new IllegalStateException("Could not access method: " + ex.getMessage()); } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new UndeclaredThrowableException(ex); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/System.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.ZonedDateTime; import java.util.List; /** * Content item system attributes * <p> * Every {@link ContentItem} and {@link ContentType} in a JSON response from the Delivery API contains a system * attribute. This attribute represents the System object with information about the retrieved content item */ @lombok.Getter @lombok.Setter @lombok.ToString @lombok.EqualsAndHashCode @lombok.NoArgsConstructor public class System { /** * Unique identifier of the content item * * @param id Sets the id of this. * @return The identifier of this. */ @JsonProperty("id") String id; /** * Display name of the content item. * * @param name Sets the name of this. * @return The display name of this. */ @JsonProperty("name") String name; /** * Codename of the content item * <p> * Generated from the content item's display name. * * @param codename Sets the codename of this. * @return The codename of this. */ @JsonProperty("codename") String codename; /** * Codename of the language variant * * @param language Sets the language of this. * @return The language variant of this. */ @JsonProperty("language") String language; /** * Codename of the content type * * @param type Sets the type of this. * @return The content type codename. */ @JsonProperty("type") String type; /** * Codename of the collection * * @param collection Sets the collection of this. * @return The collection codename. */ @JsonProperty("collection") String collection; /** * A list of sitemap locations the content item is in * * @param sitemapLocations Sets the sitemapLocations of this. * @return The sitemap location strings of this. */ @JsonProperty("sitemap_locations") List<String> sitemapLocations; /** * When was the content item last modified * * @param lastModified Sets the lastModified time of this. * @return Zoned DateTime generated from ISO 8601 formatted string */ @JsonProperty("last_modified") ZonedDateTime lastModified; /** * The codename of the item's current workflow step. * * @param workflowStep Sets the workflowStep of this. * @return The workflow step of this. */ @JsonProperty("workflow_step") String workflowStep; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/Taxonomy.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Object model for a Taxonomy element */ @lombok.Getter @lombok.Setter @lombok.ToString @lombok.EqualsAndHashCode @lombok.NoArgsConstructor public class Taxonomy { /** * The display name of the taxonomy * * @param name Sets the name of this. * @return The name of the taxonomy. */ @JsonProperty("name") String name; /** * The codename of the taxonomy * * @param codename Sets the codename of this. * @return The codename of the taxonomy. */ @JsonProperty("codename") String codename; /** * A list of taxonomically descendant terms * * @param terms Sets the taxonomy terms of this. * @return A list of taxonomically descendant terms. */ @JsonProperty("terms") List<Taxonomy> terms; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/TaxonomyElement.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Object model for a Taxonomy group element */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class TaxonomyElement extends Element<List<Taxonomy>> { static final String TYPE_VALUE = "taxonomy"; /** * The name of the taxonomy group * * @param taxonomyGroup Sets the taxonomyGroup of this. * @return The taxonomy group name of this. */ @JsonProperty("taxonomy_group") String taxonomyGroup; /** * The value of Taxonomy elements is a list of {@link Taxonomy} item objects. * * @param value Sets the value of this. * @return List of {@link Taxonomy} objects. */ @JsonProperty("value") List<Taxonomy> value; public TaxonomyElement() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/TaxonomyGroup.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Object model for a single Taxonomy group */ @lombok.Getter @lombok.Setter @lombok.ToString @lombok.EqualsAndHashCode @lombok.NoArgsConstructor public class TaxonomyGroup { /** * System attributes fo the taxonomy group. * * @param system Sets the system of this. * @return Returns the system attributes of this. */ @JsonProperty("system") System system; /** * Taxonomy terms in this taxonomy group. * * @param terms Sets the taxonomy terms of this. * @return Returns the taxonomy terms in this group. */ @JsonProperty("terms") List<Taxonomy> terms; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/TaxonomyGroupListingResponse.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Content type listing response from an invocation of {@link DeliveryClient#getTypes()}, or * {@link DeliveryClient#getTypes(List)}. * * @see <a href="https://kontent.ai/learn/reference/delivery-api#operation/list-taxonomy-groups"> * Kontent.ai API reference - List taxonomy groups</a> * @see <a href="https://kontent.ai/learn/reference/delivery-api#section/Taxonomy-group-object"> * Kontent.ai API reference - Taxonomy group model</a> * @see ContentType * @see DeliveryClient#getTypes() * @see DeliveryClient#getTypes(List) */ @lombok.Data @lombok.NoArgsConstructor @lombok.AllArgsConstructor @lombok.Builder public class TaxonomyGroupListingResponse { /** * A list of taxonomy groups * * @param taxonomies Sets the taxonomies of this. * @return List of {@link TaxonomyGroup}. */ @JsonProperty("taxonomies") List<TaxonomyGroup> taxonomies; /** * Information about the retrieved page. * * @param pagination Sets the pagination of this. * @return The {@link Pagination} object identifying the current page. */ @JsonProperty("pagination") Pagination pagination; }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/TextElement.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Object model for text elements */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class TextElement extends Element<String> { static final String TYPE_VALUE = "text"; /** * The value of a Text element is a string. * * @param value Sets the value of this. * @return The element value of this. */ @JsonProperty("value") String value; public TextElement() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/UrlSlugElement.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery; import com.fasterxml.jackson.annotation.JsonProperty; /** * Object model for URL slug elements */ @lombok.Getter @lombok.Setter @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode(callSuper = true) public class UrlSlugElement extends Element<String> { static final String TYPE_VALUE = "url_slug"; /** * The value of URL slug elements is a string. * * @param value Sets the value of this. * @return A URL slug string. */ @JsonProperty("value") String value; public UrlSlugElement() { setType(TYPE_VALUE); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/package-info.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * The Kontent.ai Delivery API is read-only. You can retrieve content but not add or modify it. * <p> * Production vs Preview * You can work with the Delivery API in two ways. Either retrieve published versions of content items or preview their * yet unpublished versions. In both cases, you use the same methods to request data with the * {@link kontent.ai.delivery.DeliveryClient}. * <p> * If you want to preview unpublished content in your project, you need to include the Preview API key in your * construction of the {@link kontent.ai.delivery.DeliveryClient}. */ package kontent.ai.delivery;
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template/RenderingEngineMissingException.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery.template; public class RenderingEngineMissingException extends Exception { public RenderingEngineMissingException(String message) { super(message); } public RenderingEngineMissingException(String message, Exception cause) { super(message, cause); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template/TemplateEngine.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery.template; public interface TemplateEngine { void setViewResolverConfiguration(ViewResolverConfiguration viewResolverConfiguration); String process(TemplateEngineModel data); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template/TemplateEngineConfig.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery.template; import io.github.classgraph.ClassGraph; import io.github.classgraph.ClassInfoList; import io.github.classgraph.ScanResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationTargetException; import java.util.*; public class TemplateEngineConfig { private static final Logger logger = LoggerFactory.getLogger(TemplateEngineConfig.class); private static final String DEFAULT_SCAN_PATH = "kontent.ai.delivery.template"; private Map<String, Object> defaultModelVariables = new HashMap<>(); private ViewResolverConfiguration viewResolverConfiguration = new ViewResolverConfiguration(); private List<String> pathsToScan = new ArrayList<>(); private boolean autoRegister = true; List<TemplateEngineInlineContentItemsResolver> resolvers = new ArrayList<>(); public TemplateEngineConfig() { this.pathsToScan.add(DEFAULT_SCAN_PATH); } public void init() { if (isAutoRegister()) { try (ScanResult scanResult = new ClassGraph() .enableAllInfo() .acceptPackages(getPathsToScan().toArray(new String[0])) .scan()) { ClassInfoList resolvers = scanResult.getClassesImplementing(TemplateEngineInlineContentItemsResolver.class.getName()); resolvers.loadClasses(TemplateEngineInlineContentItemsResolver.class).forEach(implementingClass -> { try { TemplateEngineInlineContentItemsResolver resolver = implementingClass.getConstructor().newInstance(); resolver.getTemplateEngine().setViewResolverConfiguration(getViewResolverConfiguration()); addResolvers(resolver); logger.info("Registered inline content template resolver: {}", resolver.getClass().getName()); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException e) { logger.error("Exception instantiating template resolver {}", e); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RenderingEngineMissingException) { logger.info("Renderer Missing: {}", e.getTargetException().getMessage()); } else { logger.error("Exception instantiating template resolver {}", e); } } }); } } } public Map<String, Object> getDefaultModelVariables() { return defaultModelVariables; } public void setDefaultModelVariables(Map<String, Object> defaultModelVariables) { this.defaultModelVariables = defaultModelVariables; } public ViewResolverConfiguration getViewResolverConfiguration() { return viewResolverConfiguration; } public void setViewResolverConfiguration(ViewResolverConfiguration viewResolverConfiguration) { this.viewResolverConfiguration = viewResolverConfiguration; } public List<String> getPathsToScan() { return pathsToScan; } public void setPathsToScan(List<String> pathsToScan) { this.pathsToScan = pathsToScan; } public void addPathsToScan(String... paths) { this.pathsToScan.addAll(Arrays.asList(paths)); } public boolean isAutoRegister() { return autoRegister; } public void setAutoRegister(boolean autoRegister) { this.autoRegister = autoRegister; } public List<TemplateEngineInlineContentItemsResolver> getResolvers() { return resolvers; } public void setResolvers(List<TemplateEngineInlineContentItemsResolver> resolvers) { this.resolvers = resolvers; } public void addResolvers(TemplateEngineInlineContentItemsResolver... resolvers) { this.resolvers.addAll(Arrays.asList(resolvers)); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template/TemplateEngineInlineContentItemsResolver.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery.template; public interface TemplateEngineInlineContentItemsResolver { default String resolve(TemplateEngineModel data) { TemplateEngine templateEngine = getTemplateEngine(); return templateEngine.process(data); } boolean supports(TemplateEngineModel data); TemplateEngine getTemplateEngine(); }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template/TemplateEngineModel.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery.template; import java.util.HashMap; import java.util.Locale; import java.util.Map; public class TemplateEngineModel { private Object inlineContentItem; private Map<String, Object> variables = new HashMap<>(); private Locale locale = Locale.getDefault(); public Object getInlineContentItem() { return inlineContentItem; } public void setInlineContentItem(Object inlineContentItem) { this.inlineContentItem = inlineContentItem; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } public void addVariable(String key, Object value) { variables.put(key, value); } public void addVariables(Map<String, Object> variables) { this.variables.putAll(variables); } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template/ViewResolverConfiguration.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery.template; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ViewResolverConfiguration { List<String> prefixes = new ArrayList<>(); String suffix = ".html"; public ViewResolverConfiguration() { this.prefixes.addAll(Arrays.asList("kontent/ai/templates/", "META-INF/kontent/ai/templates/")); } public ViewResolverConfiguration addPrefixes(String... prefixes) { this.prefixes.addAll(Arrays.asList(prefixes)); return this; } public ViewResolverConfiguration setSuffix(String suffix) { this.suffix = suffix; return this; } public List<String> getPrefixes() { return prefixes; } public void setPrefixes(List<String> prefixes) { this.prefixes = prefixes; } public String getSuffix() { return suffix; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template/thymeleaf/ThymeleafInlineContentItemsResolver.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery.template.thymeleaf; import kontent.ai.delivery.template.RenderingEngineMissingException; import kontent.ai.delivery.template.TemplateEngine; import kontent.ai.delivery.template.TemplateEngineInlineContentItemsResolver; import kontent.ai.delivery.template.TemplateEngineModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.thymeleaf.Thymeleaf; public class ThymeleafInlineContentItemsResolver implements TemplateEngineInlineContentItemsResolver { private static final Logger logger = LoggerFactory.getLogger(ThymeleafInlineContentItemsResolver.class); protected ThymeleafTemplateEngine thymeleafTemplateEngine; public ThymeleafInlineContentItemsResolver() throws RenderingEngineMissingException { super(); try { Class.forName("org.thymeleaf.Thymeleaf"); if (Thymeleaf.VERSION_MAJOR < 3) { throw new RenderingEngineMissingException("Support is only available for Thymeleaf version 3.0.0.RELEASE and above"); } thymeleafTemplateEngine = new ThymeleafTemplateEngine(); } catch (ClassNotFoundException e) { String msg = "Thymeleaf version 3.0.0.RELEASE or above is not on the classpath, Thymeleaf Inline Content resolution is disabled"; logger.warn(msg); throw new RenderingEngineMissingException(msg, e); } } @Override public boolean supports(TemplateEngineModel data) { return thymeleafTemplateEngine.supports(data); } @Override public TemplateEngine getTemplateEngine() { return thymeleafTemplateEngine; } }
0
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template
java-sources/ai/kontent/delivery-sdk/5.1.2/kontent/ai/delivery/template/thymeleaf/ThymeleafTemplateEngine.java
/* * MIT License * * Copyright (c) 2022 Kontent s.r.o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package kontent.ai.delivery.template.thymeleaf; import kontent.ai.delivery.ContentItem; import kontent.ai.delivery.ContentItemMapping; import kontent.ai.delivery.template.TemplateEngine; import kontent.ai.delivery.template.TemplateEngineModel; import kontent.ai.delivery.template.ViewResolverConfiguration; import kontent.ai.delivery.System; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.thymeleaf.context.Context; import org.thymeleaf.context.IContext; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.AbstractTemplateResolver; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import org.thymeleaf.templateresolver.ITemplateResolver; import org.thymeleaf.templateresolver.TemplateResolution; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ThymeleafTemplateEngine implements TemplateEngine { private static final Logger logger = LoggerFactory.getLogger(ThymeleafTemplateEngine.class); boolean configured = false; protected ViewResolverConfiguration viewResolverConfiguration; org.thymeleaf.TemplateEngine templateEngine; @Override public void setViewResolverConfiguration(ViewResolverConfiguration viewResolverConfiguration) { this.viewResolverConfiguration = viewResolverConfiguration; configure(); } @Override public String process(TemplateEngineModel data) { if (!configured) { throw new IllegalStateException("Engine not configured. Did you call setViewResolverConfiguration()?"); } Map<String, Object> variables = data.getVariables(); Object inlineContentItem = data.getInlineContentItem(); String contentType = getContentTypeFromModel(inlineContentItem); variables.put("model", inlineContentItem); IContext context = new Context(data.getLocale(), variables); return templateEngine.process(contentType, context); } protected void configure() { if (viewResolverConfiguration != null) { org.thymeleaf.TemplateEngine engine = new org.thymeleaf.TemplateEngine(); Set<ITemplateResolver> resolvers = new HashSet<>(); for (String prefix : viewResolverConfiguration.getPrefixes()) { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setPrefix(prefix); templateResolver.setSuffix(viewResolverConfiguration.getSuffix()); templateResolver.setTemplateMode(TemplateMode.HTML); templateResolver.setCheckExistence(true); resolvers.add(templateResolver); } engine.setTemplateResolvers(configureTemplateResolvers(resolvers)); this.templateEngine = engine; configured = true; } } protected boolean supports(TemplateEngineModel data) { if (!configured) { return false; } String contentType = getContentTypeFromModel(data.getInlineContentItem()); if (contentType == null) { return false; } Set<ITemplateResolver> templateResolvers = templateEngine.getTemplateResolvers(); for (ITemplateResolver resolver : templateResolvers) { if (resolver instanceof AbstractTemplateResolver) { TemplateResolution templateResolution = resolver.resolveTemplate(templateEngine.getConfiguration(), null, contentType, null); if (templateResolution != null && templateResolution.getTemplateResource().exists()) { return true; } } } return false; } /** * Override this method to reconfigure template resolvers * @param resolvers A Set of {@link ClassLoaderTemplateResolver} * @return A set of {@link ITemplateResolver} */ protected Set<ITemplateResolver> configureTemplateResolvers(Set<ITemplateResolver> resolvers) { return resolvers; } private String getContentTypeFromModel(Object model) { if (model instanceof ContentItem) { ContentItem contentItem = (ContentItem) model; return contentItem.getSystem().getType(); } ContentItemMapping contentItemMapping = model.getClass().getAnnotation(ContentItemMapping.class); if (contentItemMapping != null) { return contentItemMapping.value(); } try { Object system = model.getClass().getDeclaredField("system").get(model); if (system instanceof System) { return ((System) system).getType(); } } catch (IllegalAccessException | NoSuchFieldException e) { logger.debug("Unable to find System property on model", e); } return null; } }
0
java-sources/ai/kontent/delivery-sdk-generators/5.1.2/kontent/ai/delivery
java-sources/ai/kontent/delivery-sdk-generators/5.1.2/kontent/ai/delivery/generators/CodeGenerator.java
package kontent.ai.delivery.generators; import com.google.common.base.CaseFormat; import com.squareup.javapoet.*; import kontent.ai.delivery.*; import kontent.ai.delivery.System; import javax.lang.model.element.Modifier; import java.io.File; import java.io.IOException; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; /** * Generates java source files using the Kontent.ai Type listing endpoint in the Delivery API */ public class CodeGenerator { private static final String DELIVERY_PACKAGE = "kontent.ai.delivery"; private static final String JAVA_UTIL_PACKAGE = "java.util"; private static final String SYSTEM = "system"; String projectId; String packageName; File outputDir; /** * Constructs the CodeGenerator * @param projectId the project id from your Kontent.ai account * @param packageName the package to place the generated models under * @param outputDir the source root to place the generated models * @throws UnsupportedOperationException when a there is a problem with the outputDir */ public CodeGenerator(String projectId, String packageName, File outputDir) { this.projectId = projectId; this.packageName = packageName; this.outputDir = outputDir; if (!outputDir.exists() && !outputDir.mkdirs()){ throw new UnsupportedOperationException( String.format("Unable to create directory %s", outputDir.getAbsolutePath())); } if (!outputDir.isDirectory()) { throw new UnsupportedOperationException( String.format("%s exists and is not a directory", outputDir.getAbsolutePath())); } } /** * Returns a list of specifications of the sources representing the types in your Kontent.ai account * @return A list of specifications * @throws ExecutionException when a problem occurs communicating with the Kontent.ai API * @throws InterruptedException when a problem occurs communicating with the Kontent.ai API */ public List<JavaFile> generateSources() throws ExecutionException, InterruptedException { return generateSources(new DeliveryClient(projectId)); } /** * Returns a list of specifications of the sources representing the types in your Kontent.ai account. * The provided {@link DeliveryClient} param is useful for testing, however in most environments, the default * {@link #generateSources()} method should suffice. * @param client A DeliveryClient instance to use to generate the sources. * @return A list of specifications * @throws ExecutionException when a problem occurs communicating with the Kontent.ai API * @throws InterruptedException when a problem occurs communicating with the Kontent.ai API */ public List<JavaFile> generateSources(DeliveryClient client) throws ExecutionException, InterruptedException { return generateSources(client.getTypes().toCompletableFuture().get().getTypes()); } /** * Returns a list of specifications of the sources representing the types in your Kontent.ai account. * The provided List of {@link ContentType} param is useful for testing, however in most environments, the default * {@link #generateSources()} method should generally be the only method invoking this. * @param types A List of ContentType to generate the sources from * @return A list of specifications */ public List<JavaFile> generateSources(List<ContentType> types) { List<JavaFile> sources = new ArrayList<>(); for (ContentType type : types) { sources.add(generateSource(type)); } return sources; } /** * Returns a specification of the source representing this type in your Kontent.ai account. * Invoking this directly may be useful for testing, however in most environments, the default * {@link #generateSources()} method should suffice. * @param type A ContentType to generate the source from * @return A specification */ public JavaFile generateSource(ContentType type) { List<FieldSpec> fieldSpecs = new ArrayList<>(); List<MethodSpec> methodSpecs = new ArrayList<>(); for (Map.Entry<String, Element> element : type.getElements().entrySet()) { TypeName typeName = null; //Get the TypeName switch (element.getValue().getType()) { case "text" : case "rich_text" : case "url_slug" : case "custom" : typeName = ClassName.get(String.class); break; case "number" : typeName = ClassName.get(Double.class); break; case "multiple_choice" : typeName = ParameterizedTypeName.get( ClassName.get(JAVA_UTIL_PACKAGE, "List"), ClassName.get(DELIVERY_PACKAGE, "Option")); break; case "date_time" : typeName = ClassName.get(ZonedDateTime.class); break; case "asset" : typeName = ParameterizedTypeName.get( ClassName.get(JAVA_UTIL_PACKAGE, "List"), ClassName.get(DELIVERY_PACKAGE, "Asset")); break; case "modular_content" : typeName = ParameterizedTypeName.get( ClassName.get(JAVA_UTIL_PACKAGE, "List"), ClassName.get(DELIVERY_PACKAGE, "ContentItem")); break; case "taxonomy" : typeName = ParameterizedTypeName.get( ClassName.get(JAVA_UTIL_PACKAGE, "List"), ClassName.get(DELIVERY_PACKAGE, "Taxonomy")); break; default : break; } if (typeName != null) { //Add the field String fieldName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, element.getKey()); Class annoClass = element.getValue().getType() == "modular_content" ? ContentItemMapping.class : ElementMapping.class; fieldSpecs.add( FieldSpec.builder(typeName, fieldName) .addAnnotation( AnnotationSpec.builder(annoClass) .addMember("value", "$S", element.getKey()) .build()) .build() ); //Add the getter String getterName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "get_" + element.getKey()); methodSpecs.add( MethodSpec.methodBuilder(getterName) .addModifiers(Modifier.PUBLIC) .returns(typeName) .addStatement("return $N", fieldName) .build() ); //Add the setter String setterName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "set_" + element.getKey()); methodSpecs.add( MethodSpec.methodBuilder(setterName) .addModifiers(Modifier.PUBLIC) .addParameter(typeName, fieldName) .addStatement("this.$N = $N", fieldName, fieldName) .build() ); } } //Add the System element fieldSpecs.add(FieldSpec.builder(ClassName.get(System.class), SYSTEM).build()); methodSpecs.add( MethodSpec.methodBuilder("getSystem") .addModifiers(Modifier.PUBLIC) .returns(ClassName.get(System.class)) .addStatement("return $N", SYSTEM) .build() ); methodSpecs.add( MethodSpec.methodBuilder("setSystem") .addModifiers(Modifier.PUBLIC) .addParameter(ClassName.get(System.class), SYSTEM) .addStatement("this.$N = $N", SYSTEM, SYSTEM) .build() ); //Create the class TypeSpec.Builder typeSpecBuilder = TypeSpec .classBuilder(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, type.getSystem().getCodename())) .addModifiers(Modifier.PUBLIC) .addJavadoc("This code was generated by a " + "<a href=\"https://github.com/kontent-ai/java-packages/tree/master/delivery-sdk-generators\">delivery-sdk-generators tool</a>\n") .addJavadoc("\n") .addJavadoc("Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.\n") .addJavadoc("For further modifications of the class, create a separate file and extend this class.\n") .addAnnotation(AnnotationSpec.builder(ContentItemMapping.class) .addMember("value", "$S", type.getSystem().getCodename()) .build()); //Add the fields for (FieldSpec fieldSpec : fieldSpecs) { typeSpecBuilder.addField(fieldSpec); } //Add the methods for (MethodSpec methodSpec : methodSpecs) { typeSpecBuilder.addMethod(methodSpec); } TypeSpec typeSpec = typeSpecBuilder.build(); return JavaFile.builder(packageName, typeSpec).build(); } /** * Writes the provided specifications to the outputDir provided in the constructor. This is generally called * after a call to {@link #generateSources()}, but is separated in case you need to make modifications to your * specifications before writing. * @param sources A list of specifications * @throws IOException when a problem occurs writing the source files, note some source may have been written when * this is thrown */ public void writeSources(List<JavaFile> sources) throws IOException { for (JavaFile source : sources) { writeSource(source); } } /** * Writes the provided specification to the outputDir provided in the constructor. This is generally called * after a call to {@link #generateSources()}, but is separated in case you need to make modifications to your * specification before writing. * @param source A specification * @throws IOException when a problem occurs writing the source files */ public void writeSource(JavaFile source) throws IOException { source.writeTo(outputDir); } }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/ApiCallback.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; import java.io.IOException; import java.util.Map; import java.util.List; /** * Callback for asynchronous API call. * * @param <T> The return type */ public interface ApiCallback<T> { /** * This is called when the API call fails. * * @param e The exception causing the failure * @param statusCode Status code of the response if available, otherwise it would be 0 * @param responseHeaders Headers of the response if available, otherwise it would be null */ void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders); /** * This is called when the API call succeeded. * * @param result The result deserialized from response * @param statusCode Status code of the response * @param responseHeaders Headers of the response */ void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders); /** * This is called when the API upload processing. * * @param bytesWritten bytes Written * @param contentLength content length of request body * @param done write end */ void onUploadProgress(long bytesWritten, long contentLength, boolean done); /** * This is called when the API download processing. * * @param bytesRead bytes Read * @param contentLength content length of the response * @param done Read end */ void onDownloadProgress(long bytesRead, long contentLength, boolean done); }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/ApiClient.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; import okhttp3.*; import okhttp3.internal.http.HttpMethod; import okhttp3.internal.tls.OkHostnameVerifier; import okhttp3.logging.HttpLoggingInterceptor; import okhttp3.logging.HttpLoggingInterceptor.Level; import okio.Buffer; import okio.BufferedSink; import okio.Okio; import javax.net.ssl.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.net.URI; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.text.DateFormat; import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import ai.lamin.lamin_api_client.auth.Authentication; import ai.lamin.lamin_api_client.auth.HttpBasicAuth; import ai.lamin.lamin_api_client.auth.HttpBearerAuth; import ai.lamin.lamin_api_client.auth.ApiKeyAuth; /** * <p>ApiClient class.</p> */ public class ApiClient { private String basePath = "https://aws.us-east-1.lamin.ai/api"; protected List<ServerConfiguration> servers = new ArrayList<ServerConfiguration>(Arrays.asList( new ServerConfiguration( "https://aws.us-east-1.lamin.ai/api", "No description provided", new HashMap<String, ServerVariable>() ) )); protected Integer serverIndex = 0; protected Map<String, String> serverVariables = null; private boolean debugging = false; private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); private Map<String, String> defaultCookieMap = new HashMap<String, String>(); private String tempFolderPath = null; private Map<String, Authentication> authentications; private DateFormat dateFormat; private DateFormat datetimeFormat; private boolean lenientDatetimeFormat; private int dateLength; private InputStream sslCaCert; private boolean verifyingSsl; private KeyManager[] keyManagers; private OkHttpClient httpClient; private JSON json; private HttpLoggingInterceptor loggingInterceptor; /** * Basic constructor for ApiClient */ public ApiClient() { init(); initHttpClient(); // Setup authentications (key: authentication name, value: authentication). // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } /** * Basic constructor with custom OkHttpClient * * @param client a {@link okhttp3.OkHttpClient} object */ public ApiClient(OkHttpClient client) { init(); httpClient = client; // Setup authentications (key: authentication name, value: authentication). // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } private void initHttpClient() { initHttpClient(Collections.<Interceptor>emptyList()); } private void initHttpClient(List<Interceptor> interceptors) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.addNetworkInterceptor(getProgressInterceptor()); for (Interceptor interceptor: interceptors) { builder.addInterceptor(interceptor); } httpClient = builder.build(); } private void init() { verifyingSsl = true; json = new JSON(); // Set default User-Agent. setUserAgent("OpenAPI-Generator/0.0.3/java"); authentications = new HashMap<String, Authentication>(); } /** * Get base path * * @return Base path */ public String getBasePath() { return basePath; } /** * Set base path * * @param basePath Base path of the URL (e.g https://aws.us-east-1.lamin.ai/api * @return An instance of OkHttpClient */ public ApiClient setBasePath(String basePath) { this.basePath = basePath; this.serverIndex = null; return this; } public List<ServerConfiguration> getServers() { return servers; } public ApiClient setServers(List<ServerConfiguration> servers) { this.servers = servers; return this; } public Integer getServerIndex() { return serverIndex; } public ApiClient setServerIndex(Integer serverIndex) { this.serverIndex = serverIndex; return this; } public Map<String, String> getServerVariables() { return serverVariables; } public ApiClient setServerVariables(Map<String, String> serverVariables) { this.serverVariables = serverVariables; return this; } /** * Get HTTP client * * @return An instance of OkHttpClient */ public OkHttpClient getHttpClient() { return httpClient; } /** * Set HTTP client, which must never be null. * * @param newHttpClient An instance of OkHttpClient * @return Api Client * @throws java.lang.NullPointerException when newHttpClient is null */ public ApiClient setHttpClient(OkHttpClient newHttpClient) { this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); return this; } /** * Get JSON * * @return JSON object */ public JSON getJSON() { return json; } /** * Set JSON * * @param json JSON object * @return Api client */ public ApiClient setJSON(JSON json) { this.json = json; return this; } /** * True if isVerifyingSsl flag is on * * @return True if isVerifySsl flag is on */ public boolean isVerifyingSsl() { return verifyingSsl; } /** * Configure whether to verify certificate and hostname when making https requests. * Default to true. * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. * * @param verifyingSsl True to verify TLS/SSL connection * @return ApiClient */ public ApiClient setVerifyingSsl(boolean verifyingSsl) { this.verifyingSsl = verifyingSsl; applySslSettings(); return this; } /** * Get SSL CA cert. * * @return Input stream to the SSL CA cert */ public InputStream getSslCaCert() { return sslCaCert; } /** * Configure the CA certificate to be trusted when making https requests. * Use null to reset to default. * * @param sslCaCert input stream for SSL CA cert * @return ApiClient */ public ApiClient setSslCaCert(InputStream sslCaCert) { this.sslCaCert = sslCaCert; applySslSettings(); return this; } /** * <p>Getter for the field <code>keyManagers</code>.</p> * * @return an array of {@link javax.net.ssl.KeyManager} objects */ public KeyManager[] getKeyManagers() { return keyManagers; } /** * Configure client keys to use for authorization in an SSL session. * Use null to reset to default. * * @param managers The KeyManagers to use * @return ApiClient */ public ApiClient setKeyManagers(KeyManager[] managers) { this.keyManagers = managers; applySslSettings(); return this; } /** * <p>Getter for the field <code>dateFormat</code>.</p> * * @return a {@link java.text.DateFormat} object */ public DateFormat getDateFormat() { return dateFormat; } /** * <p>Setter for the field <code>dateFormat</code>.</p> * * @param dateFormat a {@link java.text.DateFormat} object * @return a {@link ai.lamin.lamin_api_client.ApiClient} object */ public ApiClient setDateFormat(DateFormat dateFormat) { JSON.setDateFormat(dateFormat); return this; } /** * <p>Set SqlDateFormat.</p> * * @param dateFormat a {@link java.text.DateFormat} object * @return a {@link ai.lamin.lamin_api_client.ApiClient} object */ public ApiClient setSqlDateFormat(DateFormat dateFormat) { JSON.setSqlDateFormat(dateFormat); return this; } /** * <p>Set OffsetDateTimeFormat.</p> * * @param dateFormat a {@link java.time.format.DateTimeFormatter} object * @return a {@link ai.lamin.lamin_api_client.ApiClient} object */ public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { JSON.setOffsetDateTimeFormat(dateFormat); return this; } /** * <p>Set LocalDateFormat.</p> * * @param dateFormat a {@link java.time.format.DateTimeFormatter} object * @return a {@link ai.lamin.lamin_api_client.ApiClient} object */ public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { JSON.setLocalDateFormat(dateFormat); return this; } /** * <p>Set LenientOnJson.</p> * * @param lenientOnJson a boolean * @return a {@link ai.lamin.lamin_api_client.ApiClient} object */ public ApiClient setLenientOnJson(boolean lenientOnJson) { JSON.setLenientOnJson(lenientOnJson); return this; } /** * Get authentications (key: authentication name, value: authentication). * * @return Map of authentication objects */ public Map<String, Authentication> getAuthentications() { return authentications; } /** * Get authentication for the given name. * * @param authName The authentication name * @return The authentication, null if not found */ public Authentication getAuthentication(String authName) { return authentications.get(authName); } /** * Helper method to set username for the first HTTP basic authentication. * * @param username Username */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setUsername(username); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); } /** * Helper method to set password for the first HTTP basic authentication. * * @param password Password */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setPassword(password); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); } /** * Helper method to set API key value for the first API key authentication. * * @param apiKey API key */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { ((ApiKeyAuth) auth).setApiKey(apiKey); return; } } throw new RuntimeException("No API key authentication configured!"); } /** * Helper method to set API key prefix for the first API key authentication. * * @param apiKeyPrefix API key prefix */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); return; } } throw new RuntimeException("No API key authentication configured!"); } /** * Helper method to set access token for the first OAuth2 authentication. * * @param accessToken Access token */ public void setAccessToken(String accessToken) { throw new RuntimeException("No OAuth2 authentication configured!"); } /** * Helper method to set credentials for AWSV4 Signature * * @param accessKey Access Key * @param secretKey Secret Key * @param region Region * @param service Service to access to */ public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { throw new RuntimeException("No AWS4 authentication configured!"); } /** * Helper method to set credentials for AWSV4 Signature * * @param accessKey Access Key * @param secretKey Secret Key * @param sessionToken Session Token * @param region Region * @param service Service to access to */ public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) { throw new RuntimeException("No AWS4 authentication configured!"); } /** * Set the User-Agent header's value (by adding to the default header map). * * @param userAgent HTTP request's user agent * @return ApiClient */ public ApiClient setUserAgent(String userAgent) { addDefaultHeader("User-Agent", userAgent); return this; } /** * Add a default header. * * @param key The header's key * @param value The header's value * @return ApiClient */ public ApiClient addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); return this; } /** * Add a default cookie. * * @param key The cookie's key * @param value The cookie's value * @return ApiClient */ public ApiClient addDefaultCookie(String key, String value) { defaultCookieMap.put(key, value); return this; } /** * Check that whether debugging is enabled for this API client. * * @return True if debugging is enabled, false otherwise. */ public boolean isDebugging() { return debugging; } /** * Enable/disable debugging for this API client. * * @param debugging To enable (true) or disable (false) debugging * @return ApiClient */ public ApiClient setDebugging(boolean debugging) { if (debugging != this.debugging) { if (debugging) { loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(Level.BODY); httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); } else { final OkHttpClient.Builder builder = httpClient.newBuilder(); builder.interceptors().remove(loggingInterceptor); httpClient = builder.build(); loggingInterceptor = null; } } this.debugging = debugging; return this; } /** * The path of temporary folder used to store downloaded files from endpoints * with file response. The default value is <code>null</code>, i.e. using * the system's default temporary folder. * * @see <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempFile(java.lang.String,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...)">createTempFile</a> * @return Temporary folder path */ public String getTempFolderPath() { return tempFolderPath; } /** * Set the temporary folder path (for downloading files) * * @param tempFolderPath Temporary folder path * @return ApiClient */ public ApiClient setTempFolderPath(String tempFolderPath) { this.tempFolderPath = tempFolderPath; return this; } /** * Get connection timeout (in milliseconds). * * @return Timeout in milliseconds */ public int getConnectTimeout() { return httpClient.connectTimeoutMillis(); } /** * Sets the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and * {@link java.lang.Integer#MAX_VALUE}. * * @param connectionTimeout connection timeout in milliseconds * @return Api client */ public ApiClient setConnectTimeout(int connectionTimeout) { httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); return this; } /** * Get read timeout (in milliseconds). * * @return Timeout in milliseconds */ public int getReadTimeout() { return httpClient.readTimeoutMillis(); } /** * Sets the read timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and * {@link java.lang.Integer#MAX_VALUE}. * * @param readTimeout read timeout in milliseconds * @return Api client */ public ApiClient setReadTimeout(int readTimeout) { httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); return this; } /** * Get write timeout (in milliseconds). * * @return Timeout in milliseconds */ public int getWriteTimeout() { return httpClient.writeTimeoutMillis(); } /** * Sets the write timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and * {@link java.lang.Integer#MAX_VALUE}. * * @param writeTimeout connection timeout in milliseconds * @return Api client */ public ApiClient setWriteTimeout(int writeTimeout) { httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); return this; } /** * Format the given parameter object into string. * * @param param Parameter * @return String representation of the parameter */ public String parameterToString(Object param) { if (param == null) { return ""; } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { //Serialize to json string and remove the " enclosing characters String jsonStr = JSON.serialize(param); return jsonStr.substring(1, jsonStr.length() - 1); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); for (Object o : (Collection) param) { if (b.length() > 0) { b.append(","); } b.append(o); } return b.toString(); } else { return String.valueOf(param); } } /** * Formats the specified query parameter to a list containing a single {@code Pair} object. * * Note that {@code value} must not be a collection. * * @param name The name of the parameter. * @param value The value of the parameter. * @return A list containing a single {@code Pair} object. */ public List<Pair> parameterToPair(String name, Object value) { List<Pair> params = new ArrayList<Pair>(); // preconditions if (name == null || name.isEmpty() || value == null || value instanceof Collection) { return params; } params.add(new Pair(name, parameterToString(value))); return params; } /** * Formats the specified collection query parameters to a list of {@code Pair} objects. * * Note that the values of each of the returned Pair objects are percent-encoded. * * @param collectionFormat The collection format of the parameter. * @param name The name of the parameter. * @param value The value of the parameter. * @return A list of {@code Pair} objects. */ public List<Pair> parameterToPairs(String collectionFormat, String name, Collection value) { List<Pair> params = new ArrayList<Pair>(); // preconditions if (name == null || name.isEmpty() || value == null || value.isEmpty()) { return params; } // create the params based on the collection format if ("multi".equals(collectionFormat)) { for (Object item : value) { params.add(new Pair(name, escapeString(parameterToString(item)))); } return params; } // collectionFormat is assumed to be "csv" by default String delimiter = ","; // escape all delimiters except commas, which are URI reserved // characters if ("ssv".equals(collectionFormat)) { delimiter = escapeString(" "); } else if ("tsv".equals(collectionFormat)) { delimiter = escapeString("\t"); } else if ("pipes".equals(collectionFormat)) { delimiter = escapeString("|"); } StringBuilder sb = new StringBuilder(); for (Object item : value) { sb.append(delimiter); sb.append(escapeString(parameterToString(item))); } params.add(new Pair(name, sb.substring(delimiter.length()))); return params; } /** * Formats the specified free-form query parameters to a list of {@code Pair} objects. * * @param value The free-form query parameters. * @return A list of {@code Pair} objects. */ public List<Pair> freeFormParameterToPairs(Object value) { List<Pair> params = new ArrayList<>(); // preconditions if (value == null || !(value instanceof Map )) { return params; } @SuppressWarnings("unchecked") final Map<String, Object> valuesMap = (Map<String, Object>) value; for (Map.Entry<String, Object> entry : valuesMap.entrySet()) { params.add(new Pair(entry.getKey(), parameterToString(entry.getValue()))); } return params; } /** * Formats the specified collection path parameter to a string value. * * @param collectionFormat The collection format of the parameter. * @param value The value of the parameter. * @return String representation of the parameter */ public String collectionPathParameterToString(String collectionFormat, Collection value) { // create the value based on the collection format if ("multi".equals(collectionFormat)) { // not valid for path params return parameterToString(value); } // collectionFormat is assumed to be "csv" by default String delimiter = ","; if ("ssv".equals(collectionFormat)) { delimiter = " "; } else if ("tsv".equals(collectionFormat)) { delimiter = "\t"; } else if ("pipes".equals(collectionFormat)) { delimiter = "|"; } StringBuilder sb = new StringBuilder() ; for (Object item : value) { sb.append(delimiter); sb.append(parameterToString(item)); } return sb.substring(delimiter.length()); } /** * Sanitize filename by removing path. * e.g. ../../sun.gif becomes sun.gif * * @param filename The filename to be sanitized * @return The sanitized filename */ public String sanitizeFilename(String filename) { return filename.replaceAll(".*[/\\\\]", ""); } /** * Check if the given MIME is a JSON MIME. * JSON MIME examples: * application/json * application/json; charset=UTF8 * APPLICATION/JSON * application/vnd.company+json * "* / *" is also default to JSON * @param mime MIME (Multipurpose Internet Mail Extensions) * @return True if the given MIME is JSON, false otherwise. */ public boolean isJsonMime(String mime) { String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); } /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; * otherwise use all of them (joining into a string) * * @param accepts The accepts array to select from * @return The Accept header to use. If the given array is empty, * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { if (accepts.length == 0) { return null; } for (String accept : accepts) { if (isJsonMime(accept)) { return accept; } } return StringUtil.join(accepts, ","); } /** * Select the Content-Type header's value from the given array: * if JSON exists in the given array, use it; * otherwise use the first one of the array. * * @param contentTypes The Content-Type array to select from * @return The Content-Type header to use. If the given array is empty, * returns null. If it matches "any", JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { if (contentTypes.length == 0) { return null; } if (contentTypes[0].equals("*/*")) { return "application/json"; } for (String contentType : contentTypes) { if (isJsonMime(contentType)) { return contentType; } } return contentTypes[0]; } /** * Escape the given string to be used as URL query value. * * @param str String to be escaped * @return Escaped string */ public String escapeString(String str) { try { return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { return str; } } /** * Deserialize response body to Java object, according to the return type and * the Content-Type response header. * * @param <T> Type * @param response HTTP response * @param returnType The type of the Java object * @return The deserialized Java object * @throws ai.lamin.lamin_api_client.ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ @SuppressWarnings("unchecked") public <T> T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; } if ("byte[]".equals(returnType.toString())) { // Handle binary response (byte array). try { return (T) response.body().bytes(); } catch (IOException e) { throw new ApiException(e); } } else if (returnType.equals(File.class)) { // Handle file downloading. return (T) downloadFileFromResponse(response); } String respBody; try { if (response.body() != null) respBody = response.body().string(); else respBody = null; } catch (IOException e) { throw new ApiException(e); } if (respBody == null || "".equals(respBody)) { return null; } String contentType = response.headers().get("Content-Type"); if (contentType == null) { // ensuring a default content type contentType = "application/json"; } if (isJsonMime(contentType)) { return JSON.deserialize(respBody, returnType); } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. return (T) respBody; } else { throw new ApiException( "Content type \"" + contentType + "\" is not supported for type: " + returnType, response.code(), response.headers().toMultimap(), respBody); } } /** * Serialize the given Java object into request body according to the object's * class and the request Content-Type. * * @param obj The Java object * @param contentType The request Content-Type * @return The serialized request body * @throws ai.lamin.lamin_api_client.ApiException If fail to serialize the given object */ public RequestBody serialize(Object obj, String contentType) throws ApiException { if (obj instanceof byte[]) { // Binary (byte array) body parameter support. return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); } else if (obj instanceof File) { // File body parameter support. return RequestBody.create((File) obj, MediaType.parse(contentType)); } else if ("text/plain".equals(contentType) && obj instanceof String) { return RequestBody.create((String) obj, MediaType.parse(contentType)); } else if (isJsonMime(contentType)) { String content; if (obj != null) { content = JSON.serialize(obj); } else { content = null; } return RequestBody.create(content, MediaType.parse(contentType)); } else if (obj instanceof String) { return RequestBody.create((String) obj, MediaType.parse(contentType)); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } } /** * Download file from the given response. * * @param response An instance of the Response object * @throws ai.lamin.lamin_api_client.ApiException If fail to read file content from response and write to disk * @return Downloaded file */ public File downloadFileFromResponse(Response response) throws ApiException { try { File file = prepareDownloadFile(response); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(response.body().source()); sink.close(); return file; } catch (IOException e) { throw new ApiException(e); } } /** * Prepare file for download * * @param response An instance of the Response object * @return Prepared file for the download * @throws java.io.IOException If fail to prepare file for download */ public File prepareDownloadFile(Response response) throws IOException { String filename = null; String contentDisposition = response.header("Content-Disposition"); if (contentDisposition != null && !"".equals(contentDisposition)) { // Get filename from the Content-Disposition header. Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); Matcher matcher = pattern.matcher(contentDisposition); if (matcher.find()) { filename = sanitizeFilename(matcher.group(1)); } } String prefix = null; String suffix = null; if (filename == null) { prefix = "download-"; suffix = ""; } else { int pos = filename.lastIndexOf("."); if (pos == -1) { prefix = filename + "-"; } else { prefix = filename.substring(0, pos) + "-"; suffix = filename.substring(pos); } // Files.createTempFile requires the prefix to be at least three characters long if (prefix.length() < 3) prefix = "download-"; } if (tempFolderPath == null) return Files.createTempFile(prefix, suffix).toFile(); else return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); } /** * {@link #execute(Call, Type)} * * @param <T> Type * @param call An instance of the Call object * @return ApiResponse&lt;T&gt; * @throws ai.lamin.lamin_api_client.ApiException If fail to execute the call */ public <T> ApiResponse<T> execute(Call call) throws ApiException { return execute(call, null); } /** * Execute HTTP call and deserialize the HTTP response body into the given return type. * * @param returnType The return type used to deserialize HTTP response body * @param <T> The return type corresponding to (same with) returnType * @param call Call * @return ApiResponse object containing response status, headers and * data, which is a Java object deserialized from response body and would be null * when returnType is null. * @throws ai.lamin.lamin_api_client.ApiException If fail to execute the call */ public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException { try { Response response = call.execute(); T data = handleResponse(response, returnType); return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data); } catch (IOException e) { throw new ApiException(e); } } /** * {@link #executeAsync(Call, Type, ApiCallback)} * * @param <T> Type * @param call An instance of the Call object * @param callback ApiCallback&lt;T&gt; */ public <T> void executeAsync(Call call, ApiCallback<T> callback) { executeAsync(call, null, callback); } /** * Execute HTTP call asynchronously. * * @param <T> Type * @param call The callback to be executed when the API call finishes * @param returnType Return type * @param callback ApiCallback * @see #execute(Call, Type) */ @SuppressWarnings("unchecked") public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) { call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callback.onFailure(new ApiException(e), 0, null); } @Override public void onResponse(Call call, Response response) throws IOException { T result; try { result = (T) handleResponse(response, returnType); } catch (ApiException e) { callback.onFailure(e, response.code(), response.headers().toMultimap()); return; } catch (Exception e) { callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); return; } callback.onSuccess(result, response.code(), response.headers().toMultimap()); } }); } /** * Handle the given response, return the deserialized object when the response is successful. * * @param <T> Type * @param response Response * @param returnType Return type * @return Type * @throws ai.lamin.lamin_api_client.ApiException If the response has an unsuccessful status code or * fail to deserialize the response body */ public <T> T handleResponse(Response response, Type returnType) throws ApiException { if (response.isSuccessful()) { if (returnType == null || response.code() == 204) { // returning null if the returnType is not defined, // or the status code is 204 (No Content) if (response.body() != null) { try { response.body().close(); } catch (Exception e) { throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); } } return null; } else { return deserialize(response, returnType); } } else { String respBody = null; if (response.body() != null) { try { respBody = response.body().string(); } catch (IOException e) { throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); } } throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); } } /** * Build HTTP call with the given options. * * @param baseUrl The base URL * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param collectionQueryParams The collection query parameters * @param body The request body object * @param headerParams The header parameters * @param cookieParams The cookie parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param callback Callback for upload/download progress * @return The HTTP call * @throws ai.lamin.lamin_api_client.ApiException If fail to serialize the request body object */ public Call buildCall(String baseUrl, String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException { Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); return httpClient.newCall(request); } /** * Build an HTTP request with the given options. * * @param baseUrl The base URL * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param collectionQueryParams The collection query parameters * @param body The request body object * @param headerParams The header parameters * @param cookieParams The cookie parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param callback Callback for upload/download progress * @return The HTTP request * @throws ai.lamin.lamin_api_client.ApiException If fail to serialize the request body object */ public Request buildRequest(String baseUrl, String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException { final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); // prepare HTTP request body RequestBody reqBody; String contentType = headerParams.get("Content-Type"); String contentTypePure = contentType; if (contentTypePure != null && contentTypePure.contains(";")) { contentTypePure = contentType.substring(0, contentType.indexOf(";")); } if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentTypePure)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); } } else { reqBody = serialize(body, contentType); } List<Pair> updatedQueryParams = new ArrayList<>(queryParams); // update parameters with authentication settings updateParamsForAuth(authNames, updatedQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); final Request.Builder reqBuilder = new Request.Builder().url(buildUrl(baseUrl, path, updatedQueryParams, collectionQueryParams)); processHeaderParams(headerParams, reqBuilder); processCookieParams(cookieParams, reqBuilder); // Associate callback with request (if not null) so interceptor can // access it when creating ProgressResponseBody reqBuilder.tag(callback); Request request = null; if (callback != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return request; } /** * Build full URL by concatenating base path, the given sub path and query parameters. * * @param baseUrl The base URL * @param path The sub path * @param queryParams The query parameters * @param collectionQueryParams The collection query parameters * @return The full URL */ public String buildUrl(String baseUrl, String path, List<Pair> queryParams, List<Pair> collectionQueryParams) { final StringBuilder url = new StringBuilder(); if (baseUrl != null) { url.append(baseUrl).append(path); } else { String baseURL; if (serverIndex != null) { if (serverIndex < 0 || serverIndex >= servers.size()) { throw new ArrayIndexOutOfBoundsException(String.format( "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() )); } baseURL = servers.get(serverIndex).URL(serverVariables); } else { baseURL = basePath; } url.append(baseURL).append(path); } if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" String prefix = path.contains("?") ? "&" : "?"; for (Pair param : queryParams) { if (param.getValue() != null) { if (prefix != null) { url.append(prefix); prefix = null; } else { url.append("&"); } String value = parameterToString(param.getValue()); url.append(escapeString(param.getName())).append("=").append(escapeString(value)); } } } if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { String prefix = url.toString().contains("?") ? "&" : "?"; for (Pair param : collectionQueryParams) { if (param.getValue() != null) { if (prefix != null) { url.append(prefix); prefix = null; } else { url.append("&"); } String value = parameterToString(param.getValue()); // collection query parameter value already escaped as part of parameterToPairs url.append(escapeString(param.getName())).append("=").append(value); } } } return url.toString(); } /** * Set header parameters to the request builder, including default headers. * * @param headerParams Header parameters in the form of Map * @param reqBuilder Request.Builder */ public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) { for (Entry<String, String> param : headerParams.entrySet()) { reqBuilder.header(param.getKey(), parameterToString(param.getValue())); } for (Entry<String, String> header : defaultHeaderMap.entrySet()) { if (!headerParams.containsKey(header.getKey())) { reqBuilder.header(header.getKey(), parameterToString(header.getValue())); } } } /** * Set cookie parameters to the request builder, including default cookies. * * @param cookieParams Cookie parameters in the form of Map * @param reqBuilder Request.Builder */ public void processCookieParams(Map<String, String> cookieParams, Request.Builder reqBuilder) { for (Entry<String, String> param : cookieParams.entrySet()) { reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); } for (Entry<String, String> param : defaultCookieMap.entrySet()) { if (!cookieParams.containsKey(param.getKey())) { reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); } } } /** * Update query and header parameters based on authentication settings. * * @param authNames The authentications to apply * @param queryParams List of query parameters * @param headerParams Map of header parameters * @param cookieParams Map of cookie parameters * @param payload HTTP request body * @param method HTTP method * @param uri URI * @throws ai.lamin.lamin_api_client.ApiException If fails to update the parameters */ public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) { throw new RuntimeException("Authentication undefined: " + authName); } auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); } } /** * Build a form-encoding request body with the given form parameters. * * @param formParams Form parameters in the form of Map * @return RequestBody */ public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) { okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); for (Entry<String, Object> param : formParams.entrySet()) { formBuilder.add(param.getKey(), parameterToString(param.getValue())); } return formBuilder.build(); } /** * Build a multipart (file uploading) request body with the given form parameters, * which could contain text fields and file fields. * * @param formParams Form parameters in the form of Map * @return RequestBody */ public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) { MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); for (Entry<String, Object> param : formParams.entrySet()) { if (param.getValue() instanceof File) { File file = (File) param.getValue(); addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); } else if (param.getValue() instanceof List) { List list = (List) param.getValue(); for (Object item: list) { if (item instanceof File) { addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); } else { addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); } } } else { addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); } } return mpBuilder.build(); } /** * Guess Content-Type header from the given file (defaults to "application/octet-stream"). * * @param file The given file * @return The guessed Content-Type */ public String guessContentTypeFromFile(File file) { String contentType = URLConnection.guessContentTypeFromName(file.getName()); if (contentType == null) { return "application/octet-stream"; } else { return contentType; } } /** * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. * * @param mpBuilder MultipartBody.Builder * @param key The key of the Header element * @param file The file to add to the Header */ private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); } /** * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. * * @param mpBuilder MultipartBody.Builder * @param key The key of the Header element * @param obj The complex object to add to the Header */ private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { RequestBody requestBody; if (obj instanceof String) { requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); } else { String content; if (obj != null) { content = JSON.serialize(obj); } else { content = null; } requestBody = RequestBody.create(content, MediaType.parse("application/json")); } Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); mpBuilder.addPart(partHeaders, requestBody); } /** * Get network interceptor to add it to the httpClient to track download progress for * async requests. */ private Interceptor getProgressInterceptor() { return new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { final Request request = chain.request(); final Response originalResponse = chain.proceed(request); if (request.tag() instanceof ApiCallback) { final ApiCallback callback = (ApiCallback) request.tag(); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), callback)) .build(); } return originalResponse; } }; } /** * Apply SSL related settings to httpClient according to the current values of * verifyingSsl and sslCaCert. */ private void applySslSettings() { try { TrustManager[] trustManagers; HostnameVerifier hostnameVerifier; if (!verifyingSsl) { trustManagers = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; } else { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); if (sslCaCert == null) { trustManagerFactory.init((KeyStore) null); } else { char[] password = null; // Any password will work. CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert); if (certificates.isEmpty()) { throw new IllegalArgumentException("expected non-empty set of trusted certificates"); } KeyStore caKeyStore = newEmptyKeyStore(password); int index = 0; for (Certificate certificate : certificates) { String certificateAlias = "ca" + (index++); caKeyStore.setCertificateEntry(certificateAlias, certificate); } trustManagerFactory.init(caKeyStore); } trustManagers = trustManagerFactory.getTrustManagers(); hostnameVerifier = OkHostnameVerifier.INSTANCE; } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, new SecureRandom()); httpClient = httpClient.newBuilder() .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) .hostnameVerifier(hostnameVerifier) .build(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, password); return keyStore; } catch (IOException e) { throw new AssertionError(e); } } /** * Convert the HTTP request body to a string. * * @param requestBody The HTTP request object * @return The string representation of the HTTP request body * @throws ai.lamin.lamin_api_client.ApiException If fail to serialize the request body object into a string */ private String requestBodyToString(RequestBody requestBody) throws ApiException { if (requestBody != null) { try { final Buffer buffer = new Buffer(); requestBody.writeTo(buffer); return buffer.readUtf8(); } catch (final IOException e) { throw new ApiException(e); } } // empty http request body return ""; } }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/ApiException.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; import java.util.Map; import java.util.List; /** * <p>ApiException class.</p> */ @SuppressWarnings("serial") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-06-17T13:08:14.011869776+02:00[Europe/Brussels]", comments = "Generator version: 7.12.0") public class ApiException extends Exception { private static final long serialVersionUID = 1L; private int code = 0; private Map<String, List<String>> responseHeaders = null; private String responseBody = null; /** * <p>Constructor for ApiException.</p> */ public ApiException() {} /** * <p>Constructor for ApiException.</p> * * @param throwable a {@link java.lang.Throwable} object */ public ApiException(Throwable throwable) { super(throwable); } /** * <p>Constructor for ApiException.</p> * * @param message the error message */ public ApiException(String message) { super(message); } /** * <p>Constructor for ApiException.</p> * * @param message the error message * @param throwable a {@link java.lang.Throwable} object * @param code HTTP status code * @param responseHeaders a {@link java.util.Map} of HTTP response headers * @param responseBody the response body */ public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) { super(message, throwable); this.code = code; this.responseHeaders = responseHeaders; this.responseBody = responseBody; } /** * <p>Constructor for ApiException.</p> * * @param message the error message * @param code HTTP status code * @param responseHeaders a {@link java.util.Map} of HTTP response headers * @param responseBody the response body */ public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) { this(message, (Throwable) null, code, responseHeaders, responseBody); } /** * <p>Constructor for ApiException.</p> * * @param message the error message * @param throwable a {@link java.lang.Throwable} object * @param code HTTP status code * @param responseHeaders a {@link java.util.Map} of HTTP response headers */ public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) { this(message, throwable, code, responseHeaders, null); } /** * <p>Constructor for ApiException.</p> * * @param code HTTP status code * @param responseHeaders a {@link java.util.Map} of HTTP response headers * @param responseBody the response body */ public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) { this("Response Code: " + code + " Response Body: " + responseBody, (Throwable) null, code, responseHeaders, responseBody); } /** * <p>Constructor for ApiException.</p> * * @param code HTTP status code * @param message a {@link java.lang.String} object */ public ApiException(int code, String message) { super(message); this.code = code; } /** * <p>Constructor for ApiException.</p> * * @param code HTTP status code * @param message the error message * @param responseHeaders a {@link java.util.Map} of HTTP response headers * @param responseBody the response body */ public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) { this(code, message); this.responseHeaders = responseHeaders; this.responseBody = responseBody; } /** * Get the HTTP status code. * * @return HTTP status code */ public int getCode() { return code; } /** * Get the HTTP response headers. * * @return A map of list of string */ public Map<String, List<String>> getResponseHeaders() { return responseHeaders; } /** * Get the HTTP response body. * * @return Response body in the form of string */ public String getResponseBody() { return responseBody; } /** * Get the exception message including HTTP response data. * * @return The exception message */ public String getMessage() { return String.format("Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s", super.getMessage(), this.getCode(), this.getResponseBody(), this.getResponseHeaders()); } }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/ApiResponse.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; import java.util.List; import java.util.Map; /** * API response returned by API call. */ public class ApiResponse<T> { final private int statusCode; final private Map<String, List<String>> headers; final private T data; /** * <p>Constructor for ApiResponse.</p> * * @param statusCode The status code of HTTP response * @param headers The headers of HTTP response */ public ApiResponse(int statusCode, Map<String, List<String>> headers) { this(statusCode, headers, null); } /** * <p>Constructor for ApiResponse.</p> * * @param statusCode The status code of HTTP response * @param headers The headers of HTTP response * @param data The object deserialized from response bod */ public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) { this.statusCode = statusCode; this.headers = headers; this.data = data; } /** * <p>Get the <code>status code</code>.</p> * * @return the status code */ public int getStatusCode() { return statusCode; } /** * <p>Get the <code>headers</code>.</p> * * @return a {@link java.util.Map} of headers */ public Map<String, List<String>> getHeaders() { return headers; } /** * <p>Get the <code>data</code>.</p> * * @return the data */ public T getData() { return data; } }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/Configuration.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-06-17T13:08:14.011869776+02:00[Europe/Brussels]", comments = "Generator version: 7.12.0") public class Configuration { public static final String VERSION = "0.0.3"; private static volatile ApiClient defaultApiClient = new ApiClient(); /** * Get the default API client, which would be used when creating API * instances without providing an API client. * * @return Default API client */ public static ApiClient getDefaultApiClient() { return defaultApiClient; } /** * Set the default API client, which would be used when creating API * instances without providing an API client. * * @param apiClient API client */ public static void setDefaultApiClient(ApiClient apiClient) { defaultApiClient = apiClient; } }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/GzipRequestInterceptor.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; import okhttp3.*; import okio.Buffer; import okio.BufferedSink; import okio.GzipSink; import okio.Okio; import java.io.IOException; /** * Encodes request bodies using gzip. * * Taken from https://github.com/square/okhttp/issues/350 */ class GzipRequestInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { return chain.proceed(originalRequest); } Request compressedRequest = originalRequest.newBuilder() .header("Content-Encoding", "gzip") .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) .build(); return chain.proceed(compressedRequest); } private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { final Buffer buffer = new Buffer(); requestBody.writeTo(buffer); return new RequestBody() { @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() { return buffer.size(); } @Override public void writeTo(BufferedSink sink) throws IOException { sink.write(buffer.snapshot()); } }; } private RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return -1; // We don't know the compressed length in advance! } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; } }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/JSON.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; import io.gsonfire.GsonFireBuilder; import io.gsonfire.TypeSelector; import okio.ByteString; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; /* * A JSON utility class * * NOTE: in the future, this class may be converted to static, which may break * backward-compatibility */ public class JSON { private static Gson gson; private static boolean isLenientOnJson = false; private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() ; GsonBuilder builder = fireBuilder.createGsonBuilder(); return builder; } private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { JsonElement element = readElement.getAsJsonObject().get(discriminatorField); if (null == element) { throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); } return element.getAsString(); } /** * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. * * @param classByDiscriminatorValue The map of discriminator values to Java classes. * @param discriminatorValue The value of the OpenAPI discriminator in the input data. * @return The Java class that implements the OpenAPI schema */ private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); if (null == clazz) { throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); } return clazz; } static { GsonBuilder gsonBuilder = createGson(); gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.AddCollaboratorRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.AddOrganizationMemberRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.AddSpaceCollaboratorRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.AddTeamMemberRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.AttachSpaceToRecordRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.CreateArtifactRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.CreateSpaceRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.CreateTeamRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.CreateTransformRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.DbUrlRequest.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.Dimension.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.GetRecordRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.GetRecordsRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.GetValuesRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.GroupByRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.HTTPValidationError.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.Measure.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.OrderByColumn.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.RegisterDbServerBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.RegisterFormRequest.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.Role.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.Role1.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.S3PermissionsRequest.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.UpdateCollaboratorRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.UpdateOrganizationMemberRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.UpdateSpaceCollaboratorRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.UpdateSpaceRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.UpdateTeamMemberRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.UpdateTeamRequestBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.ValidationError.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new ai.lamin.lamin_api_client.model.ValidationErrorLocInner.CustomTypeAdapterFactory()); gson = gsonBuilder.create(); } /** * Get Gson. * * @return Gson */ public static Gson getGson() { return gson; } /** * Set Gson. * * @param gson Gson */ public static void setGson(Gson gson) { JSON.gson = gson; } public static void setLenientOnJson(boolean lenientOnJson) { isLenientOnJson = lenientOnJson; } /** * Serialize the given Java object into JSON string. * * @param obj Object * @return String representation of the JSON */ public static String serialize(Object obj) { return gson.toJson(obj); } /** * Deserialize the given JSON string to Java object. * * @param <T> Type * @param body The JSON string * @param returnType The type to deserialize into * @return The deserialized Java object */ @SuppressWarnings("unchecked") public static <T> T deserialize(String body, Type returnType) { try { if (isLenientOnJson) { JsonReader jsonReader = new JsonReader(new StringReader(body)); // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) jsonReader.setLenient(true); return gson.fromJson(jsonReader, returnType); } else { return gson.fromJson(body, returnType); } } catch (JsonParseException e) { // Fallback processing when failed to parse JSON form response body: // return the response body string directly for the String return type; if (returnType.equals(String.class)) { return (T) body; } else { throw (e); } } } /** * Gson TypeAdapter for Byte Array type */ public static class ByteArrayAdapter extends TypeAdapter<byte[]> { @Override public void write(JsonWriter out, byte[] value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(ByteString.of(value).base64()); } } @Override public byte[] read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String bytesAsBase64 = in.nextString(); ByteString byteString = ByteString.decodeBase64(bytesAsBase64); return byteString.toByteArray(); } } } /** * Gson TypeAdapter for JSR310 OffsetDateTime type */ public static class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> { private DateTimeFormatter formatter; public OffsetDateTimeTypeAdapter() { this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); } public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { this.formatter = formatter; } public void setFormat(DateTimeFormatter dateFormat) { this.formatter = dateFormat; } @Override public void write(JsonWriter out, OffsetDateTime date) throws IOException { if (date == null) { out.nullValue(); } else { out.value(formatter.format(date)); } } @Override public OffsetDateTime read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); if (date.endsWith("+0000")) { date = date.substring(0, date.length()-5) + "Z"; } return OffsetDateTime.parse(date, formatter); } } } /** * Gson TypeAdapter for JSR310 LocalDate type */ public static class LocalDateTypeAdapter extends TypeAdapter<LocalDate> { private DateTimeFormatter formatter; public LocalDateTypeAdapter() { this(DateTimeFormatter.ISO_LOCAL_DATE); } public LocalDateTypeAdapter(DateTimeFormatter formatter) { this.formatter = formatter; } public void setFormat(DateTimeFormatter dateFormat) { this.formatter = dateFormat; } @Override public void write(JsonWriter out, LocalDate date) throws IOException { if (date == null) { out.nullValue(); } else { out.value(formatter.format(date)); } } @Override public LocalDate read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); return LocalDate.parse(date, formatter); } } } public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { offsetDateTimeTypeAdapter.setFormat(dateFormat); } public static void setLocalDateFormat(DateTimeFormatter dateFormat) { localDateTypeAdapter.setFormat(dateFormat); } /** * Gson TypeAdapter for java.sql.Date type * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used * (more efficient than SimpleDateFormat). */ public static class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> { private DateFormat dateFormat; public SqlDateTypeAdapter() {} public SqlDateTypeAdapter(DateFormat dateFormat) { this.dateFormat = dateFormat; } public void setFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public void write(JsonWriter out, java.sql.Date date) throws IOException { if (date == null) { out.nullValue(); } else { String value; if (dateFormat != null) { value = dateFormat.format(date); } else { value = date.toString(); } out.value(value); } } @Override public java.sql.Date read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); try { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } } } } /** * Gson TypeAdapter for java.util.Date type * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter<Date> { private DateFormat dateFormat; public DateTypeAdapter() {} public DateTypeAdapter(DateFormat dateFormat) { this.dateFormat = dateFormat; } public void setFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public void write(JsonWriter out, Date date) throws IOException { if (date == null) { out.nullValue(); } else { String value; if (dateFormat != null) { value = dateFormat.format(date); } else { value = ISO8601Utils.format(date, true); } out.value(value); } } @Override public Date read(JsonReader in) throws IOException { try { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); try { if (dateFormat != null) { return dateFormat.parse(date); } return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } } } catch (IllegalArgumentException e) { throw new JsonParseException(e); } } } public static void setDateFormat(DateFormat dateFormat) { dateTypeAdapter.setFormat(dateFormat); } public static void setSqlDateFormat(DateFormat dateFormat) { sqlDateTypeAdapter.setFormat(dateFormat); } }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/Pair.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-06-17T13:08:14.011869776+02:00[Europe/Brussels]", comments = "Generator version: 7.12.0") public class Pair { private String name = ""; private String value = ""; public Pair (String name, String value) { setName(name); setValue(value); } private void setName(String name) { if (!isValidString(name)) { return; } this.name = name; } private void setValue(String value) { if (!isValidString(value)) { return; } this.value = value; } public String getName() { return this.name; } public String getValue() { return this.value; } private boolean isValidString(String arg) { if (arg == null) { return false; } return true; } }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/ProgressRequestBody.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; import okhttp3.MediaType; import okhttp3.RequestBody; import java.io.IOException; import okio.Buffer; import okio.BufferedSink; import okio.ForwardingSink; import okio.Okio; import okio.Sink; public class ProgressRequestBody extends RequestBody { private final RequestBody requestBody; private final ApiCallback callback; public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { this.requestBody = requestBody; this.callback = callback; } @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() throws IOException { return requestBody.contentLength(); } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink bufferedSink = Okio.buffer(sink(sink)); requestBody.writeTo(bufferedSink); bufferedSink.flush(); } private Sink sink(Sink sink) { return new ForwardingSink(sink) { long bytesWritten = 0L; long contentLength = 0L; @Override public void write(Buffer source, long byteCount) throws IOException { super.write(source, byteCount); if (contentLength == 0) { contentLength = contentLength(); } bytesWritten += byteCount; callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength); } }; } }
0
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin
java-sources/ai/lamin/lamin-api-client/0.0.3/ai/lamin/lamin_api_client/ProgressResponseBody.java
/* * FastAPI * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package ai.lamin.lamin_api_client; import okhttp3.MediaType; import okhttp3.ResponseBody; import java.io.IOException; import okio.Buffer; import okio.BufferedSource; import okio.ForwardingSource; import okio.Okio; import okio.Source; public class ProgressResponseBody extends ResponseBody { private final ResponseBody responseBody; private final ApiCallback callback; private BufferedSource bufferedSource; public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { this.responseBody = responseBody; this.callback = callback; } @Override public MediaType contentType() { return responseBody.contentType(); } @Override public long contentLength() { return responseBody.contentLength(); } @Override public BufferedSource source() { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(responseBody.source())); } return bufferedSource; } private Source source(Source source) { return new ForwardingSource(source) { long totalBytesRead = 0L; @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); // read() returns the number of bytes read, or -1 if this source is exhausted. totalBytesRead += bytesRead != -1 ? bytesRead : 0; callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1); return bytesRead; } }; } }