index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/cheq/sst/android/cheq-sst-kotlin-protobuf/1.2.0/ai/cheq/sst/android/protobuf
java-sources/ai/cheq/sst/android/cheq-sst-kotlin-protobuf/1.2.0/ai/cheq/sst/android/protobuf/storage/StorageOuterClass.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // NO CHECKED-IN PROTOBUF GENCODE // source: storage.proto // Protobuf Java Version: 4.28.3 package ai.cheq.sst.android.protobuf.storage; public final class StorageOuterClass { private StorageOuterClass() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } static { } // @@protoc_insertion_point(outer_class_scope) }
0
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon/online/JTry.java
package ai.chronon.online; import scala.util.Try; import java.util.Objects; import java.util.function.Function; public abstract class JTry<V> { private JTry() { } public static <V> JTry<V> failure(Exception t) { Objects.requireNonNull(t); return new Failure<>(t); } public static <V> JTry<V> success(V value) { Objects.requireNonNull(value); return new Success<>(value); } public static <V> JTry<V> fromScala(Try<V> sTry) { if (sTry.isSuccess()) { return new Success<>(sTry.get()); } else { return new Failure(sTry.failed().get()); } } public abstract boolean isSuccess(); public abstract Exception getException(); public abstract V getValue(); public abstract <U> JTry<U> map(Function<? super V, ? extends U> f); public Try<V> toScala() { if (this.isSuccess()) { return new scala.util.Success<>(getValue()); } else { return new scala.util.Failure(getException()); } } private static class Failure<V> extends JTry<V> { private final Exception exception; public Failure(Throwable t) { super(); this.exception = new RuntimeException(t); } @Override public boolean isSuccess() { return false; } @Override public Exception getException() { return exception; } @Override public V getValue() { throw new RuntimeException("call getValue on a Failure object"); } @Override public <U> JTry<U> map(Function<? super V, ? extends U> f) { Objects.requireNonNull(f); return JTry.failure(exception); } } private static class Success<V> extends JTry<V> { private final V value; public Success(V value) { super(); this.value = value; } @Override public boolean isSuccess() { return true; } @Override public Exception getException() { throw new RuntimeException("Calling get exception on a successful object"); } @Override public V getValue() { return value; } @Override public <U> JTry<U> map(Function<? super V, ? extends U> f) { Objects.requireNonNull(f); try { return JTry.success(f.apply(value)); } catch (Exception t) { return JTry.failure(t); } } } }
0
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon/online/JavaExternalSourceHandler.java
package ai.chronon.online; import scala.collection.Seq; import scala.compat.java8.FutureConverters; import scala.concurrent.Future; import scala.util.ScalaVersionSpecificCollectionsConverter; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; // helper method to writeExternalSourceHandlers in java/kt etc. // the override method takes care of mapping to and from // scala.util.Try -> ai.chronon.online.JTry // scala.collection.immutable.Map -> java.util.Map // scala.collection.immutable.List -> java.util.List // scala.concurrent.Future -> java.util.concurrent.CompletableFuture public abstract class JavaExternalSourceHandler extends ExternalSourceHandler { //java friendly method public abstract CompletableFuture<java.util.List<JavaResponse>> fetchJava(java.util.List<JavaRequest> requests); @Override public Future<Seq<Fetcher.Response>> fetch(Seq<Fetcher.Request> requests) { java.util.List<JavaRequest> javaRequests = ScalaVersionSpecificCollectionsConverter .convertScalaListToJava(requests.toList()) .stream() .map(JavaRequest::fromScalaRequest) .collect(Collectors.toList()); CompletableFuture<java.util.List<JavaResponse>> jResultFuture = fetchJava(javaRequests); CompletableFuture<Seq<Fetcher.Response>> mapJFuture = jResultFuture.thenApply(jList -> { java.util.List<Fetcher.Response> jListSMap = jList .stream() .map(JavaResponse::toScala) .collect(Collectors.toList()); return ScalaVersionSpecificCollectionsConverter.convertJavaListToScala(jListSMap).toSeq(); } ); return FutureConverters.toScala(mapJFuture); } }
0
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon/online/JavaFetcher.java
package ai.chronon.online; import ai.chronon.api.Constants; import ai.chronon.online.Fetcher.Request; import ai.chronon.online.Fetcher.Response; import scala.collection.Iterator; import scala.collection.Seq; import scala.collection.mutable.ArrayBuffer; import scala.compat.java8.FutureConverters; import scala.concurrent.Future; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; public class JavaFetcher { Fetcher fetcher; public JavaFetcher(KVStore kvStore, String metaDataSet, Long timeoutMillis, Consumer<LoggableResponse> logFunc, ExternalSourceRegistry registry) { this.fetcher = new Fetcher(kvStore, metaDataSet, timeoutMillis, logFunc, false, registry); } public static List<JavaResponse> toJavaResponses(Seq<Response> responseSeq) { List<JavaResponse> result = new ArrayList<>(responseSeq.size()); Iterator<Response> it = responseSeq.iterator(); while(it.hasNext()) { result.add(new JavaResponse(it.next())); } return result; } private CompletableFuture<List<JavaResponse>> convertResponses(Future<Seq<Response>> responses) { return FutureConverters .toJava(responses) .toCompletableFuture() .thenApply(JavaFetcher::toJavaResponses); } private Seq<Request> convertJavaRequestList(List<JavaRequest> requests) { ArrayBuffer<Request> scalaRequests = new ArrayBuffer<>(); for (JavaRequest request : requests) { Request convertedRequest = request.toScalaRequest(); scalaRequests.$plus$eq(convertedRequest); } return scalaRequests.toSeq(); } public CompletableFuture<List<JavaResponse>> fetchGroupBys(List<JavaRequest> requests) { // Get responses from the fetcher Future<Seq<Response>> responses = this.fetcher.fetchGroupBys(convertJavaRequestList(requests)); // Convert responses to CompletableFuture return convertResponses(responses); } public CompletableFuture<List<JavaResponse>> fetchJoin(List<JavaRequest> requests) { Future<Seq<Response>> responses = this.fetcher.fetchJoin(convertJavaRequestList(requests)); // Convert responses to CompletableFuture return convertResponses(responses); } }
0
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon/online/JavaRequest.java
package ai.chronon.online; import scala.Option; import scala.util.ScalaVersionSpecificCollectionsConverter; import java.util.Map; public class JavaRequest { public String name; public Map<String, Object> keys; public Long atMillis; public JavaRequest(String name, Map<String, Object> keys) { this(name, keys, null); } public JavaRequest(String name, Map<String, Object> keys, Long atMillis) { this.name = name; this.keys = keys; this.atMillis = atMillis; } public JavaRequest(Fetcher.Request scalaRequest) { this.name = scalaRequest.name(); this.keys = ScalaVersionSpecificCollectionsConverter.convertScalaMapToJava(scalaRequest.keys()); Option<Object> millisOpt = scalaRequest.atMillis(); if (millisOpt.isDefined()) { this.atMillis = (Long) millisOpt.get(); } } public static JavaRequest fromScalaRequest(Fetcher.Request scalaRequest) { return new JavaRequest(scalaRequest); } public Fetcher.Request toScalaRequest() { scala.collection.immutable.Map<String, Object> scalaKeys = null; if (keys != null) { scalaKeys = ScalaVersionSpecificCollectionsConverter.convertJavaMapToScala(keys); } return new Fetcher.Request( this.name, scalaKeys, Option.apply(this.atMillis), Option.empty()); } }
0
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon
java-sources/ai/chronon/online_2.11/13_publish-0.0.12/ai/chronon/online/JavaResponse.java
package ai.chronon.online; import scala.util.ScalaVersionSpecificCollectionsConverter; import java.util.Map; public class JavaResponse { public JavaRequest request; public JTry<Map<String, Object>> values; public JavaResponse(JavaRequest request, JTry<Map<String, Object>> values) { this.request = request; this.values = values; } public JavaResponse(Fetcher.Response scalaResponse){ this.request = new JavaRequest(scalaResponse.request()); this.values = JTry .fromScala(scalaResponse.values()) .map(ScalaVersionSpecificCollectionsConverter::convertScalaMapToJava); } public Fetcher.Response toScala(){ return new Fetcher.Response( request.toScalaRequest(), values.map(ScalaVersionSpecificCollectionsConverter::convertJavaMapToScala).toScala()); } }
0
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service/ApiProvider.java
package ai.chronon.service; import ai.chronon.online.Api; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.util.ScalaVersionSpecificCollectionsConverter; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.Map; import java.util.Optional; /** * Responsible for loading the relevant concrete Chronon Api implementation and providing that * for use in the Web service code. We follow similar semantics as the Driver to configure this: * online.jar - Jar that contains the implementation of the Api * online.class - Name of the Api class * online.api.props - Structure that contains fields that are loaded and passed to the Api implementation * during instantiation to configure it (e.g. connection params) */ public class ApiProvider { private static final Logger logger = LoggerFactory.getLogger(ApiProvider.class); public static Api buildApi(ConfigStore configStore) throws Exception { Optional<String> maybeJarPath = configStore.getOnlineJar(); Optional<String> maybeClass = configStore.getOnlineClass(); if (!(maybeJarPath.isPresent() && maybeClass.isPresent())) { throw new IllegalArgumentException("Both 'online.jar' and 'online.class' configs must be set."); } String jarPath = maybeJarPath.get(); String className = maybeClass.get(); File jarFile = new File(jarPath); if (!jarFile.exists()) { throw new IllegalArgumentException("JAR file does not exist: " + jarPath); } logger.info("Loading API implementation from JAR: {}, class: {}", jarPath, className); // Create class loader for the API JAR URL jarUrl = jarFile.toURI().toURL(); URLClassLoader apiClassLoader = new URLClassLoader( new URL[]{jarUrl}, ApiProvider.class.getClassLoader() ); // Load and instantiate the API implementation Class<?> apiClass = Class.forName(className, true, apiClassLoader); if (!Api.class.isAssignableFrom(apiClass)) { throw new IllegalArgumentException( "Class " + className + " does not extend the Api abstract class" ); } Map<String, String> propsMap = configStore.getOnlineApiProps(); scala.collection.immutable.Map<String, String> scalaPropsMap = ScalaVersionSpecificCollectionsConverter.convertJavaMapToScala(propsMap); return (Api) apiClass.getConstructors()[0].newInstance(scalaPropsMap); } }
0
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service/ChrononServiceLauncher.java
package ai.chronon.service; import ai.chronon.online.Metrics; import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.statsd.StatsdConfig; import io.micrometer.statsd.StatsdMeterRegistry; import io.vertx.core.Launcher; import io.vertx.core.VertxOptions; import io.vertx.micrometer.Label; import io.vertx.micrometer.MicrometerMetricsFactory; import io.vertx.micrometer.MicrometerMetricsOptions; import java.util.HashMap; import java.util.Map; /** * Custom launcher to help configure the Chronon vertx feature service * to handle things like setting up a statsd metrics registry. * We use statsd here to be consistent with the rest of our project (e.g. fetcher code). * This allows us to send Vertx webservice metrics along with fetcher related metrics to allow users * to debug performance issues and set alerts etc. */ public class ChrononServiceLauncher extends Launcher { @Override public void beforeStartingVertx(VertxOptions options) { StatsdConfig config = new StatsdConfig() { private final String statsdHost = Metrics.Context$.MODULE$.statsHost(); private final String statsdPort = String.valueOf(Metrics.Context$.MODULE$.statsPort()); final Map<String, String> statsProps = new HashMap<String, String>() {{ put(prefix() + "." + "port", statsdPort); put(prefix() + "." + "host", statsdHost); put(prefix() + "." + "protocol", Integer.parseInt(statsdPort) == 0 ? "UDS_DATAGRAM" : "UDP"); }}; @Override public String get(String key) { return statsProps.get(key); } }; MeterRegistry registry = new StatsdMeterRegistry(config, Clock.SYSTEM); MicrometerMetricsFactory metricsFactory = new MicrometerMetricsFactory(registry); // Configure metrics via statsd MicrometerMetricsOptions metricsOptions = new MicrometerMetricsOptions() .setEnabled(true) .setJvmMetricsEnabled(true) .setFactory(metricsFactory) .addLabels(Label.HTTP_METHOD, Label.HTTP_CODE, Label.HTTP_PATH); options.setMetricsOptions(metricsOptions); } public static void main(String[] args) { new ChrononServiceLauncher().dispatch(args); } }
0
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service/ConfigStore.java
package ai.chronon.service; import io.vertx.config.ConfigRetriever; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Helps keep track of the various Chronon fetcher service configs. * We currently read configs once at startup - this makes sense for configs * such as the server port and we can revisit / extend things in the future to * be able to hot-refresh configs like Vertx supports under the hood. */ public class ConfigStore { private static final int DEFAULT_PORT = 8080; private static final String SERVER_PORT = "server.port"; private static final String ONLINE_JAR = "online.jar"; private static final String ONLINE_CLASS = "online.class"; private static final String ONLINE_API_PROPS = "online.api.props"; private volatile JsonObject jsonConfig; private final Object lock = new Object(); public ConfigStore(Vertx vertx) { // Use CountDownLatch to wait for config loading CountDownLatch latch = new CountDownLatch(1); ConfigRetriever configRetriever = ConfigRetriever.create(vertx); configRetriever.getConfig().onComplete(ar -> { if (ar.failed()) { throw new IllegalStateException("Unable to load service config", ar.cause()); } synchronized (lock) { jsonConfig = ar.result(); } latch.countDown(); }); try { if (!latch.await(1, TimeUnit.SECONDS)) { throw new IllegalStateException("Timed out waiting for Vertx config read"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted while loading config", e); } } public int getServerPort() { return jsonConfig.getInteger(SERVER_PORT, DEFAULT_PORT); } public Optional<String> getOnlineJar() { return Optional.ofNullable(jsonConfig.getString(ONLINE_JAR)); } public Optional<String> getOnlineClass() { return Optional.ofNullable(jsonConfig.getString(ONLINE_CLASS)); } public Map<String, String> getOnlineApiProps() { JsonObject apiProps = jsonConfig.getJsonObject(ONLINE_API_PROPS); if (apiProps == null) { return new HashMap<String, String>(); } return apiProps.stream().collect(Collectors.toMap( Map.Entry::getKey, e -> String.valueOf(e.getValue()) )); } public String encodeConfig() { return jsonConfig.encodePrettily(); } }
0
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service/WebServiceVerticle.java
package ai.chronon.service; import ai.chronon.online.Api; import ai.chronon.service.handlers.FeaturesRouter; import io.vertx.core.AbstractVerticle; import io.vertx.core.Promise; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerOptions; import io.vertx.ext.web.Router; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Entry point for the Chronon webservice. We wire up our API routes and configure and launch our HTTP service here. * We choose to use just 1 verticle for now as it allows us to keep things simple and we don't need to scale / * independently deploy different endpoint routes. */ public class WebServiceVerticle extends AbstractVerticle { private static final Logger logger = LoggerFactory.getLogger(WebServiceVerticle.class); private HttpServer server; @Override public void start(Promise<Void> startPromise) throws Exception { ConfigStore cfgStore = new ConfigStore(vertx); startHttpServer(cfgStore.getServerPort(), cfgStore.encodeConfig(), ApiProvider.buildApi(cfgStore), startPromise); } protected void startHttpServer(int port, String configJsonString, Api api, Promise<Void> startPromise) throws Exception { Router router = Router.router(vertx); // Define routes // Set up sub-routes for the various feature retrieval apis router.route("/v1/features/*").subRouter(FeaturesRouter.createFeaturesRoutes(vertx, api)); // Health check route router.get("/ping").handler(ctx -> { ctx.json("Pong!"); }); // Add route to show current configuration router.get("/config").handler(ctx -> { ctx.response() .putHeader("content-type", "application/json") .end(configJsonString); }); // Start HTTP server HttpServerOptions httpOptions = new HttpServerOptions() .setTcpKeepAlive(true) .setIdleTimeout(60); server = vertx.createHttpServer(httpOptions); server.requestHandler(router) .listen(port) .onSuccess(server -> { logger.info("HTTP server started on port {}", server.actualPort()); startPromise.complete(); }) .onFailure(err -> { logger.error("Failed to start HTTP server", err); startPromise.fail(err); }); } @Override public void stop(Promise<Void> stopPromise) { logger.info("Stopping HTTP server..."); if (server != null) { server.close() .onSuccess(v -> { logger.info("HTTP server stopped successfully"); stopPromise.complete(); }) .onFailure(err -> { logger.error("Failed to stop HTTP server", err); stopPromise.fail(err); }); } else { stopPromise.complete(); } } }
0
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service/handlers/FeaturesHandler.java
package ai.chronon.service.handlers; import ai.chronon.online.JTry; import ai.chronon.online.JavaFetcher; import ai.chronon.online.JavaRequest; import ai.chronon.online.JavaResponse; import ai.chronon.service.model.GetFeaturesResponse; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RequestBody; import io.vertx.ext.web.RoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static ai.chronon.service.model.GetFeaturesResponse.Result.Status.Failure; import static ai.chronon.service.model.GetFeaturesResponse.Result.Status.Success; /** * Concrete implementation of the GetFeatures endpoints. Supports loading groupBys and joins. * Some notes on this: * We currently support bulkGet lookups against a single groupBy / join. Attempts to lookup n different GroupBys / Joins * need to be split up into n different requests. * A given bulkGet request might result in some successful lookups and some failed ones. We return a 4xx or 5xx response * if the overall request fails (e.g. we're not able to parse the input json, Future failure due to Api returning an error) * Individual failure responses will be marked as 'Failed' however the overall response status code will be successful (200) * The response list maintains the same order as the incoming request list. * As an example: * { results: [ {"status": "Success", "features": ...}, {"status": "Failure", "error": ...} ] } */ public class FeaturesHandler implements Handler<RoutingContext> { public enum EntityType { GroupBy, Join } // PoJo to simplify transforming responses from the Fetcher to the final results form we return private static class EntityKeyToValues { public EntityKeyToValues(Map<String, Object> keys, JTry<Map<String, Object>> values) { this.entityKeys = keys; this.features = values; } public Map<String, Object> entityKeys; public JTry<Map<String, Object>> features; } private static final Logger logger = LoggerFactory.getLogger(FeaturesHandler.class); private static final ObjectMapper objectMapper = new ObjectMapper(); private final EntityType entityType; private final JavaFetcher fetcher; public FeaturesHandler(EntityType entityType, JavaFetcher fetcher) { this.entityType = entityType; this.fetcher = fetcher; } @Override public void handle(RoutingContext ctx) { String entityName = ctx.pathParam("name"); logger.debug("Retrieving {} - {}", entityType.name(), entityName); JTry<List<JavaRequest>> maybeRequest = parseJavaRequest(entityName, ctx.body()); if (! maybeRequest.isSuccess()) { logger.error("Unable to parse request body", maybeRequest.getException()); List<String> errorMessages = Collections.singletonList(maybeRequest.getException().getMessage()); ctx.response() .setStatusCode(400) .putHeader("content-type", "application/json") .end(new JsonObject().put("errors", errorMessages).encode()); return; } List<JavaRequest> requests = maybeRequest.getValue(); CompletableFuture<List<JavaResponse>> resultsJavaFuture = entityType.equals(EntityType.GroupBy) ? fetcher.fetchGroupBys(requests) : fetcher.fetchJoin(requests); // wrap the Java future we get in a Vert.x Future to not block the worker thread Future<List<EntityKeyToValues>> maybeFeatureResponses = Future.fromCompletionStage(resultsJavaFuture) .map(result -> result.stream().map(FeaturesHandler::responseToPoJo) .collect(Collectors.toList())); maybeFeatureResponses.onSuccess(resultList -> { // as this is a bulkGet request, we might have some successful and some failed responses // we return the responses in the same order as they come in and mark them as successful / failed based // on the lookups GetFeaturesResponse.Builder responseBuilder = GetFeaturesResponse.builder(); List<GetFeaturesResponse.Result> results = resultList.stream().map(resultsPojo -> { if (resultsPojo.features.isSuccess()) { return GetFeaturesResponse.Result.builder().status(Success).entityKeys(resultsPojo.entityKeys).features(resultsPojo.features.getValue()).build(); } else { return GetFeaturesResponse.Result.builder().status(Failure).entityKeys(resultsPojo.entityKeys).error(resultsPojo.features.getException().getMessage()).build(); } }).collect(Collectors.toList()); responseBuilder.results(results); ctx.response() .setStatusCode(200) .putHeader("content-type", "application/json") .end(JsonObject.mapFrom(responseBuilder.build()).encode()); }); maybeFeatureResponses.onFailure(err -> { List<String> failureMessages = Collections.singletonList(err.getMessage()); ctx.response() .setStatusCode(500) .putHeader("content-type", "application/json") .end(new JsonObject().put("errors", failureMessages).encode()); }); } public static EntityKeyToValues responseToPoJo(JavaResponse response) { return new EntityKeyToValues(response.request.keys, response.values); } public static JTry<List<JavaRequest>> parseJavaRequest(String name, RequestBody body) { TypeReference<List<Map<String, Object>>> ref = new TypeReference<List<Map<String, Object>>>() { }; try { List<Map<String, Object>> entityKeysList = objectMapper.readValue(body.asString(), ref); List<JavaRequest> requests = entityKeysList.stream().map(m -> new JavaRequest(name, m)).collect(Collectors.toList()); return JTry.success(requests); } catch (Exception e) { return JTry.failure(e); } } }
0
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service/handlers/FeaturesRouter.java
package ai.chronon.service.handlers; import ai.chronon.online.*; import io.vertx.core.Vertx; import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.BodyHandler; import static ai.chronon.service.handlers.FeaturesHandler.EntityType.GroupBy; import static ai.chronon.service.handlers.FeaturesHandler.EntityType.Join; // Configures the routes for our get features endpoints // We support bulkGets of groupBys and bulkGets of joins public class FeaturesRouter { public static Router createFeaturesRoutes(Vertx vertx, Api api) { Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); JavaFetcher fetcher = api.buildJavaFetcher("feature-service", false); router.post("/groupby/:name").handler(new FeaturesHandler(GroupBy, fetcher)); router.post("/join/:name").handler(new FeaturesHandler(Join, fetcher)); return router; } }
0
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service
java-sources/ai/chronon/service_2.11/0.0.108/ai/chronon/service/model/GetFeaturesResponse.java
package ai.chronon.service.model; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * PoJo capturing the response we return back as part of /v1/features/groupby and /v1/features/join endpoints * when the individual bulkGet lookups were either all successful or partially successful. */ @JsonInclude(JsonInclude.Include.NON_NULL) public class GetFeaturesResponse { private final List<Result> results; private GetFeaturesResponse(Builder builder) { this.results = builder.results; } public List<Result> getResults() { return results; } public static Builder builder() { return new Builder(); } public static class Builder { private List<Result> results = new ArrayList<>(); public Builder results(List<Result> results) { this.results = results; return this; } public Builder addResult(Result result) { this.results.add(result); return this; } public GetFeaturesResponse build() { return new GetFeaturesResponse(this); } } @JsonInclude(JsonInclude.Include.NON_NULL) public static class Result { public enum Status { Success, Failure } private final Status status; private final Map<String, Object> entityKeys; private final Map<String, Object> features; private final String error; private Result(Builder builder) { this.status = builder.status; this.entityKeys = builder.entityKeys; this.features = builder.features; this.error = builder.error; } public Status getStatus() { return status; } public Map<String, Object> getFeatures() { return features; } public Map<String, Object> getEntityKeys() { return entityKeys; } public String getError() { return error; } public static Builder builder() { return new Builder(); } public static class Builder { private Status status; private Map<String, Object> entityKeys; private Map<String, Object> features; private String error; public Builder status(Status status) { this.status = status; return this; } public Builder features(Map<String, Object> features) { this.features = features; return this; } public Builder entityKeys(Map<String, Object> entityKeys) { this.entityKeys = entityKeys; return this; } public Builder error(String error) { this.error = error; return this; } public Result build() { return new Result(this); } } } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/ApiCallback.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.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/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/ApiClient.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.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.regex.Matcher; import java.util.regex.Pattern; import ai.cochl.client.auth.Authentication; import ai.cochl.client.auth.HttpBasicAuth; import ai.cochl.client.auth.HttpBearerAuth; import ai.cochl.client.auth.ApiKeyAuth; /** * <p>ApiClient class.</p> */ public class ApiClient { private String basePath = "https://api.cochl.ai/sense/api/v1"; 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). authentications.put("API_Key", new ApiKeyAuth("header", "x-api-key")); // 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). authentications.put("API_Key", new ApiKeyAuth("header", "x-api-key")); // 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/v1.4.0/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://api.cochl.ai/sense/api/v1 * @return An instance of OkHttpClient */ public ApiClient setBasePath(String basePath) { this.basePath = basePath; 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 org.openapitools.client.ApiClient} object */ public ApiClient setDateFormat(DateFormat dateFormat) { this.json.setDateFormat(dateFormat); return this; } /** * <p>Set SqlDateFormat.</p> * * @param dateFormat a {@link java.text.DateFormat} object * @return a {@link org.openapitools.client.ApiClient} object */ public ApiClient setSqlDateFormat(DateFormat dateFormat) { this.json.setSqlDateFormat(dateFormat); return this; } /** * <p>Set OffsetDateTimeFormat.</p> * * @param dateFormat a {@link org.threeten.bp.format.DateTimeFormatter} object * @return a {@link org.openapitools.client.ApiClient} object */ public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { this.json.setOffsetDateTimeFormat(dateFormat); return this; } /** * <p>Set LocalDateFormat.</p> * * @param dateFormat a {@link org.threeten.bp.format.DateTimeFormatter} object * @return a {@link org.openapitools.client.ApiClient} object */ public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { this.json.setLocalDateFormat(dateFormat); return this; } /** * <p>Set LenientOnJson.</p> * * @param lenientOnJson a boolean * @return a {@link org.openapitools.client.ApiClient} object */ public ApiClient setLenientOnJson(boolean lenientOnJson) { this.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!"); } /** * 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(String.valueOf(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 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 org.openapitools.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 org.openapitools.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 { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } } /** * Download file from the given response. * * @param response An instance of the Response object * @throws org.openapitools.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 org.openapitools.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 org.openapitools.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 org.openapitools.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 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 org.openapitools.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 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 org.openapitools.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 { // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams List<Pair> allQueryParams = new ArrayList<Pair>(queryParams); allQueryParams.addAll(collectionQueryParams); final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); // prepare HTTP request body RequestBody reqBody; String contentType = headerParams.get("Content-Type"); if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { 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("", MediaType.parse(contentType)); } } else { reqBody = serialize(body, contentType); } // update parameters with authentication settings updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); final Request.Builder reqBuilder = new Request.Builder().url(url); 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 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 { url.append(basePath).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 */ 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(); Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); } else { Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); mpBuilder.addPart(partHeaders, RequestBody.create(parameterToString(param.getValue()), null)); } } 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; } } /** * 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" + Integer.toString(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 request The HTTP request object * @return The string representation of the HTTP request body * @throws org.openapitools.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/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/ApiException.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.client; import java.util.Map; import java.util.List; /** * <p>ApiException class.</p> */ @SuppressWarnings("serial") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class ApiException extends Exception { 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((String) null, (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; } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/ApiResponse.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.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/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/Configuration.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.client; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class Configuration { private static 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/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/GzipRequestInterceptor.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.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/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/JSON.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.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 ai.cochl.sense.model.*; 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; public class JSON { private Gson gson; private boolean isLenientOnJson = false; private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private 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; } public JSON() { gson = createGson() .registerTypeAdapter(Date.class, dateTypeAdapter) .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) .registerTypeAdapter(byte[].class, byteArrayAdapter) .create(); } /** * Get Gson. * * @return Gson */ public Gson getGson() { return gson; } /** * Set Gson. * * @param gson Gson * @return JSON */ public JSON setGson(Gson gson) { this.gson = gson; return this; } /** * Configure the parser to be liberal in what it accepts. * * @param lenientOnJson Set it to true to ignore some syntax errors * @return JSON * @see <a href="https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html">https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html</a> */ public JSON setLenientOnJson(boolean lenientOnJson) { isLenientOnJson = lenientOnJson; return this; } /** * Serialize the given Java object into JSON string. * * @param obj Object * @return String representation of the JSON */ public 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 <T> T deserialize(String body, Type returnType) { try { if (isLenientOnJson) { JsonReader jsonReader = new JsonReader(new StringReader(body)); // see https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html 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 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 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 JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { offsetDateTimeTypeAdapter.setFormat(dateFormat); return this; } public JSON setLocalDateFormat(DateTimeFormatter dateFormat) { localDateTypeAdapter.setFormat(dateFormat); return this; } /** * 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 JSON setDateFormat(DateFormat dateFormat) { dateTypeAdapter.setFormat(dateFormat); return this; } public JSON setSqlDateFormat(DateFormat dateFormat) { sqlDateTypeAdapter.setFormat(dateFormat); return this; } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/Pair.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.client; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") 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/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/ProgressRequestBody.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.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/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/ProgressResponseBody.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.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; } }; } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/ServerConfiguration.java
package ai.cochl.client; import java.util.Map; /** * Representing a Server configuration. */ public class ServerConfiguration { public String URL; public String description; public Map<String, ServerVariable> variables; /** * @param URL A URL to the target host. * @param description A description of the host designated by the URL. * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. */ public ServerConfiguration(String URL, String description, Map<String, ServerVariable> variables) { this.URL = URL; this.description = description; this.variables = variables; } /** * Format URL template using given variables. * * @param variables A map between a variable name and its value. * @return Formatted URL. */ public String URL(Map<String, String> variables) { String url = this.URL; // go through variables and replace placeholders for (Map.Entry<String, ServerVariable> variable: this.variables.entrySet()) { String name = variable.getKey(); ServerVariable serverVariable = variable.getValue(); String value = serverVariable.defaultValue; if (variables != null && variables.containsKey(name)) { value = variables.get(name); if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { throw new RuntimeException("The variable " + name + " in the server URL has invalid value " + value + "."); } } url = url.replaceAll("\\{" + name + "\\}", value); } return url; } /** * Format URL template using default server variables. * * @return Formatted URL. */ public String URL() { return URL(null); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/ServerVariable.java
package ai.cochl.client; import java.util.HashSet; /** * Representing a Server Variable for server URL template substitution. */ public class ServerVariable { public String description; public String defaultValue; public HashSet<String> enumValues = null; /** * @param description A description for the server variable. * @param defaultValue The default value to use for substitution. * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. */ public ServerVariable(String description, String defaultValue, HashSet<String> enumValues) { this.description = description; this.defaultValue = defaultValue; this.enumValues = enumValues; } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/StringUtil.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.client; import java.util.Collection; import java.util.Iterator; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). * * @param array The array * @param value The value to search * @return true if the array contains the value */ public static boolean containsIgnoreCase(String[] array, String value) { for (String str : array) { if (value == null && str == null) { return true; } if (value != null && value.equalsIgnoreCase(str)) { return true; } } return false; } /** * Join an array of strings with the given separator. * <p> * Note: This might be replaced by utility method from commons-lang or guava someday * if one of those libraries is added as dependency. * </p> * * @param array The array of strings * @param separator The separator * @return the resulting string */ public static String join(String[] array, String separator) { int len = array.length; if (len == 0) { return ""; } StringBuilder out = new StringBuilder(); out.append(array[0]); for (int i = 1; i < len; i++) { out.append(separator).append(array[i]); } return out.toString(); } /** * Join a list of strings with the given separator. * * @param list The list of strings * @param separator The separator * @return the resulting string */ public static String join(Collection<String> list, String separator) { Iterator<String> iterator = list.iterator(); StringBuilder out = new StringBuilder(); if (iterator.hasNext()) { out.append(iterator.next()); } while (iterator.hasNext()) { out.append(separator).append(iterator.next()); } return out.toString(); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/auth/ApiKeyAuth.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.client.auth; import ai.cochl.client.ApiException; import ai.cochl.client.Pair; import java.net.URI; import java.util.Map; import java.util.List; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; private String apiKey; private String apiKeyPrefix; public ApiKeyAuth(String location, String paramName) { this.location = location; this.paramName = paramName; } public String getLocation() { return location; } public String getParamName() { return paramName; } public String getApiKey() { return apiKey; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public String getApiKeyPrefix() { return apiKeyPrefix; } public void setApiKeyPrefix(String apiKeyPrefix) { this.apiKeyPrefix = apiKeyPrefix; } @Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException { if (apiKey == null) { return; } String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; } else { value = apiKey; } if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); } else if ("header".equals(location)) { headerParams.put(paramName, value); } else if ("cookie".equals(location)) { cookieParams.put(paramName, value); } } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/auth/Authentication.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.client.auth; import ai.cochl.client.Pair; import ai.cochl.client.ApiException; import java.net.URI; import java.util.Map; import java.util.List; public interface Authentication { /** * Apply authentication settings to header and query params. * * @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 ApiException if failed to update the parameters */ void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException; }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/auth/HttpBasicAuth.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.client.auth; import ai.cochl.client.Pair; import ai.cochl.client.ApiException; import okhttp3.Credentials; import java.net.URI; import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; public class HttpBasicAuth implements Authentication { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException { if (username == null && password == null) { return; } headerParams.put("Authorization", Credentials.basic( username == null ? "" : username, password == null ? "" : password)); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/client/auth/HttpBearerAuth.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.client.auth; import ai.cochl.client.ApiException; import ai.cochl.client.Pair; import java.net.URI; import java.util.Map; import java.util.List; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; private String bearerToken; public HttpBearerAuth(String scheme) { this.scheme = scheme; } /** * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. * * @return The bearer token */ public String getBearerToken() { return bearerToken; } /** * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. * * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { this.bearerToken = bearerToken; } @Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException { if (bearerToken == null) { return; } headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); } private static String upperCaseBearer(String scheme) { return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/api/AudioSessionApi.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.api; import ai.cochl.client.ApiCallback; import ai.cochl.client.ApiClient; import ai.cochl.client.ApiException; import ai.cochl.client.ApiResponse; import ai.cochl.client.Configuration; import ai.cochl.client.Pair; import ai.cochl.client.ProgressRequestBody; import ai.cochl.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.cochl.sense.model.AudioChunk; import ai.cochl.sense.model.CreateSession; import ai.cochl.sense.model.GenericError; import ai.cochl.sense.model.SessionRefs; import ai.cochl.sense.model.SessionStatus; import ai.cochl.sense.model.UpdateSession; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class AudioSessionApi { private ApiClient localVarApiClient; private int localHostIndex; private String localCustomBaseUrl; public AudioSessionApi() { this(Configuration.getDefaultApiClient()); } public AudioSessionApi(ApiClient apiClient) { this.localVarApiClient = apiClient; } public ApiClient getApiClient() { return localVarApiClient; } public void setApiClient(ApiClient apiClient) { this.localVarApiClient = apiClient; } public int getHostIndex() { return localHostIndex; } public void setHostIndex(int hostIndex) { this.localHostIndex = hostIndex; } public String getCustomBaseUrl() { return localCustomBaseUrl; } public void setCustomBaseUrl(String customBaseUrl) { this.localCustomBaseUrl = customBaseUrl; } /** * Build call for createSession * @param createSession (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The session was created successfully </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 401 </td><td> Authentication failed. For instance, API key is missing or invalid </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call createSessionCall(CreateSession createSession, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; // Determine Base Path to Use if (localCustomBaseUrl != null){ basePath = localCustomBaseUrl; } else if ( localBasePaths.length > 0 ) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = createSession; // create path and map variables String localVarPath = "/audio_sessions/"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { "API_Key" }; return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call createSessionValidateBeforeCall(CreateSession createSession, final ApiCallback _callback) throws ApiException { // verify the required parameter 'createSession' is set if (createSession == null) { throw new ApiException("Missing the required parameter 'createSession' when calling createSession(Async)"); } okhttp3.Call localVarCall = createSessionCall(createSession, _callback); return localVarCall; } /** * Create Session * Create a new session. An API key is required. Session parameters are immutable and can be set at creation only. * @param createSession (required) * @return SessionRefs * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The session was created successfully </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 401 </td><td> Authentication failed. For instance, API key is missing or invalid </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public SessionRefs createSession(CreateSession createSession) throws ApiException { ApiResponse<SessionRefs> localVarResp = createSessionWithHttpInfo(createSession); return localVarResp.getData(); } /** * Create Session * Create a new session. An API key is required. Session parameters are immutable and can be set at creation only. * @param createSession (required) * @return ApiResponse&lt;SessionRefs&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The session was created successfully </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 401 </td><td> Authentication failed. For instance, API key is missing or invalid </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public ApiResponse<SessionRefs> createSessionWithHttpInfo(CreateSession createSession) throws ApiException { okhttp3.Call localVarCall = createSessionValidateBeforeCall(createSession, null); Type localVarReturnType = new TypeToken<SessionRefs>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Create Session (asynchronously) * Create a new session. An API key is required. Session parameters are immutable and can be set at creation only. * @param createSession (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The session was created successfully </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 401 </td><td> Authentication failed. For instance, API key is missing or invalid </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call createSessionAsync(CreateSession createSession, final ApiCallback<SessionRefs> _callback) throws ApiException { okhttp3.Call localVarCall = createSessionValidateBeforeCall(createSession, _callback); Type localVarReturnType = new TypeToken<SessionRefs>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for deleteSession * @param sessionId Session id represents a unique identifier for an audio session (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The session successfully deleted </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don&#39;t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call deleteSessionCall(String sessionId, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; // Determine Base Path to Use if (localCustomBaseUrl != null){ basePath = localCustomBaseUrl; } else if ( localBasePaths.length > 0 ) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = null; // create path and map variables String localVarPath = "/audio_sessions/{session_id}" .replaceAll("\\{" + "session_id" + "\\}", localVarApiClient.escapeString(sessionId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { }; return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call deleteSessionValidateBeforeCall(String sessionId, final ApiCallback _callback) throws ApiException { // verify the required parameter 'sessionId' is set if (sessionId == null) { throw new ApiException("Missing the required parameter 'sessionId' when calling deleteSession(Async)"); } okhttp3.Call localVarCall = deleteSessionCall(sessionId, _callback); return localVarCall; } /** * Delete Session * Change the state of the session to *deleted*. All future call on the session will return 404 * @param sessionId Session id represents a unique identifier for an audio session (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The session successfully deleted </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don&#39;t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public void deleteSession(String sessionId) throws ApiException { deleteSessionWithHttpInfo(sessionId); } /** * Delete Session * Change the state of the session to *deleted*. All future call on the session will return 404 * @param sessionId Session id represents a unique identifier for an audio session (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The session successfully deleted </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don&#39;t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public ApiResponse<Void> deleteSessionWithHttpInfo(String sessionId) throws ApiException { okhttp3.Call localVarCall = deleteSessionValidateBeforeCall(sessionId, null); return localVarApiClient.execute(localVarCall); } /** * Delete Session (asynchronously) * Change the state of the session to *deleted*. All future call on the session will return 404 * @param sessionId Session id represents a unique identifier for an audio session (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The session successfully deleted </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don&#39;t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call deleteSessionAsync(String sessionId, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = deleteSessionValidateBeforeCall(sessionId, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for readStatus * @param sessionId Session id represents a unique identifier for an audio session (required) * @param offset How many existing elements to skip before returning the first result control how many results to receive (optional, default to 0) * @param count Limit the length of the returned results array to limit the size of the returned payload (optional, default to 1024) * @param nextToken The next token can be used from a previous page result. It allows to iterating through all the next elements of a collection. If next_token is set, offset and limit will be ignored (optional) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Successful operation </td><td> - </td></tr> <tr><td> 400 </td><td> Parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call readStatusCall(String sessionId, Integer offset, Integer count, String nextToken, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; // Determine Base Path to Use if (localCustomBaseUrl != null){ basePath = localCustomBaseUrl; } else if ( localBasePaths.length > 0 ) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = null; // create path and map variables String localVarPath = "/audio_sessions/{session_id}/status" .replaceAll("\\{" + "session_id" + "\\}", localVarApiClient.escapeString(sessionId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); if (offset != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("offset", offset)); } if (count != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("count", count)); } if (nextToken != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("next_token", nextToken)); } final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { }; return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call readStatusValidateBeforeCall(String sessionId, Integer offset, Integer count, String nextToken, final ApiCallback _callback) throws ApiException { // verify the required parameter 'sessionId' is set if (sessionId == null) { throw new ApiException("Missing the required parameter 'sessionId' when calling readStatus(Async)"); } okhttp3.Call localVarCall = readStatusCall(sessionId, offset, count, nextToken, _callback); return localVarCall; } /** * Read Status * Get session status *Note that if all chunks didn&#39;t finish to be inferenced, the server will wait for at least one result to be available in the required page range before returning result. Such waiting can lead to HTTP requests timeout. Therefore we recommend implementing a client retry logic.* * @param sessionId Session id represents a unique identifier for an audio session (required) * @param offset How many existing elements to skip before returning the first result control how many results to receive (optional, default to 0) * @param count Limit the length of the returned results array to limit the size of the returned payload (optional, default to 1024) * @param nextToken The next token can be used from a previous page result. It allows to iterating through all the next elements of a collection. If next_token is set, offset and limit will be ignored (optional) * @return SessionStatus * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Successful operation </td><td> - </td></tr> <tr><td> 400 </td><td> Parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public SessionStatus readStatus(String sessionId, Integer offset, Integer count, String nextToken) throws ApiException { ApiResponse<SessionStatus> localVarResp = readStatusWithHttpInfo(sessionId, offset, count, nextToken); return localVarResp.getData(); } /** * Read Status * Get session status *Note that if all chunks didn&#39;t finish to be inferenced, the server will wait for at least one result to be available in the required page range before returning result. Such waiting can lead to HTTP requests timeout. Therefore we recommend implementing a client retry logic.* * @param sessionId Session id represents a unique identifier for an audio session (required) * @param offset How many existing elements to skip before returning the first result control how many results to receive (optional, default to 0) * @param count Limit the length of the returned results array to limit the size of the returned payload (optional, default to 1024) * @param nextToken The next token can be used from a previous page result. It allows to iterating through all the next elements of a collection. If next_token is set, offset and limit will be ignored (optional) * @return ApiResponse&lt;SessionStatus&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Successful operation </td><td> - </td></tr> <tr><td> 400 </td><td> Parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public ApiResponse<SessionStatus> readStatusWithHttpInfo(String sessionId, Integer offset, Integer count, String nextToken) throws ApiException { okhttp3.Call localVarCall = readStatusValidateBeforeCall(sessionId, offset, count, nextToken, null); Type localVarReturnType = new TypeToken<SessionStatus>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Read Status (asynchronously) * Get session status *Note that if all chunks didn&#39;t finish to be inferenced, the server will wait for at least one result to be available in the required page range before returning result. Such waiting can lead to HTTP requests timeout. Therefore we recommend implementing a client retry logic.* * @param sessionId Session id represents a unique identifier for an audio session (required) * @param offset How many existing elements to skip before returning the first result control how many results to receive (optional, default to 0) * @param count Limit the length of the returned results array to limit the size of the returned payload (optional, default to 1024) * @param nextToken The next token can be used from a previous page result. It allows to iterating through all the next elements of a collection. If next_token is set, offset and limit will be ignored (optional) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Successful operation </td><td> - </td></tr> <tr><td> 400 </td><td> Parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call readStatusAsync(String sessionId, Integer offset, Integer count, String nextToken, final ApiCallback<SessionStatus> _callback) throws ApiException { okhttp3.Call localVarCall = readStatusValidateBeforeCall(sessionId, offset, count, nextToken, _callback); Type localVarReturnType = new TypeToken<SessionStatus>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for updateSession * @param sessionId Session id represents a unique identifier for an audio session (required) * @param updateSession (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The session has been updated successfully </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call updateSessionCall(String sessionId, UpdateSession updateSession, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; // Determine Base Path to Use if (localCustomBaseUrl != null){ basePath = localCustomBaseUrl; } else if ( localBasePaths.length > 0 ) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = updateSession; // create path and map variables String localVarPath = "/audio_sessions/{session_id}" .replaceAll("\\{" + "session_id" + "\\}", localVarApiClient.escapeString(sessionId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { }; return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call updateSessionValidateBeforeCall(String sessionId, UpdateSession updateSession, final ApiCallback _callback) throws ApiException { // verify the required parameter 'sessionId' is set if (sessionId == null) { throw new ApiException("Missing the required parameter 'sessionId' when calling updateSession(Async)"); } // verify the required parameter 'updateSession' is set if (updateSession == null) { throw new ApiException("Missing the required parameter 'updateSession' when calling updateSession(Async)"); } okhttp3.Call localVarCall = updateSessionCall(sessionId, updateSession, _callback); return localVarCall; } /** * Update Session * Update a session * @param sessionId Session id represents a unique identifier for an audio session (required) * @param updateSession (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The session has been updated successfully </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public void updateSession(String sessionId, UpdateSession updateSession) throws ApiException { updateSessionWithHttpInfo(sessionId, updateSession); } /** * Update Session * Update a session * @param sessionId Session id represents a unique identifier for an audio session (required) * @param updateSession (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The session has been updated successfully </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public ApiResponse<Void> updateSessionWithHttpInfo(String sessionId, UpdateSession updateSession) throws ApiException { okhttp3.Call localVarCall = updateSessionValidateBeforeCall(sessionId, updateSession, null); return localVarApiClient.execute(localVarCall); } /** * Update Session (asynchronously) * Update a session * @param sessionId Session id represents a unique identifier for an audio session (required) * @param updateSession (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The session has been updated successfully </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call updateSessionAsync(String sessionId, UpdateSession updateSession, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = updateSessionValidateBeforeCall(sessionId, updateSession, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for uploadChunk * @param sessionId Session id represents a unique identifier for an audio session (required) * @param chunkSequence Chunk represents the chunk number. This is needed to be a counter starting from 0 and growing by one on each request (required) * @param audioChunk raw binary chunk (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The chunk successfully uploaded </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 403 </td><td> The session is not writable anymore </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 409 </td><td> The chunk sequence is invalid </td><td> - </td></tr> <tr><td> 413 </td><td> Audio chunk size must be smaller than 1MiB </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call uploadChunkCall(String sessionId, Integer chunkSequence, AudioChunk audioChunk, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; // Determine Base Path to Use if (localCustomBaseUrl != null){ basePath = localCustomBaseUrl; } else if ( localBasePaths.length > 0 ) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = audioChunk; // create path and map variables String localVarPath = "/audio_sessions/{session_id}/chunks/{chunk_sequence}" .replaceAll("\\{" + "session_id" + "\\}", localVarApiClient.escapeString(sessionId.toString())) .replaceAll("\\{" + "chunk_sequence" + "\\}", localVarApiClient.escapeString(chunkSequence.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] { }; return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call uploadChunkValidateBeforeCall(String sessionId, Integer chunkSequence, AudioChunk audioChunk, final ApiCallback _callback) throws ApiException { // verify the required parameter 'sessionId' is set if (sessionId == null) { throw new ApiException("Missing the required parameter 'sessionId' when calling uploadChunk(Async)"); } // verify the required parameter 'chunkSequence' is set if (chunkSequence == null) { throw new ApiException("Missing the required parameter 'chunkSequence' when calling uploadChunk(Async)"); } // verify the required parameter 'audioChunk' is set if (audioChunk == null) { throw new ApiException("Missing the required parameter 'audioChunk' when calling uploadChunk(Async)"); } okhttp3.Call localVarCall = uploadChunkCall(sessionId, chunkSequence, audioChunk, _callback); return localVarCall; } /** * Upload Chunk * Upload new audio chunk * @param sessionId Session id represents a unique identifier for an audio session (required) * @param chunkSequence Chunk represents the chunk number. This is needed to be a counter starting from 0 and growing by one on each request (required) * @param audioChunk raw binary chunk (required) * @return SessionRefs * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The chunk successfully uploaded </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 403 </td><td> The session is not writable anymore </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 409 </td><td> The chunk sequence is invalid </td><td> - </td></tr> <tr><td> 413 </td><td> Audio chunk size must be smaller than 1MiB </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public SessionRefs uploadChunk(String sessionId, Integer chunkSequence, AudioChunk audioChunk) throws ApiException { ApiResponse<SessionRefs> localVarResp = uploadChunkWithHttpInfo(sessionId, chunkSequence, audioChunk); return localVarResp.getData(); } /** * Upload Chunk * Upload new audio chunk * @param sessionId Session id represents a unique identifier for an audio session (required) * @param chunkSequence Chunk represents the chunk number. This is needed to be a counter starting from 0 and growing by one on each request (required) * @param audioChunk raw binary chunk (required) * @return ApiResponse&lt;SessionRefs&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The chunk successfully uploaded </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 403 </td><td> The session is not writable anymore </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 409 </td><td> The chunk sequence is invalid </td><td> - </td></tr> <tr><td> 413 </td><td> Audio chunk size must be smaller than 1MiB </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public ApiResponse<SessionRefs> uploadChunkWithHttpInfo(String sessionId, Integer chunkSequence, AudioChunk audioChunk) throws ApiException { okhttp3.Call localVarCall = uploadChunkValidateBeforeCall(sessionId, chunkSequence, audioChunk, null); Type localVarReturnType = new TypeToken<SessionRefs>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Upload Chunk (asynchronously) * Upload new audio chunk * @param sessionId Session id represents a unique identifier for an audio session (required) * @param chunkSequence Chunk represents the chunk number. This is needed to be a counter starting from 0 and growing by one on each request (required) * @param audioChunk raw binary chunk (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The chunk successfully uploaded </td><td> - </td></tr> <tr><td> 400 </td><td> The parameter is missing or not formatted properly </td><td> - </td></tr> <tr><td> 403 </td><td> The session is not writable anymore </td><td> - </td></tr> <tr><td> 404 </td><td> Resources don’t exist or have been deleted </td><td> - </td></tr> <tr><td> 409 </td><td> The chunk sequence is invalid </td><td> - </td></tr> <tr><td> 413 </td><td> Audio chunk size must be smaller than 1MiB </td><td> - </td></tr> <tr><td> 500 </td><td> Unexpected server error. If the error persists, you can contact support@cochl.ai to fix the problem. </td><td> - </td></tr> </table> */ public okhttp3.Call uploadChunkAsync(String sessionId, Integer chunkSequence, AudioChunk audioChunk, final ApiCallback<SessionRefs> _callback) throws ApiException { okhttp3.Call localVarCall = uploadChunkValidateBeforeCall(sessionId, chunkSequence, audioChunk, _callback); Type localVarReturnType = new TypeToken<SessionRefs>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/AudioChunk.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * AudioChunk */ @ApiModel(description = "AudioChunk ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class AudioChunk { public static final String SERIALIZED_NAME_DATA = "data"; @SerializedName(SERIALIZED_NAME_DATA) private String data; public AudioChunk() { } public AudioChunk data(String data) { this.data = data; return this; } /** * Raw audio encoded as base64 * @return data **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "Raw audio encoded as base64 ") public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AudioChunk audioChunk = (AudioChunk) o; return Objects.equals(this.data, audioChunk.data); } @Override public int hashCode() { return Objects.hash(data); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AudioChunk {\n"); sb.append(" data: ").append(toIndentedString(data)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/AudioType.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import io.swagger.annotations.ApiModel; import com.google.gson.annotations.SerializedName; import java.io.IOException; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * Whether the audio that will be sent is a stream or a file */ @JsonAdapter(AudioType.Adapter.class) public enum AudioType { STREAM("stream"), FILE("file"); private String value; AudioType(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static AudioType fromValue(String value) { for (AudioType b : AudioType.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } public static class Adapter extends TypeAdapter<AudioType> { @Override public void write(final JsonWriter jsonWriter, final AudioType enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public AudioType read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return AudioType.fromValue(value); } } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/CreateSession.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import ai.cochl.sense.model.AudioType; import ai.cochl.sense.model.WindowHop; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Options to create a new session. Make sure that specified type and content_type are compatible. [more info](https://docs.cochl.ai/todo) */ @ApiModel(description = "Options to create a new session. Make sure that specified type and content_type are compatible. [more info](https://docs.cochl.ai/todo) ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class CreateSession { public static final String SERIALIZED_NAME_CONTENT_TYPE = "content_type"; @SerializedName(SERIALIZED_NAME_CONTENT_TYPE) private String contentType; public static final String SERIALIZED_NAME_TYPE = "type"; @SerializedName(SERIALIZED_NAME_TYPE) private AudioType type; public static final String SERIALIZED_NAME_METADATAS = "metadatas"; @SerializedName(SERIALIZED_NAME_METADATAS) private Map<String, String> metadatas = null; public static final String SERIALIZED_NAME_TOTAL_SIZE = "total_size"; @SerializedName(SERIALIZED_NAME_TOTAL_SIZE) private Integer totalSize; public static final String SERIALIZED_NAME_TAGS_SENSITIVITY = "tags_sensitivity"; @SerializedName(SERIALIZED_NAME_TAGS_SENSITIVITY) private Map<String, Integer> tagsSensitivity = null; public static final String SERIALIZED_NAME_DEFAULT_SENSITIVITY = "default_sensitivity"; @SerializedName(SERIALIZED_NAME_DEFAULT_SENSITIVITY) private Integer defaultSensitivity = 0; public static final String SERIALIZED_NAME_WINDOW_HOP = "window_hop"; @SerializedName(SERIALIZED_NAME_WINDOW_HOP) private WindowHop windowHop; public CreateSession() { } public CreateSession contentType(String contentType) { this.contentType = contentType; return this; } /** * Type of audio to send. * @return contentType **/ @javax.annotation.Nonnull @ApiModelProperty(example = "audio/x-raw; rate=44100; format=s24le", required = true, value = "Type of audio to send.") public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public CreateSession type(AudioType type) { this.type = type; return this; } /** * Get type * @return type **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "") public AudioType getType() { return type; } public void setType(AudioType type) { this.type = type; } public CreateSession metadatas(Map<String, String> metadatas) { this.metadatas = metadatas; return this; } public CreateSession putMetadatasItem(String key, String metadatasItem) { if (this.metadatas == null) { this.metadatas = new HashMap<>(); } this.metadatas.put(key, metadatasItem); return this; } /** * Type of audio session&#39;s metadatas. Check [metadatas documentation](https://docs.cochl.ai/todo) for an exaustive list of available metadatas * @return metadatas **/ @javax.annotation.Nullable @ApiModelProperty(value = "Type of audio session's metadatas. Check [metadatas documentation](https://docs.cochl.ai/todo) for an exaustive list of available metadatas ") public Map<String, String> getMetadatas() { return metadatas; } public void setMetadatas(Map<String, String> metadatas) { this.metadatas = metadatas; } public CreateSession totalSize(Integer totalSize) { this.totalSize = totalSize; return this; } /** * If set, it allows to automatically change the state of the session to &#x60;readonly&#x60; when at least &#x60;total_size&#x60; bytes of audio chunk has been uploaded. For stream, this can be used to limit the maximum duration of the session. For a file, this allows to automatically start inferencing when the whole file has been sent. We recommend to set the size for files as it allows to do one less API call to start the inferencing * minimum: 1 * @return totalSize **/ @javax.annotation.Nullable @ApiModelProperty(value = "If set, it allows to automatically change the state of the session to `readonly` when at least `total_size` bytes of audio chunk has been uploaded. For stream, this can be used to limit the maximum duration of the session. For a file, this allows to automatically start inferencing when the whole file has been sent. We recommend to set the size for files as it allows to do one less API call to start the inferencing ") public Integer getTotalSize() { return totalSize; } public void setTotalSize(Integer totalSize) { this.totalSize = totalSize; } public CreateSession tagsSensitivity(Map<String, Integer> tagsSensitivity) { this.tagsSensitivity = tagsSensitivity; return this; } public CreateSession putTagsSensitivityItem(String key, Integer tagsSensitivityItem) { if (this.tagsSensitivity == null) { this.tagsSensitivity = new HashMap<>(); } this.tagsSensitivity.put(key, tagsSensitivityItem); return this; } /** * If set, it allows to adjust the sensitivity of a given tag [in this list](https://docs.cochl.ai/sense/tags/) The sensitivity adjustment ranges in [-2,2] A value of 0 preserves the default sensitivity Positive value reduces tag appearance, negative value increases it * @return tagsSensitivity **/ @javax.annotation.Nullable @ApiModelProperty(example = "{\"Siren\":-2,\"Emergency_vehicle_siren\":-1}", value = "If set, it allows to adjust the sensitivity of a given tag [in this list](https://docs.cochl.ai/sense/tags/) The sensitivity adjustment ranges in [-2,2] A value of 0 preserves the default sensitivity Positive value reduces tag appearance, negative value increases it ") public Map<String, Integer> getTagsSensitivity() { return tagsSensitivity; } public void setTagsSensitivity(Map<String, Integer> tagsSensitivity) { this.tagsSensitivity = tagsSensitivity; } public CreateSession defaultSensitivity(Integer defaultSensitivity) { this.defaultSensitivity = defaultSensitivity; return this; } /** * If set, it allows to provide a default adjusted sensitivity for all tags The sensitivity adjustment ranges in [-2,2] 0 is used if not set Positive value reduces tag appearance, negative value increases it * minimum: -2 * maximum: 2 * @return defaultSensitivity **/ @javax.annotation.Nullable @ApiModelProperty(value = "If set, it allows to provide a default adjusted sensitivity for all tags The sensitivity adjustment ranges in [-2,2] 0 is used if not set Positive value reduces tag appearance, negative value increases it ") public Integer getDefaultSensitivity() { return defaultSensitivity; } public void setDefaultSensitivity(Integer defaultSensitivity) { this.defaultSensitivity = defaultSensitivity; } public CreateSession windowHop(WindowHop windowHop) { this.windowHop = windowHop; return this; } /** * Get windowHop * @return windowHop **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public WindowHop getWindowHop() { return windowHop; } public void setWindowHop(WindowHop windowHop) { this.windowHop = windowHop; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateSession createSession = (CreateSession) o; return Objects.equals(this.contentType, createSession.contentType) && Objects.equals(this.type, createSession.type) && Objects.equals(this.metadatas, createSession.metadatas) && Objects.equals(this.totalSize, createSession.totalSize) && Objects.equals(this.tagsSensitivity, createSession.tagsSensitivity) && Objects.equals(this.defaultSensitivity, createSession.defaultSensitivity) && Objects.equals(this.windowHop, createSession.windowHop); } @Override public int hashCode() { return Objects.hash(contentType, type, metadatas, totalSize, tagsSensitivity, defaultSensitivity, windowHop); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CreateSession {\n"); sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" metadatas: ").append(toIndentedString(metadatas)).append("\n"); sb.append(" totalSize: ").append(toIndentedString(totalSize)).append("\n"); sb.append(" tagsSensitivity: ").append(toIndentedString(tagsSensitivity)).append("\n"); sb.append(" defaultSensitivity: ").append(toIndentedString(defaultSensitivity)).append("\n"); sb.append(" windowHop: ").append(toIndentedString(windowHop)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/GenericError.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Error is sent when an error happens */ @ApiModel(description = "Error is sent when an error happens ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class GenericError { public static final String SERIALIZED_NAME_STATUS_CODE = "status_code"; @SerializedName(SERIALIZED_NAME_STATUS_CODE) private Integer statusCode; public static final String SERIALIZED_NAME_ERROR = "error"; @SerializedName(SERIALIZED_NAME_ERROR) private String error; public GenericError() { } public GenericError statusCode(Integer statusCode) { this.statusCode = statusCode; return this; } /** * HTTP status code returned * @return statusCode **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "HTTP status code returned ") public Integer getStatusCode() { return statusCode; } public void setStatusCode(Integer statusCode) { this.statusCode = statusCode; } public GenericError error(String error) { this.error = error; return this; } /** * Human-readable description of the error. *Note that the value should not be used programmatically as the description might be changed at any moment* * @return error **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "Human-readable description of the error. *Note that the value should not be used programmatically as the description might be changed at any moment* ") public String getError() { return error; } public void setError(String error) { this.error = error; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GenericError genericError = (GenericError) o; return Objects.equals(this.statusCode, genericError.statusCode) && Objects.equals(this.error, genericError.error); } @Override public int hashCode() { return Objects.hash(statusCode, error); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class GenericError {\n"); sb.append(" statusCode: ").append(toIndentedString(statusCode)).append("\n"); sb.append(" error: ").append(toIndentedString(error)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/Page.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Contains the range of elements that have been returned for a given collection */ @ApiModel(description = "Contains the range of elements that have been returned for a given collection ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class Page { public static final String SERIALIZED_NAME_OFFSET = "offset"; @SerializedName(SERIALIZED_NAME_OFFSET) private Integer offset; public static final String SERIALIZED_NAME_COUNT = "count"; @SerializedName(SERIALIZED_NAME_COUNT) private Integer count; public static final String SERIALIZED_NAME_TOTAL = "total"; @SerializedName(SERIALIZED_NAME_TOTAL) private Integer total; public static final String SERIALIZED_NAME_NEXT_TOKEN = "next_token"; @SerializedName(SERIALIZED_NAME_NEXT_TOKEN) private String nextToken; public Page() { } public Page offset(Integer offset) { this.offset = offset; return this; } /** * Index of the first return element * minimum: 0 * @return offset **/ @javax.annotation.Nonnull @ApiModelProperty(example = "2048", required = true, value = "Index of the first return element ") public Integer getOffset() { return offset; } public void setOffset(Integer offset) { this.offset = offset; } public Page count(Integer count) { this.count = count; return this; } /** * The number of elements that have been returned * minimum: 0 * maximum: 1024 * @return count **/ @javax.annotation.Nonnull @ApiModelProperty(example = "1024", required = true, value = "The number of elements that have been returned ") public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public Page total(Integer total) { this.total = total; return this; } /** * The total number of available elements in the collection at the moment * minimum: 0 * @return total **/ @javax.annotation.Nonnull @ApiModelProperty(example = "4096", required = true, value = "The total number of available elements in the collection at the moment ") public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public Page nextToken(String nextToken) { this.nextToken = nextToken; return this; } /** * The next token can be used in the next page request to get the following results. If not present, it means that the page has reached the end of the collection * @return nextToken **/ @javax.annotation.Nullable @ApiModelProperty(value = "The next token can be used in the next page request to get the following results. If not present, it means that the page has reached the end of the collection ") public String getNextToken() { return nextToken; } public void setNextToken(String nextToken) { this.nextToken = nextToken; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Page page = (Page) o; return Objects.equals(this.offset, page.offset) && Objects.equals(this.count, page.count) && Objects.equals(this.total, page.total) && Objects.equals(this.nextToken, page.nextToken); } @Override public int hashCode() { return Objects.hash(offset, count, total, nextToken); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Page {\n"); sb.append(" offset: ").append(toIndentedString(offset)).append("\n"); sb.append(" count: ").append(toIndentedString(count)).append("\n"); sb.append(" total: ").append(toIndentedString(total)).append("\n"); sb.append(" nextToken: ").append(toIndentedString(nextToken)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/Sense.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import ai.cochl.sense.model.Page; import ai.cochl.sense.model.SenseEvent; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Inference related status */ @ApiModel(description = "Inference related status ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class Sense { public static final String SERIALIZED_NAME_IN_PROGRESS = "in_progress"; @SerializedName(SERIALIZED_NAME_IN_PROGRESS) private Boolean inProgress; public static final String SERIALIZED_NAME_PAGE = "page"; @SerializedName(SERIALIZED_NAME_PAGE) private Page page; public static final String SERIALIZED_NAME_RESULTS = "results"; @SerializedName(SERIALIZED_NAME_RESULTS) private List<SenseEvent> results = null; public Sense() { } public Sense inProgress(Boolean inProgress) { this.inProgress = inProgress; return this; } /** * Is true when there are still some pending chunks that were uploaded but are not inferenced yet * @return inProgress **/ @javax.annotation.Nullable @ApiModelProperty(value = "Is true when there are still some pending chunks that were uploaded but are not inferenced yet ") public Boolean getInProgress() { return inProgress; } public void setInProgress(Boolean inProgress) { this.inProgress = inProgress; } public Sense page(Page page) { this.page = page; return this; } /** * Get page * @return page **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Page getPage() { return page; } public void setPage(Page page) { this.page = page; } public Sense results(List<SenseEvent> results) { this.results = results; return this; } public Sense addResultsItem(SenseEvent resultsItem) { if (this.results == null) { this.results = new ArrayList<>(); } this.results.add(resultsItem); return this; } /** * Contains paginated results of what has been inferenced so far * @return results **/ @javax.annotation.Nullable @ApiModelProperty(value = "Contains paginated results of what has been inferenced so far ") public List<SenseEvent> getResults() { return results; } public void setResults(List<SenseEvent> results) { this.results = results; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Sense sense = (Sense) o; return Objects.equals(this.inProgress, sense.inProgress) && Objects.equals(this.page, sense.page) && Objects.equals(this.results, sense.results); } @Override public int hashCode() { return Objects.hash(inProgress, page, results); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Sense {\n"); sb.append(" inProgress: ").append(toIndentedString(inProgress)).append("\n"); sb.append(" page: ").append(toIndentedString(page)).append("\n"); sb.append(" results: ").append(toIndentedString(results)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/SenseEvent.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import ai.cochl.sense.model.SenseEventTag; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Contains data returned by the model */ @ApiModel(description = "Contains data returned by the model ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class SenseEvent { public static final String SERIALIZED_NAME_TAGS = "tags"; @SerializedName(SERIALIZED_NAME_TAGS) private List<SenseEventTag> tags = new ArrayList<>(); public static final String SERIALIZED_NAME_START_TIME = "start_time"; @SerializedName(SERIALIZED_NAME_START_TIME) private Double startTime; public static final String SERIALIZED_NAME_END_TIME = "end_time"; @SerializedName(SERIALIZED_NAME_END_TIME) private Double endTime; public SenseEvent() { } public SenseEvent tags(List<SenseEventTag> tags) { this.tags = tags; return this; } public SenseEvent addTagsItem(SenseEventTag tagsItem) { this.tags.add(tagsItem); return this; } /** * Contains results of what has been inferenced at the same time * @return tags **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "Contains results of what has been inferenced at the same time ") public List<SenseEventTag> getTags() { return tags; } public void setTags(List<SenseEventTag> tags) { this.tags = tags; } public SenseEvent startTime(Double startTime) { this.startTime = startTime; return this; } /** * Represent the start of the window, in the second, where inference was done. *Note that start_time will increase by window_hop on every step* * @return startTime **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "Represent the start of the window, in the second, where inference was done. *Note that start_time will increase by window_hop on every step* ") public Double getStartTime() { return startTime; } public void setStartTime(Double startTime) { this.startTime = startTime; } public SenseEvent endTime(Double endTime) { this.endTime = endTime; return this; } /** * Represent the end of the window, in the second where inference was done. *Note that end_time is window_length after start_time* * @return endTime **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "Represent the end of the window, in the second where inference was done. *Note that end_time is window_length after start_time* ") public Double getEndTime() { return endTime; } public void setEndTime(Double endTime) { this.endTime = endTime; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SenseEvent senseEvent = (SenseEvent) o; return Objects.equals(this.tags, senseEvent.tags) && Objects.equals(this.startTime, senseEvent.startTime) && Objects.equals(this.endTime, senseEvent.endTime); } @Override public int hashCode() { return Objects.hash(tags, startTime, endTime); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SenseEvent {\n"); sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); sb.append(" startTime: ").append(toIndentedString(startTime)).append("\n"); sb.append(" endTime: ").append(toIndentedString(endTime)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/SenseEventTag.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Contains data of the sound recognized by the model */ @ApiModel(description = "Contains data of the sound recognized by the model ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class SenseEventTag { public static final String SERIALIZED_NAME_PROBABILITY = "probability"; @SerializedName(SERIALIZED_NAME_PROBABILITY) private Double probability; public static final String SERIALIZED_NAME_NAME = "name"; @SerializedName(SERIALIZED_NAME_NAME) private String name; public SenseEventTag() { } public SenseEventTag probability(Double probability) { this.probability = probability; return this; } /** * Probability that the event occurred. 0. means not possible at all and 1. means that it is certain * minimum: 0 * maximum: 1 * @return probability **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "Probability that the event occurred. 0. means not possible at all and 1. means that it is certain ") public Double getProbability() { return probability; } public void setProbability(Double probability) { this.probability = probability; } public SenseEventTag name(String name) { this.name = name; return this; } /** * Name of the sound recognized during the inference. * @return name **/ @javax.annotation.Nonnull @ApiModelProperty(example = "Knock", required = true, value = "Name of the sound recognized during the inference. ") public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SenseEventTag senseEventTag = (SenseEventTag) o; return Objects.equals(this.probability, senseEventTag.probability) && Objects.equals(this.name, senseEventTag.name); } @Override public int hashCode() { return Objects.hash(probability, name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SenseEventTag {\n"); sb.append(" probability: ").append(toIndentedString(probability)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/SessionRefs.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * List of session links */ @ApiModel(description = "List of session links ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class SessionRefs { public static final String SERIALIZED_NAME_SESSION_ID = "session_id"; @SerializedName(SERIALIZED_NAME_SESSION_ID) private String sessionId; public static final String SERIALIZED_NAME_CHUNK_SEQUENCE = "chunk_sequence"; @SerializedName(SERIALIZED_NAME_CHUNK_SEQUENCE) private Integer chunkSequence; public SessionRefs() { } public SessionRefs sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Session id of the session that can be used to interact with API * @return sessionId **/ @javax.annotation.Nonnull @ApiModelProperty(example = "5vlv0r6SBUPYaUju1PFFalGhGVcyg", required = true, value = "Session id of the session that can be used to interact with API ") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public SessionRefs chunkSequence(Integer chunkSequence) { this.chunkSequence = chunkSequence; return this; } /** * Chunk is uploaded in sequence. This represents the sequence of the next chunk to upload * @return chunkSequence **/ @javax.annotation.Nonnull @ApiModelProperty(example = "0", required = true, value = "Chunk is uploaded in sequence. This represents the sequence of the next chunk to upload ") public Integer getChunkSequence() { return chunkSequence; } public void setChunkSequence(Integer chunkSequence) { this.chunkSequence = chunkSequence; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SessionRefs sessionRefs = (SessionRefs) o; return Objects.equals(this.sessionId, sessionRefs.sessionId) && Objects.equals(this.chunkSequence, sessionRefs.chunkSequence); } @Override public int hashCode() { return Objects.hash(sessionId, chunkSequence); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SessionRefs {\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" chunkSequence: ").append(toIndentedString(chunkSequence)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/SessionStatus.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import ai.cochl.sense.model.Sense; import ai.cochl.sense.model.SessionRefs; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Contains all the data for the product Cochl.Sense */ @ApiModel(description = "Contains all the data for the product Cochl.Sense ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class SessionStatus { /** * State in which the session is */ @JsonAdapter(StateEnum.Adapter.class) public enum StateEnum { WRITABLE("writable"), READONLY("readonly"); private String value; StateEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static StateEnum fromValue(String value) { for (StateEnum b : StateEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } public static class Adapter extends TypeAdapter<StateEnum> { @Override public void write(final JsonWriter jsonWriter, final StateEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public StateEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return StateEnum.fromValue(value); } } } public static final String SERIALIZED_NAME_STATE = "state"; @SerializedName(SERIALIZED_NAME_STATE) private StateEnum state; public static final String SERIALIZED_NAME_ERROR = "error"; @SerializedName(SERIALIZED_NAME_ERROR) private String error; public static final String SERIALIZED_NAME_REFS = "refs"; @SerializedName(SERIALIZED_NAME_REFS) private SessionRefs refs; public static final String SERIALIZED_NAME_INFERENCE = "inference"; @SerializedName(SERIALIZED_NAME_INFERENCE) private Sense inference; public SessionStatus() { } public SessionStatus state(StateEnum state) { this.state = state; return this; } /** * State in which the session is * @return state **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "State in which the session is ") public StateEnum getState() { return state; } public void setState(StateEnum state) { this.state = state; } public SessionStatus error(String error) { this.error = error; return this; } /** * An error occurred during the session * @return error **/ @javax.annotation.Nullable @ApiModelProperty(value = "An error occurred during the session ") public String getError() { return error; } public void setError(String error) { this.error = error; } public SessionStatus refs(SessionRefs refs) { this.refs = refs; return this; } /** * Get refs * @return refs **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "") public SessionRefs getRefs() { return refs; } public void setRefs(SessionRefs refs) { this.refs = refs; } public SessionStatus inference(Sense inference) { this.inference = inference; return this; } /** * Get inference * @return inference **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "") public Sense getInference() { return inference; } public void setInference(Sense inference) { this.inference = inference; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SessionStatus sessionStatus = (SessionStatus) o; return Objects.equals(this.state, sessionStatus.state) && Objects.equals(this.error, sessionStatus.error) && Objects.equals(this.refs, sessionStatus.refs) && Objects.equals(this.inference, sessionStatus.inference); } @Override public int hashCode() { return Objects.hash(state, error, refs, inference); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SessionStatus {\n"); sb.append(" state: ").append(toIndentedString(state)).append("\n"); sb.append(" error: ").append(toIndentedString(error)).append("\n"); sb.append(" refs: ").append(toIndentedString(refs)).append("\n"); sb.append(" inference: ").append(toIndentedString(inference)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/UpdateSession.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * modify session state */ @ApiModel(description = "modify session state ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class UpdateSession { public static final String SERIALIZED_NAME_MAKE_READONLY = "make_readonly"; @SerializedName(SERIALIZED_NAME_MAKE_READONLY) private Boolean makeReadonly; public UpdateSession() { } public UpdateSession makeReadonly(Boolean makeReadonly) { this.makeReadonly = makeReadonly; return this; } /** * If set to true, will set session state to readonly *Note that setting make_readonly to false once the session is readonly will not make the session writable again* * @return makeReadonly **/ @javax.annotation.Nullable @ApiModelProperty(value = "If set to true, will set session state to readonly *Note that setting make_readonly to false once the session is readonly will not make the session writable again* ") public Boolean getMakeReadonly() { return makeReadonly; } public void setMakeReadonly(Boolean makeReadonly) { this.makeReadonly = makeReadonly; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdateSession updateSession = (UpdateSession) o; return Objects.equals(this.makeReadonly, updateSession.makeReadonly); } @Override public int hashCode() { return Objects.hash(makeReadonly); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UpdateSession {\n"); sb.append(" makeReadonly: ").append(toIndentedString(makeReadonly)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense
java-sources/ai/cochl/sense-api/v1.4.0/ai/cochl/sense/model/WindowHop.java
/* * Cochl.Sense API * Cochl.Sense API allows to detect what is contained inside sound data. Send audio data over the internet to discover what it contains. ``` npx @openapitools/openapi-generator-cli generate -i openapi.json -g python -o python-client ``` * * The version of the OpenAPI document: v1.4.0 * Contact: support@cochl.ai * * 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.cochl.sense.model; import java.util.Objects; import java.util.Arrays; import io.swagger.annotations.ApiModel; import com.google.gson.annotations.SerializedName; import java.io.IOException; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * If set, it allows to adjust the sensitivity of a given tag [in this list] The window hop adjustment can be set eith to 0.5s or 1s By default, this value is set to 0.5s */ @JsonAdapter(WindowHop.Adapter.class) public enum WindowHop { _0_5S("0.5s"), _1S("1s"); private String value; WindowHop(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static WindowHop fromValue(String value) { for (WindowHop b : WindowHop.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } public static class Adapter extends TypeAdapter<WindowHop> { @Override public void write(final JsonWriter jsonWriter, final WindowHop enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public WindowHop read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return WindowHop.fromValue(value); } } }
0
java-sources/ai/connectif/sdk/1.1.0/ai/connectif
java-sources/ai/connectif/sdk/1.1.0/ai/connectif/sdk/BuildConfig.java
/** * Automatically generated file. DO NOT MODIFY */ package ai.connectif.sdk; public final class BuildConfig { public static final boolean DEBUG = false; public static final String LIBRARY_PACKAGE_NAME = "ai.connectif.sdk"; public static final String BUILD_TYPE = "release"; // Field from build type: release public static final String CONNECTIF_ENDPOINT = "https://mobile-app-api.connectif.cloud/"; // Field from build type: release public static final boolean DEV_LOG_ENABLED = false; // Field from default config. public static final int SDK_VERSION_CODE = 4; // Field from default config. public static final String SDK_VERSION_NAME = "1.1.0"; }
0
java-sources/ai/corva/otel/semconv/1.1.4/ai/corva/otel
java-sources/ai/corva/otel/semconv/1.1.4/ai/corva/otel/semconv/CorvaSemattrs.java
package ai.corva.otel.semconv; import io.opentelemetry.api.common.AttributeKey; import static io.opentelemetry.api.common.AttributeKey.*; /** * Corva Semantic Attributes * * Common names for different kinds of operations and data. * OpenTelemetry defines Semantic Conventions (sometimes called Semantic Attributes) that specify common names for different kinds of operations and data. The benefit of using Semantic Conventions is in following a common naming scheme that can be standardized across a codebase, libraries, and platforms. * * see https://opentelemetry.io/docs/concepts/semantic-conventions/ * see https://github.com/open-telemetry/opentelemetry-specification/blob/v1.26.0/specification/semantic-conventions.md */ public class CorvaSemattrs { /** * Corva Asset ID */ public static final AttributeKey<Long> CORVA_ASSET_ID = longKey("corva.asset.id"); /** * Corva Asset Type one of [`Rig`, `Well`, `Program`] */ public static final AttributeKey<String> CORVA_ASSET_TYPE = stringKey("corva.asset.type"); /** * Corva Application ID * @deprecated The Application ID is not portable through environments, use the #CORVA_APP_KEY instead */ @Deprecated public static final AttributeKey<Long> CORVA_APP_ID = longKey("corva.app.id"); /** * Corva Application Key */ public static final AttributeKey<String> CORVA_APP_KEY = stringKey("corva.app.key"); /** * Corva Application Type one of [`data_app`, `ui_app`] * Optional */ public static final AttributeKey<String> CORVA_APP_VERSION = stringKey("corva.app.version"); /** * Corva Application Version */ public static final AttributeKey<String> CORVA_APP_TYPE = stringKey("corva.app.type"); /** * Corva Application Name */ public static final AttributeKey<String> CORVA_APP_NAME = stringKey("corva.app.name"); /** * Corva Application Connection ID is the ID of a given Application within a Stream * Not very useful, prefer providing `CORVA_APP_STREAM_ID` as well * Optional */ public static final AttributeKey<Long> CORVA_APP_CONNECTION_ID = longKey("corva.app.connection.id"); /** * Corva Application Stream ID is a given graph of applications connections, handling given set of data as sa stream */ public static final AttributeKey<Long> CORVA_APP_STREAM_ID = longKey("corva.app.stream.id"); /** * Corva Task ID */ public static final AttributeKey<String> CORVA_TASK_ID = stringKey("corva.task.id"); /** * Corva Is Partial Well Rerun Merge mode * Experimental */ public static final AttributeKey<Boolean> CORVA_IS_PARTIAL_WELL_RERUN_MERGE = booleanKey("corva.is.partial.well.rerun.merge"); /** * Corva Company ID in which context the application is invoked, or is owning the relevant resource */ public static final AttributeKey<Long> CORVA_COMPANY_ID = longKey("corva.company.id"); /** * Corva Application Provider e.g. `corva` * Optional */ public static final AttributeKey<String> CORVA_APP_PROVIDER = stringKey("corva.app.provider"); /** * Invoked Application ID * Optional * @see #CORVA_APP_ID */ public static final AttributeKey<Long> CORVA_INVOKE_APP_ID = longKey("corva.invoke.app.id"); /** * Invoked Application Key * Optional * @see #CORVA_APP_KEY */ public static final AttributeKey<String> CORVA_INVOKE_APP_KEY = stringKey("corva.invoke.app.key"); /** * Invoked Application Version * Optional * @see #CORVA_APP_VERSION */ public static final AttributeKey<String> CORVA_INVOKE_APP_VERSION = stringKey("corva.invoke.app.version"); /** * Invoked Application Type * Optional * @see #CORVA_APP_TYPE */ public static final AttributeKey<String> CORVA_INVOKE_APP_TYPE = stringKey("corva.invoke.app.type"); /** * Invoked Application Name * Optional * @see #CORVA_APP_NAME */ public static final AttributeKey<String> CORVA_INVOKE_APP_NAME = stringKey("corva.invoke.app.name"); }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/ApiHelper.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api; import io.apimatic.core.utilities.CoreHelper; /** * This is a Helper class with commonly used utilities for the SDK. */ public class ApiHelper extends CoreHelper { }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/AuthorizationCodeAuth.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api; import ai.cuadra.api.exceptions.ApiException; import ai.cuadra.api.models.OauthToken; import java.io.IOException; import java.util.Map; import java.util.concurrent.CompletableFuture; /** * Interface for Authorization Code OAuth 2. */ public interface AuthorizationCodeAuth { /** * String value for oauthClientId. * @return oauthClientId */ String getOauthClientId(); /** * String value for oauthClientSecret. * @return oauthClientSecret */ String getOauthClientSecret(); /** * String value for oauthRedirectUri. * @return oauthRedirectUri */ String getOauthRedirectUri(); /** * OauthToken value for oauthToken. * @return oauthToken */ OauthToken getOauthToken(); /** * Checks if provided credentials matched with existing ones. * @param oauthClientId String value for credentials. * @param oauthClientSecret String value for credentials. * @param oauthRedirectUri String value for credentials. * @param oauthToken OauthToken value for credentials. * @return true if credentials matched. */ boolean equals(String oauthClientId, String oauthClientSecret, String oauthRedirectUri, OauthToken oauthToken); /** * Build an authorization URL for taking the user's consent to access data. * @param state An opaque state string. * @param additionalParameters Additional parameters to add the the authorization URL. * @return Authorization URL */ String buildAuthorizationUrl(final String state, final Map<String, String> additionalParameters); /** * Build an authorization URL for taking the user's consent to access data. * @return Authorization URL */ String buildAuthorizationUrl(); /** * Build an authorization URL for taking the user's consent to access data. * @param state An opaque state string. * @return Authorization URL */ String buildAuthorizationUrl(final String state); /** * Fetch the OAuth token asynchronously. * @param authorizationCode Authorization code returned by the OAuth provider. * @param additionalParameters Additional parameters to send during authorization. */ CompletableFuture<OauthToken> fetchTokenAsync(final String authorizationCode, final Map<String, Object> additionalParameters); /** * Fetch the OAuth token asynchronously. * @param authorizationCode Authorization code returned by the OAuth provider. */ CompletableFuture<OauthToken> fetchTokenAsync(final String authorizationCode); /** * Fetch the OAuth token. * @param authorizationCode Authorization code returned by the OAuth provider. * @param additionalParameters Additional parameters to send during authorization. */ OauthToken fetchToken(String authorizationCode, Map<String, Object> additionalParameters) throws ApiException, IOException; /** * Fetch the OAuth token. * @param authorizationCode Authorization code returned by the OAuth provider */ OauthToken fetchToken(String authorizationCode) throws ApiException, IOException; /** * Refresh the OAuth token. * @param additionalParameters Additional parameters to send during token refresh. */ CompletableFuture<OauthToken> refreshTokenAsync(final Map<String, Object> additionalParameters); /** * Refresh the OAuth token. */ CompletableFuture<OauthToken> refreshTokenAsync(); /** * Refresh the OAuth token. * @param additionalParameters Additional parameters to send during token refresh. */ OauthToken refreshToken(final Map<String, Object> additionalParameters) throws ApiException, IOException; /** * Refresh the OAuth token. */ OauthToken refreshToken() throws ApiException, IOException; /** * Has the OAuth token expired?. * @return True if expired */ boolean isTokenExpired(); }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/CompatibilityFactoryImpl.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api; import ai.cuadra.api.http.Headers; import ai.cuadra.api.http.client.HttpContext; import ai.cuadra.api.http.request.HttpBodyRequest; import ai.cuadra.api.http.request.HttpMethod; import ai.cuadra.api.http.request.HttpRequest; import ai.cuadra.api.http.response.ApiResponse; import ai.cuadra.api.http.response.HttpResponse; import ai.cuadra.api.http.response.HttpStringResponse; import io.apimatic.coreinterfaces.compatibility.CompatibilityFactory; import io.apimatic.coreinterfaces.http.Context; import io.apimatic.coreinterfaces.http.HttpHeaders; import io.apimatic.coreinterfaces.http.Method; import io.apimatic.coreinterfaces.http.request.Request; import io.apimatic.coreinterfaces.http.response.ApiResponseType; import io.apimatic.coreinterfaces.http.response.DynamicType; import io.apimatic.coreinterfaces.http.response.Response; import java.io.InputStream; import java.util.AbstractMap.SimpleEntry; import java.util.List; import java.util.Map; public class CompatibilityFactoryImpl implements CompatibilityFactory { @Override public Context createHttpContext(Request request, Response response) { return new HttpContext((HttpRequest) request, (HttpResponse) response); } @Override public Request createHttpRequest(Method httpMethod, StringBuilder queryUrlBuilder, HttpHeaders headers, Map<String, Object> queryParameters, List<SimpleEntry<String, Object>> formParameters) { return new HttpRequest(HttpMethod.valueOf(httpMethod.toString()), queryUrlBuilder, (Headers) headers, queryParameters, formParameters); } @Override public Request createHttpRequest(Method httpMethod, StringBuilder queryUrlBuilder, HttpHeaders headers, Map<String, Object> queryParameters, Object body) { return new HttpBodyRequest(HttpMethod.valueOf(httpMethod.toString()), queryUrlBuilder, (Headers) headers, queryParameters, body); } @Override public Response createHttpResponse(int code, HttpHeaders headers, InputStream rawBody) { return new HttpResponse(code, (Headers) headers, rawBody); } @Override public Response createHttpResponse(int code, HttpHeaders headers, InputStream rawBody, String body) { return new HttpStringResponse(code, (Headers) headers, rawBody, body); } @Override public HttpHeaders createHttpHeaders(Map<String, List<String>> headers) { return new Headers(headers); } @Override public HttpHeaders createHttpHeaders(HttpHeaders headers) { return new Headers((Headers) headers); } @Override public HttpHeaders createHttpHeaders() { return new Headers(); } @Override public DynamicType createDynamicResponse(Response httpResponse) { return null; } @Override public <T> ApiResponseType<T> createApiResponse(int statusCode, HttpHeaders headers, T result) { return new ApiResponse<T>(statusCode, (Headers) headers, result); } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/Configuration.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api; import ai.cuadra.api.authentication.AuthorizationCodeAuthModel; import ai.cuadra.api.http.client.ReadonlyHttpClientConfiguration; import ai.cuadra.api.logging.configuration.ReadonlyLoggingConfiguration; /** * Configuration Interface for the library. */ public interface Configuration { /** * Current API environment. * @return a copy of environment */ Environment getEnvironment(); /** * Http Client Configuration instance. * @return a copy of httpClientConfig */ ReadonlyHttpClientConfiguration getHttpClientConfig(); /** * Logging Configuration instance. * @return a copy of loggingConfig */ ReadonlyLoggingConfiguration getLoggingConfig(); /** * The timeout to use for making HTTP requests. The timeout to use for making HTTP requests. * @return a copy of timeout */ long timeout(); /** * The credentials to use with AuthorizationCodeAuth. * @return authorizationCodeAuth */ AuthorizationCodeAuth getAuthorizationCodeAuth(); /** * The auth credential model for AuthorizationCodeAuth. * @return the instance of AuthorizationCodeAuthModel */ AuthorizationCodeAuthModel getAuthorizationCodeAuthModel(); /** * Get base URI by current environment. * @param server Server for which to get the base URI * @return Processed base URI */ String getBaseUri(Server server); /** * Get base URI by current environment. * @return Processed base URI */ String getBaseUri(); }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/CuadraAiClient.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api; import ai.cuadra.api.authentication.AuthorizationCodeAuthManager; import ai.cuadra.api.authentication.AuthorizationCodeAuthModel; import ai.cuadra.api.controllers.ChatController; import ai.cuadra.api.controllers.EmbedsController; import ai.cuadra.api.controllers.ModelsController; import ai.cuadra.api.controllers.OauthAuthorizationController; import ai.cuadra.api.controllers.UsageController; import ai.cuadra.api.http.client.HttpCallback; import ai.cuadra.api.http.client.HttpClientConfiguration; import ai.cuadra.api.http.client.ReadonlyHttpClientConfiguration; import ai.cuadra.api.logging.configuration.ApiLoggingConfiguration; import ai.cuadra.api.logging.configuration.ReadonlyLoggingConfiguration; import io.apimatic.core.GlobalConfiguration; import io.apimatic.coreinterfaces.authentication.Authentication; import io.apimatic.coreinterfaces.compatibility.CompatibilityFactory; import io.apimatic.coreinterfaces.http.HttpClient; import io.apimatic.okhttpclient.adapter.OkClient; import java.util.AbstractMap.SimpleEntry; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; /** * Gateway class for the library. * This class acts as a factory for Controllers. * It holds the state of the SDK. */ public final class CuadraAiClient implements Configuration { /** * Private store for controllers. */ private ChatController chat; private ModelsController models; private EmbedsController embeds; private UsageController usage; private OauthAuthorizationController oauthAuthorization; private static final CompatibilityFactory compatibilityFactory = new CompatibilityFactoryImpl(); private static String userAgent = "Java-SDK/1.0.4 [OS: {os-info}, Engine: {engine}/{engine-version}]"; /** * Current API environment. */ private final Environment environment; /** * The HTTP Client instance to use for making HTTP requests. */ private final HttpClient httpClient; /** * Http Client Configuration instance. */ private final ReadonlyHttpClientConfiguration httpClientConfig; /** * Logging Configuration instance. */ private final ReadonlyLoggingConfiguration loggingConfig; /** * AuthorizationCodeAuthManager. */ private AuthorizationCodeAuthManager authorizationCodeAuthManager; /** * The instance of AuthorizationCodeAuthModel. */ private AuthorizationCodeAuthModel authorizationCodeAuthModel; /** * Map of authentication Managers. */ private Map<String, Authentication> authentications = new HashMap<String, Authentication>(); /** * Callback to be called before and after the HTTP call for an endpoint is made. */ private final HttpCallback httpCallback; private CuadraAiClient(Environment environment, HttpClient httpClient, ReadonlyHttpClientConfiguration httpClientConfig, ReadonlyLoggingConfiguration loggingConfig, AuthorizationCodeAuthModel authorizationCodeAuthModel, HttpCallback httpCallback) { this.environment = environment; this.httpClient = httpClient; this.httpClientConfig = httpClientConfig; this.loggingConfig = loggingConfig; this.httpCallback = httpCallback; this.authorizationCodeAuthModel = authorizationCodeAuthModel; this.authorizationCodeAuthManager = new AuthorizationCodeAuthManager( authorizationCodeAuthModel); this.authentications.put("OAuth2", authorizationCodeAuthManager); GlobalConfiguration globalConfig = new GlobalConfiguration.Builder() .httpClient(httpClient).baseUri(server -> getBaseUri(server)) .compatibilityFactory(compatibilityFactory) .authentication(this.authentications) .callback(httpCallback) .userAgent(userAgent) .loggingConfiguration(((ApiLoggingConfiguration) loggingConfig).getConfiguration()) .build(); this.authorizationCodeAuthManager.applyGlobalConfiguration(globalConfig); chat = new ChatController(globalConfig); models = new ModelsController(globalConfig); embeds = new EmbedsController(globalConfig); usage = new UsageController(globalConfig); oauthAuthorization = new OauthAuthorizationController(globalConfig); } /** * Shutdown the underlying HttpClient instance. */ public static void shutdown() { OkClient.shutdown(); } /** * Get the instance of ChatController. * @return chat */ public ChatController getChatController() { return chat; } /** * Get the instance of ModelsController. * @return models */ public ModelsController getModelsController() { return models; } /** * Get the instance of EmbedsController. * @return embeds */ public EmbedsController getEmbedsController() { return embeds; } /** * Get the instance of UsageController. * @return usage */ public UsageController getUsageController() { return usage; } /** * Get the instance of OauthAuthorizationController. * @return oauthAuthorization */ public OauthAuthorizationController getOauthAuthorizationController() { return oauthAuthorization; } /** * Current API environment. * @return environment */ public Environment getEnvironment() { return environment; } /** * The HTTP Client instance to use for making HTTP requests. * @return httpClient */ private HttpClient getHttpClient() { return httpClient; } /** * Http Client Configuration instance. * @return httpClientConfig */ public ReadonlyHttpClientConfiguration getHttpClientConfig() { return httpClientConfig; } /** * Logging Configuration instance. * @return loggingConfig */ public ReadonlyLoggingConfiguration getLoggingConfig() { return loggingConfig; } /** * The credentials to use with AuthorizationCodeAuth. * @return authorizationCodeAuth */ public AuthorizationCodeAuth getAuthorizationCodeAuth() { return authorizationCodeAuthManager; } /** * The auth credential model for AuthorizationCodeAuth. * @return the instance of AuthorizationCodeAuthModel */ public AuthorizationCodeAuthModel getAuthorizationCodeAuthModel() { return authorizationCodeAuthModel; } /** * The timeout to use for making HTTP requests. * @deprecated This method will be removed in a future version. Use * {@link #getHttpClientConfig()} instead. * * @return timeout */ @Deprecated public long timeout() { return httpClientConfig.getTimeout(); } /** * Get base URI by current environment. * @param server Server for which to get the base URI * @return Processed base URI */ public String getBaseUri(Server server) { Map<String, SimpleEntry<Object, Boolean>> parameters = new HashMap<>(); StringBuilder baseUrl = new StringBuilder(environmentMapper(environment, server)); ApiHelper.appendUrlWithTemplateParameters(baseUrl, parameters); return baseUrl.toString(); } /** * Get base URI by current environment. * @return Processed base URI */ public String getBaseUri() { return getBaseUri(Server.ENUM_DEFAULT); } /** * Get base URI by current environment. * * @param server string for which to get the base URI * @return Processed base URI */ public String getBaseUri(String server) { return getBaseUri(Server.fromString(server)); } /** * Base URLs by environment and server aliases. * @param environment Environment for which to get the base URI * @param server Server for which to get the base URI * @return base URL */ private static String environmentMapper(Environment environment, Server server) { if (environment.equals(Environment.PRODUCTION)) { if (server.equals(Server.ENUM_DEFAULT)) { return "https://api.cuadra.ai"; } if (server.equals(Server.AUTH_SERVER)) { return "https://dguxglyyavnhlugtecgi.supabase.co/auth/v1"; } } return "https://api.cuadra.ai"; } /** * Converts this CuadraAiClient into string format. * @return String representation of this class */ @Override public String toString() { return "CuadraAiClient [" + "environment=" + environment + ", httpClientConfig=" + httpClientConfig + ", loggingConfig=" + loggingConfig + ", authentications=" + authentications + "]"; } /** * Builds a new {@link CuadraAiClient.Builder} object. * Creates the instance with the state of the current client. * @return a new {@link CuadraAiClient.Builder} object */ public Builder newBuilder() { Builder builder = new Builder(); builder.environment = getEnvironment(); builder.httpClient = getHttpClient(); builder.authorizationCodeAuth(getAuthorizationCodeAuthModel() .toBuilder().build()); builder.httpCallback = httpCallback; builder.httpClientConfig(() -> ((HttpClientConfiguration) httpClientConfig).newBuilder()); builder.loggingConfig(() -> ((ApiLoggingConfiguration) loggingConfig).newBuilder()); return builder; } /** * Class to build instances of {@link CuadraAiClient}. */ public static class Builder { private Environment environment = Environment.PRODUCTION; private HttpClient httpClient; private AuthorizationCodeAuthModel authorizationCodeAuthModel = new AuthorizationCodeAuthModel.Builder("", "", "").build(); private HttpCallback httpCallback = null; private HttpClientConfiguration.Builder httpClientConfigBuilder = new HttpClientConfiguration.Builder(); private ApiLoggingConfiguration.Builder loggingConfigBuilder = null; /** * Credentials setter for AuthorizationCodeAuth. * @param authorizationCodeAuthModel The instance of AuthorizationCodeAuthModel. * @return The current instance of builder. */ public Builder authorizationCodeAuth( AuthorizationCodeAuthModel authorizationCodeAuthModel) { this.authorizationCodeAuthModel = authorizationCodeAuthModel; return this; } /** * Current API environment. * @param environment The environment for client. * @return Builder */ public Builder environment(Environment environment) { this.environment = environment; return this; } /** * The timeout to use for making HTTP requests. * @deprecated This method will be removed in a future version. Use * {@link #httpClientConfig(Consumer) httpClientConfig} instead. * @param timeout must be greater then 0. * @return Builder */ @Deprecated public Builder timeout(long timeout) { this.httpClientConfigBuilder.timeout(timeout); return this; } /** * Setter for the Builder of LoggingConfiguration, takes in an operation to be * performed on the builder instance of logging configuration. * @param action Consumer for the builder of LoggingConfiguration. * @return Builder */ public Builder loggingConfig(Consumer<ApiLoggingConfiguration.Builder> action) { if (loggingConfigBuilder == null) { loggingConfigBuilder = new ApiLoggingConfiguration.Builder(); } if (loggingConfigBuilder.build().getLogger() == null) { loggingConfigBuilder.useDefaultLogger(); } action.accept(loggingConfigBuilder); return this; } /** * Setter for the Builder of LoggingConfiguration with Console Logging. * * @return Builder */ public Builder loggingConfig() { loggingConfigBuilder = new ApiLoggingConfiguration.Builder(); loggingConfigBuilder.useDefaultLogger(); return this; } /** * Private setter for the Builder of LoggingConfiguration, takes in an operation to be * performed on the builder instance of logging configuration. * * @param supplier Supplier for the builder of LoggingConfiguration. * @return Builder */ private Builder loggingConfig(Supplier<ApiLoggingConfiguration.Builder> supplier) { loggingConfigBuilder = supplier.get(); return this; } /** * HttpCallback. * @param httpCallback Callback to be called before and after the HTTP call. * @return Builder */ public Builder httpCallback(HttpCallback httpCallback) { this.httpCallback = httpCallback; return this; } /** * Setter for the Builder of httpClientConfiguration, takes in an operation to be performed * on the builder instance of HTTP client configuration. * * @param action Consumer for the builder of httpClientConfiguration. * @return Builder */ public Builder httpClientConfig(Consumer<HttpClientConfiguration.Builder> action) { action.accept(httpClientConfigBuilder); return this; } /** * Private Setter for the Builder of httpClientConfiguration, takes in an operation to be performed * on the builder instance of HTTP client configuration. * * @param supplier Supplier for the builder of httpClientConfiguration. * @return Builder */ private Builder httpClientConfig(Supplier<HttpClientConfiguration.Builder> supplier) { httpClientConfigBuilder = supplier.get(); return this; } /** * Builds a new CuadraAiClient object using the set fields. * @return CuadraAiClient */ public CuadraAiClient build() { HttpClientConfiguration httpClientConfig = httpClientConfigBuilder.build(); ReadonlyLoggingConfiguration loggingConfig = loggingConfigBuilder != null ? loggingConfigBuilder.build() : new ApiLoggingConfiguration.Builder().build(); httpClient = new OkClient(httpClientConfig.getConfiguration(), compatibilityFactory); return new CuadraAiClient(environment, httpClient, httpClientConfig, loggingConfig, authorizationCodeAuthModel, httpCallback); } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/DateTimeHelper.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api; import io.apimatic.core.utilities.LocalDateTimeHelper; /** * This is a utility class for DateTime operations. */ public class DateTimeHelper extends LocalDateTimeHelper { }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/Environment.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; /** * Environment to be used. */ public enum Environment { /** * Production Server */ PRODUCTION; private static TreeMap<String, Environment> valueMap = new TreeMap<>(); private String value; static { PRODUCTION.value = "production"; valueMap.put("production", PRODUCTION); } /** * Returns the enum member associated with the given string value. * @param toConvert String value to get enum member. * @return The enum member against the given string value. * @throws IOException when provided value is not mapped to any enum member. */ @JsonCreator public static Environment constructFromString(String toConvert) throws IOException { Environment enumValue = fromString(toConvert); if (enumValue == null) { throw new IOException("Unable to create enum instance with value: " + toConvert); } return enumValue; } /** * Returns the enum member associated with the given string value. * @param toConvert String value to get enum member. * @return The enum member against the given string value. */ public static Environment fromString(String toConvert) { return valueMap.get(toConvert); } /** * Returns the string value associated with the enum member. * @return The string value against enum member. */ @JsonValue public String value() { return value; } /** * Get string representation of this enum. */ @Override public String toString() { return value.toString(); } /** * Convert list of Environment values to list of string values. * @param toConvert The list of Environment values to convert. * @return List of representative string values. */ public static List<String> toValue(List<Environment> toConvert) { if (toConvert == null) { return null; } List<String> convertedValues = new ArrayList<>(); for (Environment enumValue : toConvert) { convertedValues.add(enumValue.value); } return convertedValues; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/Server.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; /** * Server to be used. */ public enum Server { ENUM_DEFAULT, AUTH_SERVER; private static TreeMap<String, Server> valueMap = new TreeMap<>(); private String value; static { ENUM_DEFAULT.value = "default"; AUTH_SERVER.value = "auth server"; valueMap.put("default", ENUM_DEFAULT); valueMap.put("auth server", AUTH_SERVER); } /** * Returns the enum member associated with the given string value. * @param toConvert String value to get enum member. * @return The enum member against the given string value. * @throws IOException when provided value is not mapped to any enum member. */ @JsonCreator public static Server constructFromString(String toConvert) throws IOException { Server enumValue = fromString(toConvert); if (enumValue == null) { throw new IOException("Unable to create enum instance with value: " + toConvert); } return enumValue; } /** * Returns the enum member associated with the given string value. * @param toConvert String value to get enum member. * @return The enum member against the given string value. */ public static Server fromString(String toConvert) { return valueMap.get(toConvert); } /** * Returns the string value associated with the enum member. * @return The string value against enum member. */ @JsonValue public String value() { return value; } /** * Get string representation of this enum. */ @Override public String toString() { return value.toString(); } /** * Convert list of Server values to list of string values. * @param toConvert The list of Server values to convert. * @return List of representative string values. */ public static List<String> toValue(List<Server> toConvert) { if (toConvert == null) { return null; } List<String> convertedValues = new ArrayList<>(); for (Server enumValue : toConvert) { convertedValues.add(enumValue.value); } return convertedValues; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/authentication/AuthorizationCodeAuthManager.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.authentication; import ai.cuadra.api.ApiHelper; import ai.cuadra.api.AuthorizationCodeAuth; import ai.cuadra.api.Server; import ai.cuadra.api.controllers.OauthAuthorizationController; import ai.cuadra.api.exceptions.ApiException; import ai.cuadra.api.models.OauthToken; import io.apimatic.core.GlobalConfiguration; import io.apimatic.core.authentication.HeaderAuth; import io.apimatic.coreinterfaces.http.request.ArraySerializationFormat; import java.io.IOException; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; /** * Utility class for OAuth 2 authorization and token management. */ public class AuthorizationCodeAuthManager extends HeaderAuth implements AuthorizationCodeAuth { /** * Private instance of OAuth 2 API controller. */ private OauthAuthorizationController oAuthApi; /** * Private instance of the configuration to be used. */ private GlobalConfiguration config; /** * Private instance of the auth model containing the auth credentials. */ private AuthorizationCodeAuthModel authModel; /** * Constructor. */ public AuthorizationCodeAuthManager(AuthorizationCodeAuthModel authModel) { super(Collections.singletonMap("Authorization", getAuthorizationHeader(authModel.getOauthToken()))); this.authModel = authModel; } /** * Apply GlobalConfiguration for token management. * @param config GlobalConfiguration instance */ public void applyGlobalConfiguration(GlobalConfiguration config) { this.config = config; this.oAuthApi = new OauthAuthorizationController(config); } /** * String value for oauthClientId. * @return oauthClientId */ public String getOauthClientId() { return authModel.getOauthClientId(); } /** * String value for oauthClientSecret. * @return oauthClientSecret */ public String getOauthClientSecret() { return authModel.getOauthClientSecret(); } /** * String value for oauthRedirectUri. * @return oauthRedirectUri */ public String getOauthRedirectUri() { return authModel.getOauthRedirectUri(); } /** * OauthToken value for oauthToken. * @return oauthToken */ public OauthToken getOauthToken() { return authModel.getOauthToken(); } /** * Checks if provided credentials matched with existing ones. * @param oauthClientId String value for credentials. * @param oauthClientSecret String value for credentials. * @param oauthRedirectUri String value for credentials. * @param oauthToken OauthToken value for credentials. * @return true if credentials matched. */ public boolean equals(String oauthClientId, String oauthClientSecret, String oauthRedirectUri, OauthToken oauthToken) { return oauthClientId.equals(getOauthClientId()) && oauthClientSecret.equals(getOauthClientSecret()) && oauthRedirectUri.equals(getOauthRedirectUri()) && ((getOauthToken() == null && oauthToken == null) || (getOauthToken() != null && oauthToken != null && oauthToken.toString().equals(getOauthToken().toString()))); } /** * Converts this AuthorizationCodeAuthManager into string format. * @return String representation of this class */ @Override public String toString() { return "AuthorizationCodeAuthManager [" + "oauthClientId=" + getOauthClientId() + ", oauthClientSecret=" + getOauthClientSecret() + ", oauthRedirectUri=" + getOauthRedirectUri() + ", oauthToken=" + getOauthToken() + "]"; } /** * Build an authorization URL for taking the user's consent to access data. * @param state An opaque state string. * @param additionalParameters Additional parameters to add the the authorization URL. * @return Authorization URL */ public String buildAuthorizationUrl(final String state, final Map<String, String> additionalParameters) { // the uri for api requests StringBuilder queryBuilder = new StringBuilder(config.getBaseUri().apply(Server.AUTH_SERVER.value())); queryBuilder.append("/authorize"); // build query params Map<String, Object> queryParameters = new HashMap<String, Object>() { private static final long serialVersionUID = 1L; { put("response_type", "code"); put("client_id", getOauthClientId()); put("redirect_uri", getOauthRedirectUri()); put("state", state); } }; // process optional query parameters if (additionalParameters != null) { queryParameters.putAll(additionalParameters); } ApiHelper.appendUrlWithQueryParameters(queryBuilder, queryParameters, ArraySerializationFormat.INDEXED); // validate and preprocess url return ApiHelper.cleanUrl(queryBuilder); } /** * Build an authorization URL for taking the user's consent to access data. * @return Authorization URL */ public String buildAuthorizationUrl() { return buildAuthorizationUrl(null, null); } /** * Build an authorization URL for taking the user's consent to access data. * @param state An opaque state string. * @return Authorization URL */ public String buildAuthorizationUrl(final String state) { return buildAuthorizationUrl(state, null); } /** * Fetch the OAuth token asynchronously. * @param authorizationCode Authorization code returned by the OAuth provider. * @param additionalParameters Additional parameters to send during authorization. */ public CompletableFuture<OauthToken> fetchTokenAsync(final String authorizationCode, final Map<String, Object> additionalParameters) { final Map<String, Object> aparams = additionalParameters == null ? new HashMap<String, Object>() : additionalParameters; return oAuthApi.requestTokenAsync( getBasicAuthForClient(), authorizationCode, getOauthRedirectUri(), aparams).thenApply(result -> { OauthToken token = result.getResult(); Long expiresIn = token.getExpiresIn(); if (expiresIn != null && expiresIn != 0) { token.setExpiry((System.currentTimeMillis() / 1000L) + token.getExpiresIn()); } return token; }); } /** * Fetch the OAuth token asynchronously. * @param authorizationCode Authorization code returned by the OAuth provider. */ public CompletableFuture<OauthToken> fetchTokenAsync(final String authorizationCode) { return fetchTokenAsync(authorizationCode, null); } /** * Fetch the OAuth token. * @param authorizationCode Authorization code returned by the OAuth provider. * @param additionalParameters Additional parameters to send during authorization. */ public OauthToken fetchToken(String authorizationCode, Map<String, Object> additionalParameters) throws ApiException, IOException { final Map<String, Object> aparams = additionalParameters == null ? new HashMap<String, Object>() : additionalParameters; OauthToken token = oAuthApi.requestToken( getBasicAuthForClient(), authorizationCode, getOauthRedirectUri(), aparams).getResult(); if (token.getExpiresIn() != null && token.getExpiresIn() != 0) { token.setExpiry((System.currentTimeMillis() / 1000L) + token.getExpiresIn()); } return token; } /** * Fetch the OAuth token. * @param authorizationCode Authorization code returned by the OAuth provider */ public OauthToken fetchToken(String authorizationCode) throws ApiException, IOException { return fetchToken(authorizationCode, null); } /** * Refresh the OAuth token. * @param additionalParameters Additional parameters to send during token refresh. */ public CompletableFuture<OauthToken> refreshTokenAsync( final Map<String, Object> additionalParameters) { final Map<String, Object> aparams = additionalParameters == null ? new HashMap<String, Object>() : additionalParameters; return oAuthApi.refreshTokenAsync( getBasicAuthForClient(), getOauthToken().getRefreshToken(), null, aparams).thenApply(token -> { return token.getResult(); }); } /** * Refresh the OAuth token. */ public CompletableFuture<OauthToken> refreshTokenAsync() { return refreshTokenAsync(null); } /** * Refresh the OAuth token. * @param additionalParameters Additional parameters to send during token refresh. */ public OauthToken refreshToken(final Map<String, Object> additionalParameters) throws ApiException, IOException { final Map<String, Object> aparams = additionalParameters == null ? new HashMap<String, Object>() : additionalParameters; OauthToken token = oAuthApi.refreshToken( getBasicAuthForClient(), getOauthToken().getRefreshToken(), null, aparams).getResult(); return token; } /** * Refresh the OAuth token. */ public OauthToken refreshToken() throws ApiException, IOException { return refreshToken(null); } /** * Build authorization header value for basic auth. * @return Authorization header value for this client */ private String getBasicAuthForClient() { String val = getOauthClientId() + ":" + getOauthClientSecret(); return "Basic " + new String(Base64.getEncoder().encodeToString(val.getBytes())); } /** * Has the OAuth token expired?. * @return True if expired */ public boolean isTokenExpired() { if (getOauthToken() == null) { throw new IllegalStateException("OAuth token is missing."); } return getOauthToken().getExpiry() != null && getOauthToken().getExpiry() < (System.currentTimeMillis() / 1000L); } /** * Create authorization header for API calls. * @param token OAuth token * @return Authorization header */ private static String getAuthorizationHeader(OauthToken token) { if (token == null) { return null; } return "Bearer " + token.getAccessToken(); } /** * Validate the authentication on the httpRequest */ @Override public void validate() { if (getOauthToken() == null) { setErrorMessage("Client is not authorized." + " An OAuth token is needed to make API calls."); setValidity(false); } else if (isTokenExpired()) { setErrorMessage("The oAuth token is expired." + " A valid token is needed to make API calls."); setValidity(false); } else { setValidity(true); } } /** * Returns the error message if the auth credentials are not valid. * @return the auth specific error message. */ @Override public String getErrorMessage() { String errorMessage = super.getErrorMessage(); if (errorMessage == null) { return null; } return "AuthorizationCodeAuth - " + errorMessage; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/authentication/AuthorizationCodeAuthModel.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.authentication; import ai.cuadra.api.models.OauthToken; /** * A data class for OAuth 2 Authorization Code Grant credentials. */ public class AuthorizationCodeAuthModel { private String oauthClientId; private String oauthClientSecret; private String oauthRedirectUri; private OauthToken oauthToken; /** * A Constructor for AuthorizationCodeAuthModel. */ private AuthorizationCodeAuthModel(String oauthClientId, String oauthClientSecret, String oauthRedirectUri, OauthToken oauthToken) { this.oauthClientId = oauthClientId; this.oauthClientSecret = oauthClientSecret; this.oauthRedirectUri = oauthRedirectUri; this.oauthToken = oauthToken; } /** * Getter for oauthClientId. * @return oauthClientId The value of OAuthClientId. */ public String getOauthClientId() { return this.oauthClientId; } /** * Getter for oauthClientSecret. * @return oauthClientSecret The value of OAuthClientSecret. */ public String getOauthClientSecret() { return this.oauthClientSecret; } /** * Getter for oauthRedirectUri. * @return oauthRedirectUri The value of OAuthRedirectUri. */ public String getOauthRedirectUri() { return this.oauthRedirectUri; } /** * Getter for oauthToken. * @return oauthToken The value of OAuthToken. */ public OauthToken getOauthToken() { return this.oauthToken; } /** * Builds a new {@link AuthorizationCodeAuthModel.Builder} object. * Creates the instance with the state of the current auth model. * @return a new {@link AuthorizationCodeAuthModel.Builder} object. */ public Builder toBuilder() { return new Builder(getOauthClientId(), getOauthClientSecret(), getOauthRedirectUri()) .oauthToken(getOauthToken()); } /** * A Builder class for OAuth 2 Authorization Code Grant credentials. */ public static class Builder { private String oauthClientId; private String oauthClientSecret; private String oauthRedirectUri; private OauthToken oauthToken; /** * The constructor with required auth credentials. * @param oauthClientId The value of OauthClientId. * @param oauthClientSecret The value of OauthClientSecret. * @param oauthRedirectUri The value of OauthRedirectUri. */ public Builder(String oauthClientId, String oauthClientSecret, String oauthRedirectUri) { if (oauthClientId == null) { throw new NullPointerException("OauthClientId cannot be null."); } if (oauthClientSecret == null) { throw new NullPointerException("OauthClientSecret cannot be null."); } if (oauthRedirectUri == null) { throw new NullPointerException("OauthRedirectUri cannot be null."); } this.oauthClientId = oauthClientId; this.oauthClientSecret = oauthClientSecret; this.oauthRedirectUri = oauthRedirectUri; } /** * Setter for oauthClientId. * @param oauthClientId The value of OAuthClientId. * @return Builder The current instance of Builder. */ public Builder oauthClientId(String oauthClientId) { if (oauthClientId == null) { throw new NullPointerException("OauthClientId cannot be null."); } this.oauthClientId = oauthClientId; return this; } /** * Setter for oauthClientSecret. * @param oauthClientSecret The value of OAuthClientSecret. * @return Builder The current instance of Builder. */ public Builder oauthClientSecret(String oauthClientSecret) { if (oauthClientSecret == null) { throw new NullPointerException("OauthClientSecret cannot be null."); } this.oauthClientSecret = oauthClientSecret; return this; } /** * Setter for oauthRedirectUri. * @param oauthRedirectUri The value of OAuthRedirectUri. * @return Builder The current instance of Builder. */ public Builder oauthRedirectUri(String oauthRedirectUri) { if (oauthRedirectUri == null) { throw new NullPointerException("OauthRedirectUri cannot be null."); } this.oauthRedirectUri = oauthRedirectUri; return this; } /** * Setter for oauthToken. * @param oauthToken The value of OAuthToken. * @return Builder The current instance of Builder. */ public Builder oauthToken(OauthToken oauthToken) { this.oauthToken = oauthToken; return this; } /** * Builds the instance of AuthorizationCodeAuthModel using the provided credentials. * @return The instance of AuthorizationCodeAuthModel. */ public AuthorizationCodeAuthModel build() { return new AuthorizationCodeAuthModel(oauthClientId, oauthClientSecret, oauthRedirectUri, oauthToken); } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/controllers/BaseController.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.controllers; import ai.cuadra.api.exceptions.ApiException; import ai.cuadra.api.http.client.HttpCallback; import ai.cuadra.api.http.response.ApiResponse; import io.apimatic.core.ErrorCase; import io.apimatic.core.GlobalConfiguration; import io.apimatic.coreinterfaces.http.HttpClient; import java.util.HashMap; import java.util.Map; /** * Base class for all Controllers. */ public abstract class BaseController { protected static final Map<String, ErrorCase<ApiException>> GLOBAL_ERROR_CASES = new HashMap<String, ErrorCase<ApiException>>(); private GlobalConfiguration globalConfig; static { GLOBAL_ERROR_CASES.put(ErrorCase.DEFAULT, ErrorCase.setReason("HTTP Response Not OK", (reason, context) -> new ApiException(reason, context))); } protected BaseController(GlobalConfiguration globalConfig) { this.globalConfig = globalConfig; } /** * Get httpCallback associated with this controller. * @return HttpCallback */ public HttpCallback getHttpCallback() { return (HttpCallback) globalConfig.getHttpCallback(); } /** * Shared instance of the Http client. * @return The shared instance of the http client */ public HttpClient getClientInstance() { return globalConfig.getHttpClient(); } /** * Instance of the Global Configuration * @return The instance of the global configuration */ protected GlobalConfiguration getGlobalConfiguration() { return globalConfig; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/controllers/ChatController.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.controllers; import ai.cuadra.api.ApiHelper; import ai.cuadra.api.Server; import ai.cuadra.api.exceptions.ApiException; import ai.cuadra.api.exceptions.ErrorResponseException; import ai.cuadra.api.http.request.HttpMethod; import ai.cuadra.api.http.response.ApiResponse; import ai.cuadra.api.models.Chat; import ai.cuadra.api.models.ChatResponseEx; import io.apimatic.core.ApiCall; import io.apimatic.core.ErrorCase; import io.apimatic.core.GlobalConfiguration; import io.apimatic.coreinterfaces.http.request.ResponseClassType; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; /** * This class lists all the endpoints of the groups. */ public final class ChatController extends BaseController { /** * Initializes the controller. * @param globalConfig Configurations added in client. */ public ChatController(GlobalConfiguration globalConfig) { super(globalConfig); } /** * This endpoint creates a new chat interaction with our AI Models. * @param body Required parameter: * @return Returns the ChatResponseEx wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<ChatResponseEx> chat( final Chat body) throws ApiException, IOException { return prepareChatRequest(body).execute(); } /** * This endpoint creates a new chat interaction with our AI Models. * @param body Required parameter: * @return Returns the ChatResponseEx wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<ChatResponseEx>> chatAsync( final Chat body) { try { return prepareChatRequest(body).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for chat. */ private ApiCall<ApiResponse<ChatResponseEx>, ApiException> prepareChatRequest( final Chat body) { return new ApiCall.Builder<ApiResponse<ChatResponseEx>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.ENUM_DEFAULT.value()) .path("/chat") .bodyParam(param -> param.value(body)) .bodySerializer(() -> ApiHelper.serialize(body)) .headerParam(param -> param.key("Content-Type") .value("application/json").isRequired(false)) .headerParam(param -> param.key("accept").value("application/json")) .withAuth(auth -> auth .add("OAuth2")) .httpMethod(HttpMethod.POST)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, ChatResponseEx.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("Bad request, read again our documentation or contact support for guidance.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("401", ErrorCase.setReason("Not authorized, check our OAuth2 doc.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("500", ErrorCase.setReason("Internal error, if this error persist, please contact support.", (reason, context) -> new ErrorResponseException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/controllers/EmbedsController.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.controllers; import ai.cuadra.api.ApiHelper; import ai.cuadra.api.Server; import ai.cuadra.api.exceptions.ApiException; import ai.cuadra.api.exceptions.ErrorResponseException; import ai.cuadra.api.http.request.HttpMethod; import ai.cuadra.api.http.response.ApiResponse; import ai.cuadra.api.models.Embed; import ai.cuadra.api.models.EmbedResponseEx; import io.apimatic.core.ApiCall; import io.apimatic.core.ErrorCase; import io.apimatic.core.GlobalConfiguration; import io.apimatic.coreinterfaces.http.request.ResponseClassType; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; /** * This class lists all the endpoints of the groups. */ public final class EmbedsController extends BaseController { /** * Initializes the controller. * @param globalConfig Configurations added in client. */ public EmbedsController(GlobalConfiguration globalConfig) { super(globalConfig); } /** * This endpoint creates a new embed for training your custom AI Models. * @param body Required parameter: * @return Returns the EmbedResponseEx wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<EmbedResponseEx> embed( final Embed body) throws ApiException, IOException { return prepareEmbedRequest(body).execute(); } /** * This endpoint creates a new embed for training your custom AI Models. * @param body Required parameter: * @return Returns the EmbedResponseEx wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<EmbedResponseEx>> embedAsync( final Embed body) { try { return prepareEmbedRequest(body).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for embed. */ private ApiCall<ApiResponse<EmbedResponseEx>, ApiException> prepareEmbedRequest( final Embed body) { return new ApiCall.Builder<ApiResponse<EmbedResponseEx>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.ENUM_DEFAULT.value()) .path("/embed") .bodyParam(param -> param.value(body)) .bodySerializer(() -> ApiHelper.serialize(body)) .headerParam(param -> param.key("Content-Type") .value("application/json").isRequired(false)) .headerParam(param -> param.key("accept").value("application/json")) .withAuth(auth -> auth .add("OAuth2")) .httpMethod(HttpMethod.POST)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, EmbedResponseEx.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("Bad request, read again our documentation or contact support for guidance.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("401", ErrorCase.setReason("Not authorized, check our OAuth2 doc.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("500", ErrorCase.setReason("Internal error, if this error persist, please contact support.", (reason, context) -> new ErrorResponseException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/controllers/ModelsController.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.controllers; import ai.cuadra.api.ApiHelper; import ai.cuadra.api.Server; import ai.cuadra.api.exceptions.ApiException; import ai.cuadra.api.exceptions.ErrorResponseException; import ai.cuadra.api.http.request.HttpMethod; import ai.cuadra.api.http.response.ApiResponse; import ai.cuadra.api.models.ModelEx; import ai.cuadra.api.models.PaginatedResponseExListModelEx; import io.apimatic.core.ApiCall; import io.apimatic.core.ErrorCase; import io.apimatic.core.GlobalConfiguration; import io.apimatic.coreinterfaces.http.request.ResponseClassType; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; /** * This class lists all the endpoints of the groups. */ public final class ModelsController extends BaseController { /** * Initializes the controller. * @param globalConfig Configurations added in client. */ public ModelsController(GlobalConfiguration globalConfig) { super(globalConfig); } /** * This endpoint display all of our AI models. * @param page Optional parameter: * @param size Optional parameter: * @return Returns the PaginatedResponseExListModelEx wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<PaginatedResponseExListModelEx> getModels( final Integer page, final Integer size) throws ApiException, IOException { return prepareGetModelsRequest(page, size).execute(); } /** * This endpoint display all of our AI models. * @param page Optional parameter: * @param size Optional parameter: * @return Returns the PaginatedResponseExListModelEx wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<PaginatedResponseExListModelEx>> getModelsAsync( final Integer page, final Integer size) { try { return prepareGetModelsRequest(page, size).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for getModels. */ private ApiCall<ApiResponse<PaginatedResponseExListModelEx>, ApiException> prepareGetModelsRequest( final Integer page, final Integer size) { return new ApiCall.Builder<ApiResponse<PaginatedResponseExListModelEx>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.ENUM_DEFAULT.value()) .path("/model") .queryParam(param -> param.key("page") .value(page).isRequired(false)) .queryParam(param -> param.key("size") .value(size).isRequired(false)) .headerParam(param -> param.key("accept").value("application/json")) .withAuth(auth -> auth .add("OAuth2")) .httpMethod(HttpMethod.GET)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, PaginatedResponseExListModelEx.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("Bad request, read again our documentation or contact support for guidance.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("401", ErrorCase.setReason("Not authorized, check our OAuth2 doc.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("500", ErrorCase.setReason("Internal error, if this error persist, please contact support.", (reason, context) -> new ErrorResponseException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } /** * This endpoint creates a new custom Model for you to train and use. * @param body Required parameter: * @return Returns the ModelEx wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<ModelEx> createModel( final ModelEx body) throws ApiException, IOException { return prepareCreateModelRequest(body).execute(); } /** * This endpoint creates a new custom Model for you to train and use. * @param body Required parameter: * @return Returns the ModelEx wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<ModelEx>> createModelAsync( final ModelEx body) { try { return prepareCreateModelRequest(body).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for createModel. */ private ApiCall<ApiResponse<ModelEx>, ApiException> prepareCreateModelRequest( final ModelEx body) { return new ApiCall.Builder<ApiResponse<ModelEx>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.ENUM_DEFAULT.value()) .path("/model") .bodyParam(param -> param.value(body)) .bodySerializer(() -> ApiHelper.serialize(body)) .headerParam(param -> param.key("Content-Type") .value("application/json").isRequired(false)) .headerParam(param -> param.key("accept").value("application/json")) .withAuth(auth -> auth .add("OAuth2")) .httpMethod(HttpMethod.POST)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, ModelEx.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("Bad request, read again our documentation or contact support for guidance.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("401", ErrorCase.setReason("Not authorized, check our OAuth2 doc.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("500", ErrorCase.setReason("Internal error, if this error persist, please contact support.", (reason, context) -> new ErrorResponseException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } /** * This endpoint shows you information about a particular model given an id. * @param id Required parameter: * @return Returns the ModelEx wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<ModelEx> getModel( final String id) throws ApiException, IOException { return prepareGetModelRequest(id).execute(); } /** * This endpoint shows you information about a particular model given an id. * @param id Required parameter: * @return Returns the ModelEx wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<ModelEx>> getModelAsync( final String id) { try { return prepareGetModelRequest(id).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for getModel. */ private ApiCall<ApiResponse<ModelEx>, ApiException> prepareGetModelRequest( final String id) { return new ApiCall.Builder<ApiResponse<ModelEx>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.ENUM_DEFAULT.value()) .path("/model/{id}") .templateParam(param -> param.key("id").value(id) .shouldEncode(true)) .headerParam(param -> param.key("accept").value("application/json")) .withAuth(auth -> auth .add("OAuth2")) .httpMethod(HttpMethod.GET)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, ModelEx.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("Bad request, read again our documentation or contact support for guidance.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("401", ErrorCase.setReason("Not authorized, check our OAuth2 doc.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("500", ErrorCase.setReason("Internal error, if this error persist, please contact support.", (reason, context) -> new ErrorResponseException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } /** * This endpoint removes a custom model you created. * @param id Required parameter: * @return Returns the ModelEx wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<ModelEx> removeModel( final String id) throws ApiException, IOException { return prepareRemoveModelRequest(id).execute(); } /** * This endpoint removes a custom model you created. * @param id Required parameter: * @return Returns the ModelEx wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<ModelEx>> removeModelAsync( final String id) { try { return prepareRemoveModelRequest(id).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for removeModel. */ private ApiCall<ApiResponse<ModelEx>, ApiException> prepareRemoveModelRequest( final String id) { return new ApiCall.Builder<ApiResponse<ModelEx>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.ENUM_DEFAULT.value()) .path("/model/{id}") .templateParam(param -> param.key("id").value(id) .shouldEncode(true)) .headerParam(param -> param.key("accept").value("application/json")) .withAuth(auth -> auth .add("OAuth2")) .httpMethod(HttpMethod.DELETE)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, ModelEx.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("Bad request, read again our documentation or contact support for guidance.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("401", ErrorCase.setReason("Not authorized, check our OAuth2 doc.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("500", ErrorCase.setReason("Internal error, if this error persist, please contact support.", (reason, context) -> new ErrorResponseException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } /** * This endpoint updates a custom model you created. * @param id Required parameter: * @param body Required parameter: * @return Returns the ModelEx wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<ModelEx> updateModel( final String id, final ModelEx body) throws ApiException, IOException { return prepareUpdateModelRequest(id, body).execute(); } /** * This endpoint updates a custom model you created. * @param id Required parameter: * @param body Required parameter: * @return Returns the ModelEx wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<ModelEx>> updateModelAsync( final String id, final ModelEx body) { try { return prepareUpdateModelRequest(id, body).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for updateModel. */ private ApiCall<ApiResponse<ModelEx>, ApiException> prepareUpdateModelRequest( final String id, final ModelEx body) { return new ApiCall.Builder<ApiResponse<ModelEx>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.ENUM_DEFAULT.value()) .path("/model/{id}") .bodyParam(param -> param.value(body)) .bodySerializer(() -> ApiHelper.serialize(body)) .templateParam(param -> param.key("id").value(id) .shouldEncode(true)) .headerParam(param -> param.key("Content-Type") .value("application/json").isRequired(false)) .headerParam(param -> param.key("accept").value("application/json")) .withAuth(auth -> auth .add("OAuth2")) .httpMethod(HttpMethod.PATCH)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, ModelEx.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("Bad request, read again our documentation or contact support for guidance.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("401", ErrorCase.setReason("Not authorized, check our OAuth2 doc.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("500", ErrorCase.setReason("Internal error, if this error persist, please contact support.", (reason, context) -> new ErrorResponseException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/controllers/OauthAuthorizationController.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.controllers; import ai.cuadra.api.ApiHelper; import ai.cuadra.api.Server; import ai.cuadra.api.exceptions.ApiException; import ai.cuadra.api.exceptions.OauthProviderException; import ai.cuadra.api.http.request.HttpMethod; import ai.cuadra.api.http.response.ApiResponse; import ai.cuadra.api.models.OauthToken; import io.apimatic.core.ApiCall; import io.apimatic.core.ErrorCase; import io.apimatic.core.GlobalConfiguration; import io.apimatic.coreinterfaces.http.request.ResponseClassType; import java.io.IOException; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; /** * This class lists all the endpoints of the groups. */ public final class OauthAuthorizationController extends BaseController { /** * Initializes the controller. * @param globalConfig Configurations added in client. */ public OauthAuthorizationController(GlobalConfiguration globalConfig) { super(globalConfig); } /** * Create a new OAuth 2 token. * @param authorization Required parameter: Authorization header in Basic auth format * @param code Required parameter: Authorization Code * @param redirectUri Required parameter: Redirect Uri * @param fieldParameters Additional optional form parameters are supported by this endpoint * @return Returns the OauthToken wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<OauthToken> requestToken( final String authorization, final String code, final String redirectUri, final Map<String, Object> fieldParameters) throws ApiException, IOException { return prepareRequestTokenRequest(authorization, code, redirectUri, fieldParameters).execute(); } /** * Create a new OAuth 2 token. * @param authorization Required parameter: Authorization header in Basic auth format * @param code Required parameter: Authorization Code * @param redirectUri Required parameter: Redirect Uri * @param fieldParameters Additional optional form parameters are supported by this endpoint * @return Returns the OauthToken wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<OauthToken>> requestTokenAsync( final String authorization, final String code, final String redirectUri, final Map<String, Object> fieldParameters) { try { return prepareRequestTokenRequest(authorization, code, redirectUri, fieldParameters).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for requestToken. */ private ApiCall<ApiResponse<OauthToken>, ApiException> prepareRequestTokenRequest( final String authorization, final String code, final String redirectUri, final Map<String, Object> fieldParameters) { return new ApiCall.Builder<ApiResponse<OauthToken>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.AUTH_SERVER.value()) .path("/token") .formParam(param -> param.key("grant_type") .value("authorization_code").isRequired(false)) .formParam(param -> param.key("code") .value(code)) .formParam(param -> param.key("redirect_uri") .value(redirectUri)) .formParam(fieldParameters) .headerParam(param -> param.key("Authorization") .value(authorization).isRequired(false)) .headerParam(param -> param.key("accept").value("application/json")) .httpMethod(HttpMethod.POST)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, OauthToken.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("OAuth 2 provider returned an error.", (reason, context) -> new OauthProviderException(reason, context))) .localErrorCase("401", ErrorCase.setReason("OAuth 2 provider says client authentication failed.", (reason, context) -> new OauthProviderException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } /** * Obtain a new access token using a refresh token. * @param authorization Required parameter: Authorization header in Basic auth format * @param refreshToken Required parameter: Refresh token * @param scope Optional parameter: Requested scopes as a space-delimited list. * @param fieldParameters Additional optional form parameters are supported by this endpoint * @return Returns the OauthToken wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<OauthToken> refreshToken( final String authorization, final String refreshToken, final String scope, final Map<String, Object> fieldParameters) throws ApiException, IOException { return prepareRefreshTokenRequest(authorization, refreshToken, scope, fieldParameters).execute(); } /** * Obtain a new access token using a refresh token. * @param authorization Required parameter: Authorization header in Basic auth format * @param refreshToken Required parameter: Refresh token * @param scope Optional parameter: Requested scopes as a space-delimited list. * @param fieldParameters Additional optional form parameters are supported by this endpoint * @return Returns the OauthToken wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<OauthToken>> refreshTokenAsync( final String authorization, final String refreshToken, final String scope, final Map<String, Object> fieldParameters) { try { return prepareRefreshTokenRequest(authorization, refreshToken, scope, fieldParameters).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for refreshToken. */ private ApiCall<ApiResponse<OauthToken>, ApiException> prepareRefreshTokenRequest( final String authorization, final String refreshToken, final String scope, final Map<String, Object> fieldParameters) { return new ApiCall.Builder<ApiResponse<OauthToken>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.AUTH_SERVER.value()) .path("/token") .formParam(param -> param.key("grant_type") .value("refresh_token").isRequired(false)) .formParam(param -> param.key("refresh_token") .value(refreshToken)) .formParam(param -> param.key("scope") .value(scope).isRequired(false)) .formParam(fieldParameters) .headerParam(param -> param.key("Authorization") .value(authorization).isRequired(false)) .headerParam(param -> param.key("accept").value("application/json")) .httpMethod(HttpMethod.POST)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, OauthToken.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("OAuth 2 provider returned an error.", (reason, context) -> new OauthProviderException(reason, context))) .localErrorCase("401", ErrorCase.setReason("OAuth 2 provider says client authentication failed.", (reason, context) -> new OauthProviderException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/controllers/UsageController.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.controllers; import ai.cuadra.api.ApiHelper; import ai.cuadra.api.Server; import ai.cuadra.api.exceptions.ApiException; import ai.cuadra.api.exceptions.ErrorResponseException; import ai.cuadra.api.http.request.HttpMethod; import ai.cuadra.api.http.response.ApiResponse; import ai.cuadra.api.models.Chat; import ai.cuadra.api.models.TotalUsageEx; import ai.cuadra.api.models.UsageCalculationEx; import io.apimatic.core.ApiCall; import io.apimatic.core.ErrorCase; import io.apimatic.core.GlobalConfiguration; import io.apimatic.coreinterfaces.http.request.ResponseClassType; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; /** * This class lists all the endpoints of the groups. */ public final class UsageController extends BaseController { /** * Initializes the controller. * @param globalConfig Configurations added in client. */ public UsageController(GlobalConfiguration globalConfig) { super(globalConfig); } /** * This endpoint allows you to calculate the usage, so you get an idea of the amount of tokens * that will be consumed. * @param body Required parameter: * @return Returns the UsageCalculationEx wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<UsageCalculationEx> calculateTokens( final Chat body) throws ApiException, IOException { return prepareCalculateTokensRequest(body).execute(); } /** * This endpoint allows you to calculate the usage, so you get an idea of the amount of tokens * that will be consumed. * @param body Required parameter: * @return Returns the UsageCalculationEx wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<UsageCalculationEx>> calculateTokensAsync( final Chat body) { try { return prepareCalculateTokensRequest(body).executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for calculateTokens. */ private ApiCall<ApiResponse<UsageCalculationEx>, ApiException> prepareCalculateTokensRequest( final Chat body) { return new ApiCall.Builder<ApiResponse<UsageCalculationEx>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.ENUM_DEFAULT.value()) .path("/usage/tokenize") .bodyParam(param -> param.value(body)) .bodySerializer(() -> ApiHelper.serialize(body)) .headerParam(param -> param.key("Content-Type") .value("application/json").isRequired(false)) .headerParam(param -> param.key("accept").value("application/json")) .withAuth(auth -> auth .add("OAuth2")) .httpMethod(HttpMethod.POST)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, UsageCalculationEx.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("Bad request, read again our documentation or contact support for guidance.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("401", ErrorCase.setReason("Not authorized, check our OAuth2 doc.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("500", ErrorCase.setReason("Internal error, if this error persist, please contact support.", (reason, context) -> new ErrorResponseException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } /** * This endpoint calculates the amount of tokens used by the user in the given month. * @return Returns the TotalUsageEx wrapped in ApiResponse response from the API call * @throws ApiException Represents error response from the server. * @throws IOException Signals that an I/O exception of some sort has occurred. */ public ApiResponse<TotalUsageEx> totalUsage() throws ApiException, IOException { return prepareTotalUsageRequest().execute(); } /** * This endpoint calculates the amount of tokens used by the user in the given month. * @return Returns the TotalUsageEx wrapped in ApiResponse response from the API call */ public CompletableFuture<ApiResponse<TotalUsageEx>> totalUsageAsync() { try { return prepareTotalUsageRequest().executeAsync(); } catch (Exception e) { throw new CompletionException(e); } } /** * Builds the ApiCall object for totalUsage. */ private ApiCall<ApiResponse<TotalUsageEx>, ApiException> prepareTotalUsageRequest() { return new ApiCall.Builder<ApiResponse<TotalUsageEx>, ApiException>() .globalConfig(getGlobalConfiguration()) .requestBuilder(requestBuilder -> requestBuilder .server(Server.ENUM_DEFAULT.value()) .path("/usage/totals") .headerParam(param -> param.key("accept").value("application/json")) .withAuth(auth -> auth .add("OAuth2")) .httpMethod(HttpMethod.GET)) .responseHandler(responseHandler -> responseHandler .responseClassType(ResponseClassType.API_RESPONSE) .apiResponseDeserializer( response -> ApiHelper.deserialize(response, TotalUsageEx.class)) .nullify404(false) .localErrorCase("400", ErrorCase.setReason("Bad request, read again our documentation or contact support for guidance.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("401", ErrorCase.setReason("Not authorized, check our OAuth2 doc.", (reason, context) -> new ErrorResponseException(reason, context))) .localErrorCase("500", ErrorCase.setReason("Internal error, if this error persist, please contact support.", (reason, context) -> new ErrorResponseException(reason, context))) .globalErrorCase(GLOBAL_ERROR_CASES)) .build(); } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/exceptions/ApiException.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.exceptions; import io.apimatic.core.types.CoreApiException; import io.apimatic.coreinterfaces.http.Context; /** * This is the base class for all exceptions that represent an error response from the server. */ public class ApiException extends CoreApiException { //UID for serialization private static final long serialVersionUID = 1L; /** * Initialization constructor. * @param reason The reason for throwing exception */ public ApiException(String reason) { super(reason); // TODO Auto-generated constructor stub } /** * Initialization constructor. * @param reason The reason for throwing exception * @param context The http context of the API exception */ public ApiException(String reason, Context context) { super(reason, context); } /** * Converts this ApiException into string format. * @return String representation of this class */ @Override public String toString() { return "ApiException [" + "statusCode=" + getResponseCode() + ", message=" + getMessage() + "]"; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/exceptions/ErrorResponseException.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.exceptions; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.coreinterfaces.http.Context; import java.util.Map; /** * This is a model class for ErrorResponseException type. */ public class ErrorResponseException extends ApiException { private static final long serialVersionUID = -4988693302467745927L; private String message; private Integer status; private Map<String, String> fieldErrors; /** * Initialization constructor. * @param reason The reason for throwing exception * @param context The context of the API exception */ public ErrorResponseException(String reason, Context context) { super(reason, context); } /** * Getter for Message. * A message describing the error * @return Returns the String */ @JsonGetter("message") public String getMessageField() { return this.message; } /** * Setter for Message. * A message describing the error * @param messageField Value for String */ @JsonSetter("message") private void setMessageField(String messageField) { this.message = messageField; } /** * Getter for Status. * HTTP status code * @return Returns the Integer */ @JsonGetter("status") public Integer getStatus() { return this.status; } /** * Setter for Status. * HTTP status code * @param status Value for Integer */ @JsonSetter("status") private void setStatus(Integer status) { this.status = status; } /** * Getter for FieldErrors. * Optional: Field-specific validation errors * @return Returns the Map of String, String */ @JsonGetter("field_errors") public Map<String, String> getFieldErrors() { return this.fieldErrors; } /** * Setter for FieldErrors. * Optional: Field-specific validation errors * @param fieldErrors Value for Map of String, String */ @JsonSetter("field_errors") private void setFieldErrors(Map<String, String> fieldErrors) { this.fieldErrors = fieldErrors; } /** * Converts this ErrorResponseException into string format. * @return String representation of this class */ @Override public String toString() { return "ErrorResponseException [" + "statusCode=" + getResponseCode() + ", message=" + getMessage() + ", message=" + message + ", status=" + status + ", fieldErrors=" + fieldErrors + "]"; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/exceptions/OauthProviderException.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.exceptions; import ai.cuadra.api.models.OauthProviderError; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.coreinterfaces.http.Context; /** * This is a model class for OauthProviderException type. */ public class OauthProviderException extends ApiException { private static final long serialVersionUID = 3585874428095013828L; private OauthProviderError error; private String errorDescription; private String errorUri; /** * Initialization constructor. * @param reason The reason for throwing exception * @param context The context of the API exception */ public OauthProviderException(String reason, Context context) { super(reason, context); } /** * Getter for Error. * Gets or sets error code. * @return Returns the OauthProviderError */ @JsonGetter("error") public OauthProviderError getError() { return this.error; } /** * Setter for Error. * Gets or sets error code. * @param error Value for OauthProviderError */ @JsonSetter("error") private void setError(OauthProviderError error) { this.error = error; } /** * Getter for ErrorDescription. * Gets or sets human-readable text providing additional information on error. Used to assist * the client developer in understanding the error that occurred. * @return Returns the String */ @JsonGetter("error_description") public String getErrorDescription() { return this.errorDescription; } /** * Setter for ErrorDescription. * Gets or sets human-readable text providing additional information on error. Used to assist * the client developer in understanding the error that occurred. * @param errorDescription Value for String */ @JsonSetter("error_description") private void setErrorDescription(String errorDescription) { this.errorDescription = errorDescription; } /** * Getter for ErrorUri. * Gets or sets a URI identifying a human-readable web page with information about the error, * used to provide the client developer with additional information about the error. * @return Returns the String */ @JsonGetter("error_uri") public String getErrorUri() { return this.errorUri; } /** * Setter for ErrorUri. * Gets or sets a URI identifying a human-readable web page with information about the error, * used to provide the client developer with additional information about the error. * @param errorUri Value for String */ @JsonSetter("error_uri") private void setErrorUri(String errorUri) { this.errorUri = errorUri; } /** * Converts this OauthProviderException into string format. * @return String representation of this class */ @Override public String toString() { return "OauthProviderException [" + "statusCode=" + getResponseCode() + ", message=" + getMessage() + ", error=" + error + ", errorDescription=" + errorDescription + ", errorUri=" + errorUri + "]"; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/Headers.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import io.apimatic.coreinterfaces.http.HttpHeaders; /** * Class for creating and managing HTTP Headers. */ public class Headers implements HttpHeaders { private Map<String, List<String>> headers; /** * Default constructor. */ public Headers() { this.headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); } /** * Constructor that creates a new instance using a given Map. * @param headers The Map to use for creating an instance of this class. */ public Headers(Map<String, List<String>> headers) { this.headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry<String, List<String>> kv : headers.entrySet()) { add(kv.getKey(), kv.getValue()); } } /** * Copy Constructor. * @param h Headers Instance to be cloned. */ public Headers(Headers h) { this.headers = cloneHeaderMap(h.headers); } /** * Use to check if the given name is present in headers. * @param headerName String name for header to be checked. * @return true if headerName is found, false otherwise. */ public boolean has(String headerName) { return this.headers.containsKey(headerName); } /** * Returns a Set containing all header names. * @return A Set containing all header names. */ public Set<String> names() { return headers.keySet(); } /** * Get the first value associated with a given header name, * or null if the header name is not found. * @param headerName The header name to find the associated value for. * @return The first value associated with the given header name. */ public String value(String headerName) { if (headers.containsKey(headerName)) { return headers.get(headerName).get(0); } return null; } /** * Get a List of all values associated with a given header name, * or null if the header name is not found. * @param headerName The header name to find the associated values for. * @return A List of values associated with the given header name. */ public List<String> values(String headerName) { if (headers.containsKey(headerName)) { return headers.get(headerName); } return null; } /** * Returns a Map of the headers, giving only one value for each header name. * @return A Map of header names and values. */ public Map<String, String> asSimpleMap() { Map<String, String> copy = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry<String, List<String>> kv : this.headers.entrySet()) { if (kv.getValue() != null) { copy.put(kv.getKey(), kv.getValue().get(0)); } } return copy; } /** * Returns a simulated MultiMap of the headers. * @return A Map of header names and values. */ public Map<String, List<String>> asMultimap() { return cloneHeaderMap(this.headers); } /** * Clones a header map. * @param headerMap A Map containing header names and values as Entry pairs. * @return A Map of header names and values. */ private Map<String, List<String>> cloneHeaderMap(Map<String, List<String>> headerMap) { Map<String, List<String>> copy = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry<String, List<String>> kv : headerMap.entrySet()) { if (kv.getValue() != null) { copy.put(kv.getKey(), kv.getValue()); } } return copy; } /** * Adds a value for a header name to this object, neither headerName nor value can be null. * @param headerName The header name to add the value against. * @param value The value to add. */ public void add(String headerName, String value) { if (headerName == null || value == null) { return; } if (this.headers.containsKey(headerName)) { this.headers.get(headerName).add(value); } else { List<String> values = new ArrayList<String>(); values.add(value); this.headers.put(headerName, values); } } /** * Adds a List of values for a header name to this object, neither headerName nor values can be * null. * @param headerName The header name to add the values against. * @param values The List of values to add. */ public void add(String headerName, List<String> values) { if (headerName == null || values == null) { return; } if (this.headers.containsKey(headerName)) { for (String value : values) { if (value != null) { this.headers.get(headerName).add(value); } } } else { List<String> copyOfValues = new ArrayList<String>(); for (String value : values) { if (value != null) { copyOfValues.add(value); } } if (!copyOfValues.isEmpty()) { this.headers.put(headerName, copyOfValues); } } } /** * Adds a value for a header name to this object and returns the Headers instance. * Neither headerName nor values can be null. * @param headerName The header name to add the value against. * @param value The value to add. * @return The current instance after adding the provided header name and value. */ public Headers createHeader(String headerName, String value) { add(headerName, value); return this; } /** * Adds values from a Map to this object. * @param headers A Map containing header names and values as Entry pairs. */ public void addAllFromMap(Map<String, String> headers) { for (Map.Entry<String, String> kv : headers.entrySet()) { this.add(kv.getKey(), kv.getValue()); } } /** * Adds values from a simulated Multi-Map to this object. * @param headers A Map containing header names and values as Entry pairs. */ public void addAllFromMultiMap(Map<String, List<String>> headers) { for (Map.Entry<String, List<String>> kv : headers.entrySet()) { this.add(kv.getKey(), kv.getValue()); } } /** * Adds all the entries in a Headers object to this object. * @param headers The object whose values are to be added to this object. */ public void addAll(HttpHeaders headers) { for (Map.Entry<String, List<String>> kv : headers.asMultimap().entrySet()) { this.add(kv.getKey(), kv.getValue()); } } /** * Removes the mapping for a header name if it is present, * and get the value to which this map previously associated the key, * or null if the map contained no mapping for the key. * @param headerName The header name to remove the associated values for * @return A List of values associated with the given header name. */ public List<String> remove(String headerName) { if (headers.containsKey(headerName)) { return headers.remove(headerName); } return null; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/client/HttpCallback.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.client; import io.apimatic.coreinterfaces.http.Callback; /** * Callback to be called before and after the HTTP call for an endpoint is made. */ public interface HttpCallback extends Callback { }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/client/HttpClientConfiguration.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.client; import ai.cuadra.api.http.request.HttpMethod; import io.apimatic.core.configurations.http.client.CoreHttpClientConfiguration; import io.apimatic.coreinterfaces.http.ClientConfiguration; import io.apimatic.coreinterfaces.http.HttpMethodType; import io.apimatic.coreinterfaces.http.Method; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Class to hold HTTP Client Configuration. */ public class HttpClientConfiguration implements ReadonlyHttpClientConfiguration { private final ClientConfiguration configuration; /** * Default Constructor. */ private HttpClientConfiguration(CoreHttpClientConfiguration.Builder configurationBuilder) { this.configuration = configurationBuilder.build(); } /** * The timeout in seconds to use for making HTTP requests. * @return timeout */ public long getTimeout() { return configuration.getTimeout(); } /** * The number of retries to make. * @return numberOfRetries */ public int getNumberOfRetries() { return configuration.getNumberOfRetries(); } /** * To use in calculation of wait time for next request in case of failure. * @return backOffFactor */ public int getBackOffFactor() { return configuration.getBackOffFactor(); } /** * To use in calculation of wait time for next request in case of failure. * @return retryInterval */ public long getRetryInterval() { return configuration.getRetryInterval(); } /** * Http status codes to retry against. * @return httpStatusCodesToRetry */ public Set<Integer> getHttpStatusCodesToRetry() { return configuration.getHttpStatusCodesToRetry(); } /** * Http methods to retry against. * @return httpMethodsToRetry */ public Set<HttpMethod> getHttpMethodsToRetry() { if (configuration.getHttpMethodsToRetry() == null) { return null; } return configuration.getHttpMethodsToRetry().stream() .map(httpMethod -> HttpMethod.valueOf(httpMethod.toString())) .collect(Collectors.toSet()); } /** * The maximum wait time for overall retrying requests. * @return maximumRetryWaitTime */ public long getMaximumRetryWaitTime() { return configuration.getMaximumRetryWaitTime(); } /** * Whether to retry on request timeout. * @return shouldRetryOnTimeout */ public boolean shouldRetryOnTimeout() { return configuration.shouldRetryOnTimeout(); } /** * The OkHttpClient instance used to make the HTTP calls. * @return httpClientInstance */ public okhttp3.OkHttpClient getHttpClientInstance() { return configuration.getHttpClientInstance(); } /** * Allow the SDK to override HTTP client instance's settings used for features like retries, * timeouts etc. * @return overrideHttpClientConfigurations */ public boolean shouldOverrideHttpClientConfigurations() { return configuration.shouldOverrideHttpClientConfigurations(); } /** * Returns the ClientConfiguration instance. * @return ClientConfiguration */ public ClientConfiguration getConfiguration() { return this.configuration; } /** * Converts this HttpClientConfiguration into string format. * @return String representation of this class */ @Override public String toString() { return "HttpClientConfiguration [" + "timeout=" + getTimeout() + ", numberOfRetries=" + getNumberOfRetries() + ", backOffFactor=" + getBackOffFactor() + ", retryInterval=" + getRetryInterval() + ", httpStatusCodesToRetry=" + getHttpStatusCodesToRetry() + ", httpMethodsToRetry=" + getHttpMethodsToRetry() + ", maximumRetryWaitTime=" + getMaximumRetryWaitTime() + ", shouldRetryOnTimeout=" + shouldRetryOnTimeout() + ", httpClientInstance=" + getHttpClientInstance() + ", overrideHttpClientConfigurations=" + shouldOverrideHttpClientConfigurations() + "]"; } /** * Builds a new {@link HttpClientConfiguration.Builder} object. Creates the instance with the * current state. * * @return a new {@link HttpClientConfiguration.Builder} object */ public Builder newBuilder() { return new Builder() .timeout(getTimeout()) .numberOfRetries(getNumberOfRetries()) .backOffFactor(getBackOffFactor()) .retryInterval(getRetryInterval()) .httpStatusCodesToRetry(getHttpStatusCodesToRetry()) .httpMethodsToRetry(getHttpMethodsToRetry()) .maximumRetryWaitTime(getMaximumRetryWaitTime()) .shouldRetryOnTimeout(shouldRetryOnTimeout()) .httpClientInstance(getHttpClientInstance(), shouldOverrideHttpClientConfigurations()); } /** * Class to build instances of {@link HttpClientConfiguration}. */ public static class Builder { private final CoreHttpClientConfiguration.Builder configurationBuilder = new CoreHttpClientConfiguration.Builder(); /** * Default Constructor to initiate builder with default properties. */ public Builder() { // setting default values configurationBuilder.httpStatusCodesToRetry(Stream.of(408, 413, 429, 500, 502, 503, 504, 521, 522, 524).collect(Collectors.toSet())); configurationBuilder.httpMethodsToRetry(Stream.of(Method.GET, Method.PUT).collect(Collectors.toSet())); } /** * The timeout in seconds to use for making HTTP requests. * @param timeout The timeout to set. * @return Builder */ public Builder timeout(long timeout) { configurationBuilder.timeout(timeout); return this; } /** * The number of retries to make. * @param numberOfRetries The numberOfRetries to set. * @return Builder */ public Builder numberOfRetries(int numberOfRetries) { configurationBuilder.numberOfRetries(numberOfRetries); return this; } /** * To use in calculation of wait time for next request in case of failure. * @param backOffFactor The backOffFactor to set. * @return Builder */ public Builder backOffFactor(int backOffFactor) { configurationBuilder.backOffFactor(backOffFactor); return this; } /** * To use in calculation of wait time for next request in case of failure. * @param retryInterval The retryInterval to set. * @return Builder */ public Builder retryInterval(long retryInterval) { configurationBuilder.retryInterval(retryInterval); return this; } /** * Http status codes to retry against. * @param httpStatusCodesToRetry The httpStatusCodesToRetry to set. * @return Builder */ public Builder httpStatusCodesToRetry(Set<Integer> httpStatusCodesToRetry) { configurationBuilder.httpStatusCodesToRetry(httpStatusCodesToRetry); return this; } /** * Http methods to retry against. * @param httpMethodsToRetry The httpMethodsToRetry to set. * @return Builder */ public Builder httpMethodsToRetry(Set<HttpMethod> httpMethodsToRetry) { Set<Method> convertedHttpMethodsToRetry = null; if (httpMethodsToRetry != null) { convertedHttpMethodsToRetry = httpMethodsToRetry.stream() .map(httpMethod -> HttpMethodType.valueOf(httpMethod.toString())) .collect(Collectors.toSet()); } configurationBuilder.httpMethodsToRetry(convertedHttpMethodsToRetry); return this; } /** * The maximum wait time for overall retrying requests. * @param maximumRetryWaitTime The maximumRetryWaitTime to set. * @return Builder */ public Builder maximumRetryWaitTime(long maximumRetryWaitTime) { configurationBuilder.maximumRetryWaitTime(maximumRetryWaitTime); return this; } /** * Whether to retry on request timeout. * @param shouldRetryOnTimeout The shouldRetryOnTimeout to set * @return Builder */ public Builder shouldRetryOnTimeout(boolean shouldRetryOnTimeout) { configurationBuilder.shouldRetryOnTimeout(shouldRetryOnTimeout); return this; } /** * The OkHttpClient instance used to make the HTTP calls. * @param httpClientInstance The httpClientInstance to set * @return Builder */ public Builder httpClientInstance(okhttp3.OkHttpClient httpClientInstance) { configurationBuilder.httpClientInstance(httpClientInstance); return this; } /** * The OkHttpClient instance used to make the HTTP calls. * @param httpClientInstance The httpClientInstance to set * @param overrideHttpClientConfigurations The overrideHttpClientConfigurations to set * @return Builder */ public Builder httpClientInstance(okhttp3.OkHttpClient httpClientInstance, boolean overrideHttpClientConfigurations) { configurationBuilder.httpClientInstance(httpClientInstance, overrideHttpClientConfigurations); return this; } /** * Builds a new HttpClientConfiguration object using the set fields. * @return {@link HttpClientConfiguration} */ public HttpClientConfiguration build() { return new HttpClientConfiguration(configurationBuilder); } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/client/HttpContext.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.client; import io.apimatic.coreinterfaces.http.Context; import ai.cuadra.api.http.request.HttpRequest; import ai.cuadra.api.http.response.HttpResponse; /** * Class to wrap the request sent to the server and the response received from the server. */ public class HttpContext implements Context { private HttpRequest request; private HttpResponse response; /** * Initialization constructor. * @param request Instance of HttpRequest. * @param response Instance of HttpResponse. */ public HttpContext(HttpRequest request, HttpResponse response) { this.request = request; this.response = response; } /** * Getter for the Http Request. * @return HttpRequest request. */ public HttpRequest getRequest() { return request; } /** * Getter for the Http Response. * @return HttpResponse response. */ public HttpResponse getResponse() { return response; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/client/ReadonlyHttpClientConfiguration.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.client; import ai.cuadra.api.http.request.HttpMethod; import java.util.Set; /** * Interface for holding HTTP Client Configuration. */ public interface ReadonlyHttpClientConfiguration { /** * The timeout in seconds to use for making HTTP requests. * @return a copy of timeout */ long getTimeout(); /** * The number of retries to make. * @return a copy of numberOfRetries */ int getNumberOfRetries(); /** * To use in calculation of wait time for next request in case of failure. * @return a copy of backOffFactor */ int getBackOffFactor(); /** * To use in calculation of wait time for next request in case of failure. * @return a copy of retryInterval */ long getRetryInterval(); /** * Http status codes to retry against. * @return a copy of httpStatusCodesToRetry */ Set<Integer> getHttpStatusCodesToRetry(); /** * Http methods to retry against. * @return a copy of httpMethodsToRetry */ Set<HttpMethod> getHttpMethodsToRetry(); /** * The maximum wait time for overall retrying requests. * @return a copy of maximumRetryWaitTime */ long getMaximumRetryWaitTime(); /** * Whether to retry on request timeout. * @return a copy of shouldRetryOnTimeout */ boolean shouldRetryOnTimeout(); /** * The OkHttpClient instance used to make the HTTP calls. * @return a copy of httpClientInstance */ okhttp3.OkHttpClient getHttpClientInstance(); /** * Allow the SDK to override HTTP client instance's settings used for features like retries, * timeouts etc. * @return a copy of overrideHttpClientConfigurations */ boolean shouldOverrideHttpClientConfigurations(); }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/request/HttpBodyRequest.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.request; import ai.cuadra.api.http.Headers; import java.util.Map; /** * HTTP Request with an explicit body. */ public class HttpBodyRequest extends HttpRequest { /** * Create a request with explicit body. * @param method The HTTP method to use. Can be PUT, POST, DELETE and PATCH * @param queryUrlBuilder The fully qualified absolute http url to create the HTTP Request. * @param headers The key-value map of all http headers to be sent * @param queryParams The query parameters in a key-value map * @param body The object to be sent as body after serialization */ public HttpBodyRequest(HttpMethod method, StringBuilder queryUrlBuilder, Headers headers, Map<String, Object> queryParams, Object body) { super(method, queryUrlBuilder, headers, queryParams, body); } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/request/HttpMethod.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.request; import io.apimatic.coreinterfaces.http.Method; /** * HTTP methods enumeration. */ public enum HttpMethod implements Method { GET, POST, PUT, PATCH, DELETE, HEAD }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/request/HttpRequest.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.request; import ai.cuadra.api.ApiHelper; import ai.cuadra.api.http.Headers; import io.apimatic.coreinterfaces.http.request.ArraySerializationFormat; import io.apimatic.coreinterfaces.http.request.Request; import java.util.AbstractMap.SimpleEntry; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Class for creating and managing HTTP Requests. */ public class HttpRequest implements Request { /** * Private store for properties. */ private HttpMethod httpMethod; private Headers headers; private StringBuilder queryUrlBuilder; private List<SimpleEntry<String, Object>> parameters; private Map<String, Object> queryParameters; private Object body; /** * Initializes a simple http request. * @param method The HTTP method to use. Can be GET, HEAD, PUT, POST, DELETE and PATCH * @param queryUrlBuilder The fully qualified absolute http url to create the HTTP Request. * @param headers The key-value map of all http headers to be sent * @param queryParameters The query parameters in a key-value map * @param parameters The form data values in a key-value map */ public HttpRequest(HttpMethod method, StringBuilder queryUrlBuilder, Headers headers, Map<String, Object> queryParameters, List<SimpleEntry<String, Object>> parameters) { this.httpMethod = method; this.queryUrlBuilder = queryUrlBuilder; this.headers = headers; this.queryParameters = queryParameters; this.parameters = parameters; } /** * Initializes a simple http request. * * @param method The HTTP method to use. Can be GET, HEAD, PUT, POST, DELETE and PATCH * @param queryUrlBuilder The fully qualified absolute http url to create the HTTP Request. * @param headers The key-value map of all http headers to be sent * @param queryParameters The query parameters in a key-value map * @param body The object to be sent as body after serialization */ public HttpRequest(HttpMethod method, StringBuilder queryUrlBuilder, Headers headers, Map<String, Object> queryParameters, Object body) { this(method, queryUrlBuilder, headers, queryParameters, null); this.body = body != null ? body : ""; } /** * HttpMethod for the http request. * @return HttpMethod */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Headers for the http request. * @return Headers */ public Headers getHeaders() { return headers; } /** * Query url for the http request. * @return String query url */ public String getQueryUrl() { return queryUrlBuilder.toString(); } /** * Parameters for the http request. * @return List of simple entries for form parameters */ public List<SimpleEntry<String, Object>> getParameters() { return parameters; } /** * Query parameters for the http request. * @return Map of queryParameters */ public Map<String, Object> getQueryParameters() { return queryParameters; } /** * Body for the http request. * * @return Object body */ public Object getBody() { return body; } /** * Add Query parameter in http request. * @param key The key of query parameter to be added * @param value The value for respective query parameter */ public void addQueryParameter(String key, Object value) { if (key == null || key.isEmpty() || value == null) { return; } if (queryParameters == null) { queryParameters = new HashMap<String, Object>(); } queryParameters.put(key, value); } /** * Get the request URL * * @param arraySerializationFormat Array serialization format * @return The complete URL including serialized query parameters */ @Override public String getUrl(ArraySerializationFormat arraySerializationFormat) { return getQueryUrl(); } /** * Get the request URL without query parameters * * @return The complete URL excluding query parameters */ @Override public String getUrl() { return ApiHelper.removeQueryParametersFromUrl(getQueryUrl()); } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/response/ApiResponse.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.response; import ai.cuadra.api.http.Headers; import io.apimatic.coreinterfaces.http.response.ApiResponseType; public class ApiResponse<T> implements ApiResponseType<T> { /** * Private store for properties. */ int statusCode; Headers headers; T result; /** * HTTP Status code of the api response. * @return Int status code */ public int getStatusCode() { return statusCode; } /** * Headers of the http response. * @return Headers */ public Headers getHeaders() { return headers; } /** * The deserialized result of the api response. * @return result of type T */ public T getResult() { return result; } /** * Initialization constructor. * @param statusCode The HTTP Status code of the api response * @param headers The Headers of the http response * @param result The wrapped response of type T */ public ApiResponse(int statusCode, Headers headers, T result) { this.statusCode = statusCode; this.headers = headers; this.result = result; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/response/HttpResponse.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.response; import ai.cuadra.api.http.Headers; import io.apimatic.coreinterfaces.http.response.Response; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.stream.Collectors; /** * Class to hold HTTP Response. */ public class HttpResponse implements Response { /** * Private store for properties. */ private int statusCode; private Headers headers; private InputStream rawBody; private String body; /** * Initialization constructor. * @param code The HTTP status code * @param headers The HTTP headers read from response * @param rawBody The raw data returned in the HTTP response */ public HttpResponse(int code, Headers headers, InputStream rawBody) { this.statusCode = code; this.headers = headers; this.rawBody = rawBody; } /** * Initialization constructor. * * @param code The HTTP status code * @param headers The HTTP headers read from response * @param rawBody The raw data returned in the HTTP response * @param body String response body */ public HttpResponse(int code, Headers headers, InputStream rawBody, String body) { this(code, headers, rawBody); this.body = body; } /** * HTTP Status code of the http response. * @return Int status code */ public int getStatusCode() { return statusCode; } /** * Headers of the http response. * @return Headers */ public Headers getHeaders() { return headers; } /** * Raw body of the http response. * @return InputStream */ public InputStream getRawBody() { return rawBody; } /** * String representation for raw body of the http response. * @return String */ public String getRawBodyString() { try { if (rawBody == null || rawBody.available() == 0 || !rawBody.markSupported()) { return null; } rawBody.mark(0); String result = new BufferedReader(new InputStreamReader(rawBody)).lines() .collect(Collectors.joining("\n")); rawBody.reset(); return result; } catch (IOException e) { return null; } } /** * String body of the http response. * * @return String response body */ public String getBody() { return body; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/http/response/HttpStringResponse.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.http.response; import ai.cuadra.api.http.Headers; import java.io.InputStream; /** * Class to hold response body as string. */ public class HttpStringResponse extends HttpResponse { /** * Initialization constructor. * @param code The HTTP status code * @param headers The HTTP headers read from response * @param rawBody The raw data returned in the HTTP response * @param body String response body */ public HttpStringResponse(int code, Headers headers, InputStream rawBody, String body) { super(code, headers, rawBody, body); } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging/configuration/ApiLoggingConfiguration.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.logging.configuration; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.event.Level; import io.apimatic.core.logger.configurations.SdkLoggingConfiguration; import io.apimatic.core.logger.configurations.SdkRequestLoggingConfiguration; import io.apimatic.core.logger.configurations.SdkResponseLoggingConfiguration; import io.apimatic.coreinterfaces.logger.configuration.LoggingConfiguration; /** * Class to hold API logging Configuration. */ public class ApiLoggingConfiguration implements ReadonlyLoggingConfiguration { private final LoggingConfiguration configuration; private final ApiRequestLoggingConfiguration requestLoggingConfiguration; private final ApiResponseLoggingConfiguration responseLoggingConfiguration; private ApiLoggingConfiguration(SdkLoggingConfiguration.Builder builder, ApiRequestLoggingConfiguration.Builder requestLoggingConfigurationBuilder, ApiResponseLoggingConfiguration.Builder responseLoggingConfigurationBuilder) { configuration = builder.build(); requestLoggingConfiguration = requestLoggingConfigurationBuilder.build(); responseLoggingConfiguration = responseLoggingConfigurationBuilder.build(); } /** * Getter for Logger. * @return Logger instance. */ public Logger getLogger() { if (configuration.getLogger() == null) { return null; } return configuration.getLogger().getLogger(); } /** * Getter for level. * @return Level of logging. */ public Level getLevel() { return configuration.getLevel(); } /** * Getter for mask sensitive header. * @return True if masking of sensitive headers is enabled, otherwise false. */ public boolean getMaskSensitiveHeaders() { return configuration.getMaskSensitiveHeaders(); } /** * Getter for the Request. * @return The Request object. */ public ReadonlyRequestLoggingConfiguration getRequestConfig() { return requestLoggingConfiguration; } /** * Getter for the ResponseLoggingConfiguration. * @return The ResponseLoggingConfiguration object. */ public ReadonlyResponseLoggingConfiguration getResponseConfig() { return responseLoggingConfiguration; } /** * Returns the SdkLoggingConfiguration instance. * @return ClientConfiguration */ public LoggingConfiguration getConfiguration() { return this.configuration; } /** * Converts this LoggingConfiguration into string format. * @return String representation of this class. */ @Override public String toString() { return "ApiLoggingConfiguration [logger=" + getLogger() + " level=" + getLevel() + " maskSensitiveHeaders=" + getMaskSensitiveHeaders() + " requestLoggingConfiguration=" + getRequestConfig() + " responseLoggingConfiguration=" + getResponseConfig() + "]"; } /** * Builds a new {@link ApiLoggingConfiguration.Builder} object. Creates the * instance with the current state. * @return a new {@link ApiLoggingConfiguration.Builder} object. */ public Builder newBuilder() { Builder builder = new Builder().logger(configuration.getLogger()).level(getLevel()) .maskSensitiveHeaders(getMaskSensitiveHeaders()); builder.apiRequestLoggingBuilder = ((ApiRequestLoggingConfiguration) getRequestConfig()).newBuilder(); builder.apiResponseLoggingBuilder = ((ApiResponseLoggingConfiguration) getResponseConfig()).newBuilder(); return builder; } /** * Class to build instances of {@link ApiLoggingConfiguration}. */ public static class Builder { private final SdkLoggingConfiguration.Builder loggingBuilder = new SdkLoggingConfiguration.Builder(); private ApiRequestLoggingConfiguration.Builder apiRequestLoggingBuilder = new ApiRequestLoggingConfiguration.Builder(); private ApiResponseLoggingConfiguration.Builder apiResponseLoggingBuilder = new ApiResponseLoggingConfiguration.Builder(); /*** * Set Logger for logging. * @param logger The slf4j logger implementation. * @return {@link ApiLoggingConfiguration.Builder}. */ public Builder logger(Logger logger) { loggingBuilder.logger(logger); return this; } /*** * Set Logger wrapper for logging. * @param logger The logger wrapper instance * @return {@link ApiLoggingConfiguration.Builder}. */ private Builder logger(io.apimatic.coreinterfaces.logger.Logger logger) { loggingBuilder.logger(logger); return this; } /** * Set level for logging. * @param level specify level of all logs. * @return {@link ApiLoggingConfiguration.Builder}. */ public Builder level(Level level) { loggingBuilder.level(level); return this; } /** * Set mask sensitive headers flag. * @param maskSensitiveHeaders flag to enable disable masking. * @return {@link ApiLoggingConfiguration.Builder}. */ public Builder maskSensitiveHeaders(boolean maskSensitiveHeaders) { loggingBuilder.maskSensitiveHeaders(maskSensitiveHeaders); return this; } /** * Sets the RequestLoggingConfiguration.Builder for the builder. * @param action The {@link ApiRequestLoggingConfiguration} Builder object. * @return {@link ApiLoggingConfiguration.Builder}. */ public Builder requestConfig(Consumer<ApiRequestLoggingConfiguration.Builder> action) { if (action != null) { action.accept(apiRequestLoggingBuilder); } ApiRequestLoggingConfiguration obj = apiRequestLoggingBuilder.build(); SdkRequestLoggingConfiguration.Builder requestConfigBuilder = new SdkRequestLoggingConfiguration.Builder().body(obj.shouldLogBody()) .headers(obj.shouldLogHeaders()) .includeQueryInPath(obj.shouldIncludeQueryInPath()) .excludeHeaders(obj.getHeadersToExclude().toArray(new String[0])) .includeHeaders(obj.getHeadersToInclude().toArray(new String[0])) .unmaskHeaders(obj.getHeadersToUnmask().toArray(new String[0])); loggingBuilder.requestConfig(requestConfigBuilder); return this; } /** * Sets the ResponseLoggingConfiguration.Builder for the builder. * @param action The {@link ApiResponseLoggingConfiguration} Builder object. * @return {@link ApiLoggingConfiguration.Builder}. */ public Builder responseConfig(Consumer<ApiResponseLoggingConfiguration.Builder> action) { if (action != null) { action.accept(apiResponseLoggingBuilder); } ApiResponseLoggingConfiguration obj = apiResponseLoggingBuilder.build(); SdkResponseLoggingConfiguration.Builder responseConfigBuilder = new SdkResponseLoggingConfiguration.Builder().body(obj.shouldLogBody()) .headers(obj.shouldLogHeaders()) .excludeHeaders(obj.getHeadersToExclude().toArray(new String[0])) .includeHeaders(obj.getHeadersToInclude().toArray(new String[0])) .unmaskHeaders(obj.getHeadersToUnmask().toArray(new String[0])); loggingBuilder.responseConfig(responseConfigBuilder); return this; } /** * Sets the logger instance to ConsoleLogger. * @return {@link ApiLoggingConfiguration.Builder}. */ public Builder useDefaultLogger() { loggingBuilder.useDefaultLogger(); return this; } /** * Builds a new LoggingConfiguration object using the set fields. * @return {@link ApiLoggingConfiguration}. */ public ApiLoggingConfiguration build() { return new ApiLoggingConfiguration(loggingBuilder, apiRequestLoggingBuilder, apiResponseLoggingBuilder); } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging/configuration/ApiRequestLoggingConfiguration.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.logging.configuration; import java.util.List; import io.apimatic.core.logger.configurations.SdkRequestLoggingConfiguration; import io.apimatic.coreinterfaces.logger.configuration.RequestLoggingConfiguration; /** * Class to hold request logging configuration. */ public class ApiRequestLoggingConfiguration implements ReadonlyRequestLoggingConfiguration { private final RequestLoggingConfiguration requestConfig; private ApiRequestLoggingConfiguration(SdkRequestLoggingConfiguration.Builder builder) { requestConfig = builder.build(); } /** * Checks if logging of request body is enabled. * @return True if logging of request body is enabled, otherwise false. */ public boolean shouldLogBody() { return requestConfig.shouldLogBody(); } /** * Checks if logging of request headers is enabled. * @return True if logging of request headers is enabled, otherwise false. */ public boolean shouldLogHeaders() { return requestConfig.shouldLogHeaders(); } /** * Gets the list of headers to include in logging. * @return An unmodifiable list of headers to include. */ public List<String> getHeadersToInclude() { return requestConfig.getHeadersToInclude(); } /** * Gets the list of headers to exclude from logging. * @return An unmodifiable list of headers to exclude. */ public List<String> getHeadersToExclude() { return requestConfig.getHeadersToExclude(); } /** * Retrieves the list of headers to unmask from sensitive headers. These * headers are excluded from masking. * @return An unmodifiable list of headers to unmasked. */ public List<String> getHeadersToUnmask() { return requestConfig.getHeadersToUnmask(); } /** * Checks if query parameters are included in the request path. * @return True if query parameters are included in the path, otherwise false. */ public boolean shouldIncludeQueryInPath() { return requestConfig.shouldIncludeQueryInPath(); } /** * Converts {@link ApiRequestLoggingConfiguration} into string format. * @return String representation of this class. */ @Override public String toString() { return "ApiRequestLoggingConfiguration [logBody=" + shouldLogBody() + " logHeaders=" + shouldLogHeaders() + " includeQueryInPath=" + shouldIncludeQueryInPath() + " excludeHeaders=" + getHeadersToExclude() + " includeHeaders=" + getHeadersToInclude() + " unmaskHeaders=" + getHeadersToUnmask() + "]"; } /** * Builds a new {@link ApiRequestLoggingConfiguration.Builder} object. Creates the instance * with the current state. * @return a new {@link ApiRequestLoggingConfiguration.Builder} object. */ public Builder newBuilder() { return new Builder().body(shouldLogBody()).headers(shouldLogHeaders()) .excludeHeaders(getHeadersToExclude().toArray(new String[0])) .includeHeaders(getHeadersToInclude().toArray(new String[0])) .unmaskHeaders(getHeadersToUnmask().toArray(new String[0])) .includeQueryInPath(shouldIncludeQueryInPath()); } /** * Builder class for ApiRequestLoggingConfiguration. */ public static class Builder { private SdkRequestLoggingConfiguration.Builder builder = new SdkRequestLoggingConfiguration.Builder(); /** * Sets whether to log the body. * @param logBody True to log the body, otherwise false. * @return The builder instance. */ public Builder body(boolean logBody) { builder.body(logBody); return this; } /** * Sets whether to log the headers. * @param logHeaders True to log the headers, otherwise false. * @return The builder instance. */ public Builder headers(boolean logHeaders) { builder.headers(logHeaders); return this; } /** * Sets the headers to be excluded from logging. * @param excludeHeaders The headers to exclude. * @return The builder instance. */ public Builder excludeHeaders(String... excludeHeaders) { builder.excludeHeaders(excludeHeaders); return this; } /** * Sets the headers to be included in logging. * @param includeHeaders The headers to include. * @return The builder instance. */ public Builder includeHeaders(String... includeHeaders) { builder.includeHeaders(includeHeaders); return this; } /** * Sets the headers to be unmasked in logging. * @param unmaskHeaders The headers to unmask in logging. * @return The builder instance. */ public Builder unmaskHeaders(String... unmaskHeaders) { builder.unmaskHeaders(unmaskHeaders); return this; } /** * Sets whether to include query parameters in the request path. * @param includeQueryInPath True to include query parameters in the path, * otherwise false. * @return The builder instance. */ public Builder includeQueryInPath(boolean includeQueryInPath) { builder.includeQueryInPath(includeQueryInPath); return this; } /** * Constructs a ApiRequestLoggingConfiguration object with the set values. * @return The constructed RequestConfiguration object. */ public ApiRequestLoggingConfiguration build() { return new ApiRequestLoggingConfiguration(builder); } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging/configuration/ApiResponseLoggingConfiguration.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.logging.configuration; import java.util.List; import io.apimatic.core.logger.configurations.SdkResponseLoggingConfiguration; import io.apimatic.coreinterfaces.logger.configuration.ResponseLoggingConfiguration; /** * Class to hold response logging configuration. */ public class ApiResponseLoggingConfiguration implements ReadonlyResponseLoggingConfiguration { private final ResponseLoggingConfiguration responseConfig; private ApiResponseLoggingConfiguration(SdkResponseLoggingConfiguration.Builder builder) { responseConfig = builder.build(); } /** * Checks if logging of request body is enabled. * @return True if logging of request body is enabled, otherwise false. */ public boolean shouldLogBody() { return responseConfig.shouldLogBody(); } /** * Checks if logging of request headers is enabled. * @return True if logging of request headers is enabled, otherwise false. */ public boolean shouldLogHeaders() { return responseConfig.shouldLogHeaders(); } /** * Gets the list of headers to include in logging. * @return An unmodifiable list of headers to include. */ public List<String> getHeadersToInclude() { return responseConfig.getHeadersToInclude(); } /** * Gets the list of headers to exclude from logging. * @return An unmodifiable list of headers to exclude. */ public List<String> getHeadersToExclude() { return responseConfig.getHeadersToExclude(); } /** * Retrieves the list of headers to unmask from sensitive headers. These * headers are excluded from masking. * @return An unmodifiable list of headers to unmasked. */ public List<String> getHeadersToUnmask() { return responseConfig.getHeadersToUnmask(); } /** * Converts {@link ApiResponseLoggingConfiguration} into string format. * @return String representation of this class. */ @Override public String toString() { return "ApiResponseLoggingConfiguration [logBody=" + shouldLogBody() + " logHeaders=" + shouldLogHeaders() + " excludeHeaders=" + getHeadersToExclude() + " includeHeaders=" + getHeadersToInclude() + " unmaskHeaders=" + getHeadersToUnmask() + "]"; } /** * Builds a new {@link ApiResponseLoggingConfiguration.Builder} object. Creates the instance * with the current state. * @return a new {@link ApiResponseLoggingConfiguration.Builder} object. */ public Builder newBuilder() { return new Builder().body(shouldLogBody()).headers(shouldLogHeaders()) .excludeHeaders(getHeadersToExclude().toArray(new String[0])) .includeHeaders(getHeadersToInclude().toArray(new String[0])) .unmaskHeaders(getHeadersToUnmask().toArray(new String[0])); } /** * Builder class for RequestLoggingConfiguration. */ public static class Builder { private SdkResponseLoggingConfiguration.Builder builder = new SdkResponseLoggingConfiguration.Builder(); /** * Sets whether to log the body. * @param logBody True to log the body, otherwise false. * @return The builder instance. */ public Builder body(boolean logBody) { builder.body(logBody); return this; } /** * Sets whether to log the headers. * @param logHeaders True to log the headers, otherwise false. * @return The builder instance. */ public Builder headers(boolean logHeaders) { builder.headers(logHeaders); return this; } /** * Sets the headers to be excluded from logging. * @param excludeHeaders The headers to exclude. * @return The builder instance. */ public Builder excludeHeaders(String... excludeHeaders) { builder.excludeHeaders(excludeHeaders); return this; } /** * Sets the headers to be included in logging. * @param includeHeaders The headers to include. * @return The builder instance. */ public Builder includeHeaders(String... includeHeaders) { builder.includeHeaders(includeHeaders); return this; } /** * Sets the headers to be unmasked in logging. * @param unmaskHeaders The headers to unmask in logging. * @return The builder instance. */ public Builder unmaskHeaders(String... unmaskHeaders) { builder.unmaskHeaders(unmaskHeaders); return this; } /** * Constructs a RequestLoggingConfiguration object with the set values. * @return The constructed {@link ApiResponseLoggingConfiguration} object. */ public ApiResponseLoggingConfiguration build() { return new ApiResponseLoggingConfiguration(builder); } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging/configuration/ReadonlyLoggingConfiguration.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.logging.configuration; import org.slf4j.Logger; import org.slf4j.event.Level; /** * Interface to hold logging Configuration. */ public interface ReadonlyLoggingConfiguration { /*** * Getter for Logger * @return Logger Instance */ Logger getLogger(); /** * Getter for level. * @return Level of logging. */ Level getLevel(); /** * Getter for mask sensitive header * @return True if masking of sensitive headers is enabled, otherwise false. */ boolean getMaskSensitiveHeaders(); /** * Getter for ReadonlyRequestLoggingConfiguration * @return ReadonlyRequestLoggingConfiguration */ ReadonlyRequestLoggingConfiguration getRequestConfig(); /** * Getter for ReadonlyResponseLoggingConfiguration * @return {@link ReadonlyResponseLoggingConfiguration} */ ReadonlyResponseLoggingConfiguration getResponseConfig(); }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging/configuration/ReadonlyRequestLoggingConfiguration.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.logging.configuration; import java.util.List; /** * Interface to hold request logging configuration. */ public interface ReadonlyRequestLoggingConfiguration { /** * Checks if logging of request body is enabled. * @return True if logging of request body is enabled, otherwise false. */ boolean shouldLogBody(); /** * Checks if logging of request headers is enabled. * @return True if logging of request headers is enabled, otherwise false. */ boolean shouldLogHeaders(); /** * Gets the list of headers to include in logging. * @return An unmodifiable list of headers to include. */ List<String> getHeadersToInclude(); /** * Gets the list of headers to exclude from logging. * @return An unmodifiable list of headers to exclude. */ List<String> getHeadersToExclude(); /** * Checks if logging of query parameters is required * @return True if logging of query parameters enabled, otherwise false. */ boolean shouldIncludeQueryInPath(); }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/logging/configuration/ReadonlyResponseLoggingConfiguration.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.logging.configuration; import java.util.List; /** * Interface to hold response logging configuration. */ public interface ReadonlyResponseLoggingConfiguration { /** * Checks if logging of request body is enabled. * @return True if logging of request body is enabled, otherwise false. */ boolean shouldLogBody(); /** * Checks if logging of request headers is enabled. * @return True if logging of request headers is enabled, otherwise false. */ boolean shouldLogHeaders(); /** * Gets the list of headers to include in logging. * @return An unmodifiable list of headers to include. */ List<String> getHeadersToInclude(); /** * Gets the list of headers to exclude from logging. * @return An unmodifiable list of headers to exclude. */ List<String> getHeadersToExclude(); }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/Chat.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.List; import java.util.Map; /** * This is a model class for Chat type. */ public class Chat { private String model; private List<ContentEx> content; private String chatId; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public Chat() { } /** * Initialization constructor. * @param model String value for model. * @param content List of ContentEx value for content. * @param chatId String value for chatId. */ public Chat( String model, List<ContentEx> content, String chatId) { this.model = model; this.content = content; this.chatId = chatId; } /** * Getter for Model. * Model name * @return Returns the String */ @JsonGetter("model") public String getModel() { return model; } /** * Setter for Model. * Model name * @param model Value for String */ @JsonSetter("model") public void setModel(String model) { this.model = model; } /** * Getter for Content. * Request content * @return Returns the List of ContentEx */ @JsonGetter("content") public List<ContentEx> getContent() { return content; } /** * Setter for Content. * Request content * @param content Value for List of ContentEx */ @JsonSetter("content") public void setContent(List<ContentEx> content) { this.content = content; } /** * Getter for ChatId. * If you want to keep context between request, otherwise leave it empty, you get one with every * chat you create. * @return Returns the String */ @JsonGetter("chatId") @JsonInclude(JsonInclude.Include.NON_NULL) public String getChatId() { return chatId; } /** * Setter for ChatId. * If you want to keep context between request, otherwise leave it empty, you get one with every * chat you create. * @param chatId Value for String */ @JsonSetter("chatId") public void setChatId(String chatId) { this.chatId = chatId; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this Chat into string format. * @return String representation of this class */ @Override public String toString() { return "Chat [" + "model=" + model + ", content=" + content + ", chatId=" + chatId + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link Chat.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link Chat.Builder} object */ public Builder toBuilder() { Builder builder = new Builder(model, content) .chatId(getChatId()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link Chat}. */ public static class Builder { private String model; private List<ContentEx> content; private String chatId; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Initialization constructor. */ public Builder() { } /** * Initialization constructor. * @param model String value for model. * @param content List of ContentEx value for content. */ public Builder(String model, List<ContentEx> content) { this.model = model; this.content = content; } /** * Setter for model. * @param model String value for model. * @return Builder */ public Builder model(String model) { this.model = model; return this; } /** * Setter for content. * @param content List of ContentEx value for content. * @return Builder */ public Builder content(List<ContentEx> content) { this.content = content; return this; } /** * Setter for chatId. * @param chatId String value for chatId. * @return Builder */ public Builder chatId(String chatId) { this.chatId = chatId; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link Chat} object using the set fields. * @return {@link Chat} */ public Chat build() { Chat model2 = new Chat(model, content, chatId); model2.additionalProperties = additionalProperties; return model2; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/ChatResponseEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.Map; /** * This is a model class for ChatResponseEx type. */ public class ChatResponseEx { private String output; private Double confidenceScore; private String model; private UsageEx usage; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public ChatResponseEx() { } /** * Initialization constructor. * @param output String value for output. * @param confidenceScore Double value for confidenceScore. * @param model String value for model. * @param usage UsageEx value for usage. */ public ChatResponseEx( String output, Double confidenceScore, String model, UsageEx usage) { this.output = output; this.confidenceScore = confidenceScore; this.model = model; this.usage = usage; } /** * Getter for Output. * Output generated by the AI to resolve the request * @return Returns the String */ @JsonGetter("output") @JsonInclude(JsonInclude.Include.NON_NULL) public String getOutput() { return output; } /** * Setter for Output. * Output generated by the AI to resolve the request * @param output Value for String */ @JsonSetter("output") public void setOutput(String output) { this.output = output; } /** * Getter for ConfidenceScore. * Confidence score of how accurate is the output regarding your request * @return Returns the Double */ @JsonGetter("confidenceScore") @JsonInclude(JsonInclude.Include.NON_NULL) public Double getConfidenceScore() { return confidenceScore; } /** * Setter for ConfidenceScore. * Confidence score of how accurate is the output regarding your request * @param confidenceScore Value for Double */ @JsonSetter("confidenceScore") public void setConfidenceScore(Double confidenceScore) { this.confidenceScore = confidenceScore; } /** * Getter for Model. * Model used to resolve your query * @return Returns the String */ @JsonGetter("model") @JsonInclude(JsonInclude.Include.NON_NULL) public String getModel() { return model; } /** * Setter for Model. * Model used to resolve your query * @param model Value for String */ @JsonSetter("model") public void setModel(String model) { this.model = model; } /** * Getter for Usage. * This is the token usage result of your request * @return Returns the UsageEx */ @JsonGetter("usage") @JsonInclude(JsonInclude.Include.NON_NULL) public UsageEx getUsage() { return usage; } /** * Setter for Usage. * This is the token usage result of your request * @param usage Value for UsageEx */ @JsonSetter("usage") public void setUsage(UsageEx usage) { this.usage = usage; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this ChatResponseEx into string format. * @return String representation of this class */ @Override public String toString() { return "ChatResponseEx [" + "output=" + output + ", confidenceScore=" + confidenceScore + ", model=" + model + ", usage=" + usage + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link ChatResponseEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link ChatResponseEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder() .output(getOutput()) .confidenceScore(getConfidenceScore()) .model(getModel()) .usage(getUsage()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link ChatResponseEx}. */ public static class Builder { private String output; private Double confidenceScore; private String model; private UsageEx usage; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Setter for output. * @param output String value for output. * @return Builder */ public Builder output(String output) { this.output = output; return this; } /** * Setter for confidenceScore. * @param confidenceScore Double value for confidenceScore. * @return Builder */ public Builder confidenceScore(Double confidenceScore) { this.confidenceScore = confidenceScore; return this; } /** * Setter for model. * @param model String value for model. * @return Builder */ public Builder model(String model) { this.model = model; return this; } /** * Setter for usage. * @param usage UsageEx value for usage. * @return Builder */ public Builder usage(UsageEx usage) { this.usage = usage; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link ChatResponseEx} object using the set fields. * @return {@link ChatResponseEx} */ public ChatResponseEx build() { ChatResponseEx model2 = new ChatResponseEx(output, confidenceScore, model, usage); model2.additionalProperties = additionalProperties; return model2; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/ContentEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.Map; /** * This is a model class for ContentEx type. */ public class ContentEx { private String text; private InlineDataEx inlineData; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public ContentEx() { } /** * Initialization constructor. * @param text String value for text. * @param inlineData InlineDataEx value for inlineData. */ public ContentEx( String text, InlineDataEx inlineData) { this.text = text; this.inlineData = inlineData; } /** * Getter for Text. * Text is the task you want the AI to solve. * @return Returns the String */ @JsonGetter("text") public String getText() { return text; } /** * Setter for Text. * Text is the task you want the AI to solve. * @param text Value for String */ @JsonSetter("text") public void setText(String text) { this.text = text; } /** * Getter for InlineData. * Input Reference is the name of the file, if you're request is from a type other than text, * and it's required for most types. It has to contain the same name as the file attached in the * request. * @return Returns the InlineDataEx */ @JsonGetter("inlineData") @JsonInclude(JsonInclude.Include.NON_NULL) public InlineDataEx getInlineData() { return inlineData; } /** * Setter for InlineData. * Input Reference is the name of the file, if you're request is from a type other than text, * and it's required for most types. It has to contain the same name as the file attached in the * request. * @param inlineData Value for InlineDataEx */ @JsonSetter("inlineData") public void setInlineData(InlineDataEx inlineData) { this.inlineData = inlineData; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this ContentEx into string format. * @return String representation of this class */ @Override public String toString() { return "ContentEx [" + "text=" + text + ", inlineData=" + inlineData + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link ContentEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link ContentEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder(text) .inlineData(getInlineData()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link ContentEx}. */ public static class Builder { private String text; private InlineDataEx inlineData; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Initialization constructor. */ public Builder() { } /** * Initialization constructor. * @param text String value for text. */ public Builder(String text) { this.text = text; } /** * Setter for text. * @param text String value for text. * @return Builder */ public Builder text(String text) { this.text = text; return this; } /** * Setter for inlineData. * @param inlineData InlineDataEx value for inlineData. * @return Builder */ public Builder inlineData(InlineDataEx inlineData) { this.inlineData = inlineData; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link ContentEx} object using the set fields. * @return {@link ContentEx} */ public ContentEx build() { ContentEx model = new ContentEx(text, inlineData); model.additionalProperties = additionalProperties; return model; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/Embed.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.List; import java.util.Map; /** * This is a model class for Embed type. */ public class Embed { private String model; private List<ContentEx> content; private String purpose; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public Embed() { } /** * Initialization constructor. * @param model String value for model. * @param content List of ContentEx value for content. * @param purpose String value for purpose. */ public Embed( String model, List<ContentEx> content, String purpose) { this.model = model; this.content = content; this.purpose = purpose; } /** * Getter for Model. * Model name * @return Returns the String */ @JsonGetter("model") public String getModel() { return model; } /** * Setter for Model. * Model name * @param model Value for String */ @JsonSetter("model") public void setModel(String model) { this.model = model; } /** * Getter for Content. * Request content * @return Returns the List of ContentEx */ @JsonGetter("content") public List<ContentEx> getContent() { return content; } /** * Setter for Content. * Request content * @param content Value for List of ContentEx */ @JsonSetter("content") public void setContent(List<ContentEx> content) { this.content = content; } /** * Getter for Purpose. * The purpose of the embed, it could be 'search_document', 'search_query', 'classification', o * 'clustering'. * @return Returns the String */ @JsonGetter("purpose") public String getPurpose() { return purpose; } /** * Setter for Purpose. * The purpose of the embed, it could be 'search_document', 'search_query', 'classification', o * 'clustering'. * @param purpose Value for String */ @JsonSetter("purpose") public void setPurpose(String purpose) { this.purpose = purpose; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this Embed into string format. * @return String representation of this class */ @Override public String toString() { return "Embed [" + "model=" + model + ", content=" + content + ", purpose=" + purpose + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link Embed.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link Embed.Builder} object */ public Builder toBuilder() { Builder builder = new Builder(model, content, purpose); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link Embed}. */ public static class Builder { private String model; private List<ContentEx> content; private String purpose; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Initialization constructor. */ public Builder() { } /** * Initialization constructor. * @param model String value for model. * @param content List of ContentEx value for content. * @param purpose String value for purpose. */ public Builder(String model, List<ContentEx> content, String purpose) { this.model = model; this.content = content; this.purpose = purpose; } /** * Setter for model. * @param model String value for model. * @return Builder */ public Builder model(String model) { this.model = model; return this; } /** * Setter for content. * @param content List of ContentEx value for content. * @return Builder */ public Builder content(List<ContentEx> content) { this.content = content; return this; } /** * Setter for purpose. * @param purpose String value for purpose. * @return Builder */ public Builder purpose(String purpose) { this.purpose = purpose; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link Embed} object using the set fields. * @return {@link Embed} */ public Embed build() { Embed model2 = new Embed(model, content, purpose); model2.additionalProperties = additionalProperties; return model2; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/EmbedResponseEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.Map; /** * This is a model class for EmbedResponseEx type. */ public class EmbedResponseEx { private String id; private UsageEx usage; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public EmbedResponseEx() { } /** * Initialization constructor. * @param id String value for id. * @param usage UsageEx value for usage. */ public EmbedResponseEx( String id, UsageEx usage) { this.id = id; this.usage = usage; } /** * Getter for Id. * Embed id * @return Returns the String */ @JsonGetter("id") @JsonInclude(JsonInclude.Include.NON_NULL) public String getId() { return id; } /** * Setter for Id. * Embed id * @param id Value for String */ @JsonSetter("id") public void setId(String id) { this.id = id; } /** * Getter for Usage. * This is the token usage result of your request * @return Returns the UsageEx */ @JsonGetter("usage") @JsonInclude(JsonInclude.Include.NON_NULL) public UsageEx getUsage() { return usage; } /** * Setter for Usage. * This is the token usage result of your request * @param usage Value for UsageEx */ @JsonSetter("usage") public void setUsage(UsageEx usage) { this.usage = usage; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this EmbedResponseEx into string format. * @return String representation of this class */ @Override public String toString() { return "EmbedResponseEx [" + "id=" + id + ", usage=" + usage + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link EmbedResponseEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link EmbedResponseEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder() .id(getId()) .usage(getUsage()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link EmbedResponseEx}. */ public static class Builder { private String id; private UsageEx usage; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Setter for id. * @param id String value for id. * @return Builder */ public Builder id(String id) { this.id = id; return this; } /** * Setter for usage. * @param usage UsageEx value for usage. * @return Builder */ public Builder usage(UsageEx usage) { this.usage = usage; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link EmbedResponseEx} object using the set fields. * @return {@link EmbedResponseEx} */ public EmbedResponseEx build() { EmbedResponseEx model = new EmbedResponseEx(id, usage); model.additionalProperties = additionalProperties; return model; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/InlineDataEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.Map; /** * This is a model class for InlineDataEx type. */ public class InlineDataEx { private String mimeType; private String data; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public InlineDataEx() { } /** * Initialization constructor. * @param mimeType String value for mimeType. * @param data String value for data. */ public InlineDataEx( String mimeType, String data) { this.mimeType = mimeType; this.data = data; } /** * Getter for MimeType. * @return Returns the String */ @JsonGetter("mimeType") @JsonInclude(JsonInclude.Include.NON_NULL) public String getMimeType() { return mimeType; } /** * Setter for MimeType. * @param mimeType Value for String */ @JsonSetter("mimeType") public void setMimeType(String mimeType) { this.mimeType = mimeType; } /** * Getter for Data. * @return Returns the String */ @JsonGetter("data") @JsonInclude(JsonInclude.Include.NON_NULL) public String getData() { return data; } /** * Setter for Data. * @param data Value for String */ @JsonSetter("data") public void setData(String data) { this.data = data; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this InlineDataEx into string format. * @return String representation of this class */ @Override public String toString() { return "InlineDataEx [" + "mimeType=" + mimeType + ", data=" + data + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link InlineDataEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link InlineDataEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder() .mimeType(getMimeType()) .data(getData()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link InlineDataEx}. */ public static class Builder { private String mimeType; private String data; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Setter for mimeType. * @param mimeType String value for mimeType. * @return Builder */ public Builder mimeType(String mimeType) { this.mimeType = mimeType; return this; } /** * Setter for data. * @param data String value for data. * @return Builder */ public Builder data(String data) { this.data = data; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link InlineDataEx} object using the set fields. * @return {@link InlineDataEx} */ public InlineDataEx build() { InlineDataEx model = new InlineDataEx(mimeType, data); model.additionalProperties = additionalProperties; return model; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/ModelEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import ai.cuadra.api.DateTimeHelper; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.time.LocalDateTime; import java.util.Map; /** * This is a model class for ModelEx type. */ public class ModelEx { private String id; private String name; private String type; private String description; private Boolean proprietary; private String baseModel; private String baseModelId; private LocalDateTime createdAt; private LocalDateTime updatedAt; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public ModelEx() { } /** * Initialization constructor. * @param name String value for name. * @param type String value for type. * @param description String value for description. * @param id String value for id. * @param proprietary Boolean value for proprietary. * @param baseModel String value for baseModel. * @param baseModelId String value for baseModelId. * @param createdAt LocalDateTime value for createdAt. * @param updatedAt LocalDateTime value for updatedAt. */ public ModelEx( String name, String type, String description, String id, Boolean proprietary, String baseModel, String baseModelId, LocalDateTime createdAt, LocalDateTime updatedAt) { this.id = id; this.name = name; this.type = type; this.description = description; this.proprietary = proprietary; this.baseModel = baseModel; this.baseModelId = baseModelId; this.createdAt = createdAt; this.updatedAt = updatedAt; } /** * Getter for Id. * Model Id * @return Returns the String */ @JsonGetter("id") @JsonInclude(JsonInclude.Include.NON_NULL) public String getId() { return id; } /** * Setter for Id. * Model Id * @param id Value for String */ @JsonSetter("id") public void setId(String id) { this.id = id; } /** * Getter for Name. * Model name * @return Returns the String */ @JsonGetter("name") public String getName() { return name; } /** * Setter for Name. * Model name * @param name Value for String */ @JsonSetter("name") public void setName(String name) { this.name = name; } /** * Getter for Type. * Model type of content generation and processing * @return Returns the String */ @JsonGetter("type") public String getType() { return type; } /** * Setter for Type. * Model type of content generation and processing * @param type Value for String */ @JsonSetter("type") public void setType(String type) { this.type = type; } /** * Getter for Description. * Brief description of the model * @return Returns the String */ @JsonGetter("description") public String getDescription() { return description; } /** * Setter for Description. * Brief description of the model * @param description Value for String */ @JsonSetter("description") public void setDescription(String description) { this.description = description; } /** * Getter for Proprietary. * Indicates whether is a custom model created by you or not * @return Returns the Boolean */ @JsonGetter("proprietary") @JsonInclude(JsonInclude.Include.NON_NULL) public Boolean getProprietary() { return proprietary; } /** * Setter for Proprietary. * Indicates whether is a custom model created by you or not * @param proprietary Value for Boolean */ @JsonSetter("proprietary") public void setProprietary(Boolean proprietary) { this.proprietary = proprietary; } /** * Getter for BaseModel. * Base model name, if it was created from another model * @return Returns the String */ @JsonGetter("baseModel") @JsonInclude(JsonInclude.Include.NON_NULL) public String getBaseModel() { return baseModel; } /** * Setter for BaseModel. * Base model name, if it was created from another model * @param baseModel Value for String */ @JsonSetter("baseModel") public void setBaseModel(String baseModel) { this.baseModel = baseModel; } /** * Getter for BaseModelId. * Base model id, if it was created from another model * @return Returns the String */ @JsonGetter("baseModelId") @JsonInclude(JsonInclude.Include.NON_NULL) public String getBaseModelId() { return baseModelId; } /** * Setter for BaseModelId. * Base model id, if it was created from another model * @param baseModelId Value for String */ @JsonSetter("baseModelId") public void setBaseModelId(String baseModelId) { this.baseModelId = baseModelId; } /** * Getter for CreatedAt. * Creation date * @return Returns the LocalDateTime */ @JsonGetter("createdAt") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonSerialize(using = DateTimeHelper.Rfc8601DateTimeSerializer.class) public LocalDateTime getCreatedAt() { return createdAt; } /** * Setter for CreatedAt. * Creation date * @param createdAt Value for LocalDateTime */ @JsonSetter("createdAt") @JsonDeserialize(using = DateTimeHelper.Rfc8601DateTimeDeserializer.class) public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } /** * Getter for UpdatedAt. * Last time it was updated * @return Returns the LocalDateTime */ @JsonGetter("updatedAt") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonSerialize(using = DateTimeHelper.Rfc8601DateTimeSerializer.class) public LocalDateTime getUpdatedAt() { return updatedAt; } /** * Setter for UpdatedAt. * Last time it was updated * @param updatedAt Value for LocalDateTime */ @JsonSetter("updatedAt") @JsonDeserialize(using = DateTimeHelper.Rfc8601DateTimeDeserializer.class) public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this ModelEx into string format. * @return String representation of this class */ @Override public String toString() { return "ModelEx [" + "name=" + name + ", type=" + type + ", description=" + description + ", id=" + id + ", proprietary=" + proprietary + ", baseModel=" + baseModel + ", baseModelId=" + baseModelId + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link ModelEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link ModelEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder(name, type, description) .id(getId()) .proprietary(getProprietary()) .baseModel(getBaseModel()) .baseModelId(getBaseModelId()) .createdAt(getCreatedAt()) .updatedAt(getUpdatedAt()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link ModelEx}. */ public static class Builder { private String name; private String type; private String description; private String id; private Boolean proprietary; private String baseModel; private String baseModelId; private LocalDateTime createdAt; private LocalDateTime updatedAt; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Initialization constructor. */ public Builder() { } /** * Initialization constructor. * @param name String value for name. * @param type String value for type. * @param description String value for description. */ public Builder(String name, String type, String description) { this.name = name; this.type = type; this.description = description; } /** * Setter for name. * @param name String value for name. * @return Builder */ public Builder name(String name) { this.name = name; return this; } /** * Setter for type. * @param type String value for type. * @return Builder */ public Builder type(String type) { this.type = type; return this; } /** * Setter for description. * @param description String value for description. * @return Builder */ public Builder description(String description) { this.description = description; return this; } /** * Setter for id. * @param id String value for id. * @return Builder */ public Builder id(String id) { this.id = id; return this; } /** * Setter for proprietary. * @param proprietary Boolean value for proprietary. * @return Builder */ public Builder proprietary(Boolean proprietary) { this.proprietary = proprietary; return this; } /** * Setter for baseModel. * @param baseModel String value for baseModel. * @return Builder */ public Builder baseModel(String baseModel) { this.baseModel = baseModel; return this; } /** * Setter for baseModelId. * @param baseModelId String value for baseModelId. * @return Builder */ public Builder baseModelId(String baseModelId) { this.baseModelId = baseModelId; return this; } /** * Setter for createdAt. * @param createdAt LocalDateTime value for createdAt. * @return Builder */ public Builder createdAt(LocalDateTime createdAt) { this.createdAt = createdAt; return this; } /** * Setter for updatedAt. * @param updatedAt LocalDateTime value for updatedAt. * @return Builder */ public Builder updatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link ModelEx} object using the set fields. * @return {@link ModelEx} */ public ModelEx build() { ModelEx model = new ModelEx(name, type, description, id, proprietary, baseModel, baseModelId, createdAt, updatedAt); model.additionalProperties = additionalProperties; return model; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/OauthProviderError.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; /** * OauthProviderError to be used. */ public enum OauthProviderError { /** * The request is missing a required parameter, includes an unsupported parameter value (other than grant type), repeats a parameter, includes multiple credentials, utilizes more than one mechanism for authenticating the client, or is otherwise malformed. */ INVALID_REQUEST, /** * Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method). */ INVALID_CLIENT, /** * The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client. */ INVALID_GRANT, /** * The authenticated client is not authorized to use this authorization grant type. */ UNAUTHORIZED_CLIENT, /** * The authorization grant type is not supported by the authorization server. */ UNSUPPORTED_GRANT_TYPE, /** * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. */ INVALID_SCOPE; private static TreeMap<String, OauthProviderError> valueMap = new TreeMap<>(); private String value; static { INVALID_REQUEST.value = "invalid_request"; INVALID_CLIENT.value = "invalid_client"; INVALID_GRANT.value = "invalid_grant"; UNAUTHORIZED_CLIENT.value = "unauthorized_client"; UNSUPPORTED_GRANT_TYPE.value = "unsupported_grant_type"; INVALID_SCOPE.value = "invalid_scope"; valueMap.put("invalid_request", INVALID_REQUEST); valueMap.put("invalid_client", INVALID_CLIENT); valueMap.put("invalid_grant", INVALID_GRANT); valueMap.put("unauthorized_client", UNAUTHORIZED_CLIENT); valueMap.put("unsupported_grant_type", UNSUPPORTED_GRANT_TYPE); valueMap.put("invalid_scope", INVALID_SCOPE); } /** * Returns the enum member associated with the given string value. * @param toConvert String value to get enum member. * @return The enum member against the given string value. * @throws IOException when provided value is not mapped to any enum member. */ @JsonCreator public static OauthProviderError constructFromString(String toConvert) throws IOException { OauthProviderError enumValue = fromString(toConvert); if (enumValue == null) { throw new IOException("Unable to create enum instance with value: " + toConvert); } return enumValue; } /** * Returns the enum member associated with the given string value. * @param toConvert String value to get enum member. * @return The enum member against the given string value. */ public static OauthProviderError fromString(String toConvert) { return valueMap.get(toConvert); } /** * Returns the string value associated with the enum member. * @return The string value against enum member. */ @JsonValue public String value() { return value; } /** * Get string representation of this enum. */ @Override public String toString() { return value.toString(); } /** * Convert list of OauthProviderError values to list of string values. * @param toConvert The list of OauthProviderError values to convert. * @return List of representative string values. */ public static List<String> toValue(List<OauthProviderError> toConvert) { if (toConvert == null) { return null; } List<String> convertedValues = new ArrayList<>(); for (OauthProviderError enumValue : toConvert) { convertedValues.add(enumValue.value); } return convertedValues; } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/OauthToken.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; /** * This is a model class for OauthToken type. */ public class OauthToken { private String accessToken; private String tokenType; private Long expiresIn; private String scope; private Long expiry; private String refreshToken; /** * Default constructor. */ public OauthToken() { } /** * Initialization constructor. * @param accessToken String value for accessToken. * @param tokenType String value for tokenType. * @param expiresIn Long value for expiresIn. * @param scope String value for scope. * @param expiry Long value for expiry. * @param refreshToken String value for refreshToken. */ public OauthToken( String accessToken, String tokenType, Long expiresIn, String scope, Long expiry, String refreshToken) { this.accessToken = accessToken; this.tokenType = tokenType; this.expiresIn = expiresIn; this.scope = scope; this.expiry = expiry; this.refreshToken = refreshToken; } /** * Getter for AccessToken. * Access token * @return Returns the String */ @JsonGetter("access_token") public String getAccessToken() { return accessToken; } /** * Setter for AccessToken. * Access token * @param accessToken Value for String */ @JsonSetter("access_token") public void setAccessToken(String accessToken) { this.accessToken = accessToken; } /** * Getter for TokenType. * Type of access token * @return Returns the String */ @JsonGetter("token_type") public String getTokenType() { return tokenType; } /** * Setter for TokenType. * Type of access token * @param tokenType Value for String */ @JsonSetter("token_type") public void setTokenType(String tokenType) { this.tokenType = tokenType; } /** * Getter for ExpiresIn. * Time in seconds before the access token expires * @return Returns the Long */ @JsonGetter("expires_in") @JsonInclude(JsonInclude.Include.NON_NULL) public Long getExpiresIn() { return expiresIn; } /** * Setter for ExpiresIn. * Time in seconds before the access token expires * @param expiresIn Value for Long */ @JsonSetter("expires_in") public void setExpiresIn(Long expiresIn) { this.expiresIn = expiresIn; } /** * Getter for Scope. * List of scopes granted This is a space-delimited list of strings. * @return Returns the String */ @JsonGetter("scope") @JsonInclude(JsonInclude.Include.NON_NULL) public String getScope() { return scope; } /** * Setter for Scope. * List of scopes granted This is a space-delimited list of strings. * @param scope Value for String */ @JsonSetter("scope") public void setScope(String scope) { this.scope = scope; } /** * Getter for Expiry. * Time of token expiry as unix timestamp (UTC) * @return Returns the Long */ @JsonGetter("expiry") @JsonInclude(JsonInclude.Include.NON_NULL) public Long getExpiry() { return expiry; } /** * Setter for Expiry. * Time of token expiry as unix timestamp (UTC) * @param expiry Value for Long */ @JsonSetter("expiry") public void setExpiry(Long expiry) { this.expiry = expiry; } /** * Getter for RefreshToken. * Refresh token Used to get a new access token when it expires. * @return Returns the String */ @JsonGetter("refresh_token") @JsonInclude(JsonInclude.Include.NON_NULL) public String getRefreshToken() { return refreshToken; } /** * Setter for RefreshToken. * Refresh token Used to get a new access token when it expires. * @param refreshToken Value for String */ @JsonSetter("refresh_token") public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } /** * Builds a new {@link OauthToken.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link OauthToken.Builder} object */ public Builder toBuilder() { Builder builder = new Builder(accessToken, tokenType) .expiresIn(getExpiresIn()) .scope(getScope()) .expiry(getExpiry()) .refreshToken(getRefreshToken()); return builder; } /** * Class to build instances of {@link OauthToken}. */ public static class Builder { private String accessToken; private String tokenType; private Long expiresIn; private String scope; private Long expiry; private String refreshToken; /** * Initialization constructor. */ public Builder() { } /** * Initialization constructor. * @param accessToken String value for accessToken. * @param tokenType String value for tokenType. */ public Builder(String accessToken, String tokenType) { this.accessToken = accessToken; this.tokenType = tokenType; } /** * Setter for accessToken. * @param accessToken String value for accessToken. * @return Builder */ public Builder accessToken(String accessToken) { this.accessToken = accessToken; return this; } /** * Setter for tokenType. * @param tokenType String value for tokenType. * @return Builder */ public Builder tokenType(String tokenType) { this.tokenType = tokenType; return this; } /** * Setter for expiresIn. * @param expiresIn Long value for expiresIn. * @return Builder */ public Builder expiresIn(Long expiresIn) { this.expiresIn = expiresIn; return this; } /** * Setter for scope. * @param scope String value for scope. * @return Builder */ public Builder scope(String scope) { this.scope = scope; return this; } /** * Setter for expiry. * @param expiry Long value for expiry. * @return Builder */ public Builder expiry(Long expiry) { this.expiry = expiry; return this; } /** * Setter for refreshToken. * @param refreshToken String value for refreshToken. * @return Builder */ public Builder refreshToken(String refreshToken) { this.refreshToken = refreshToken; return this; } /** * Builds a new {@link OauthToken} object using the set fields. * @return {@link OauthToken} */ public OauthToken build() { return new OauthToken(accessToken, tokenType, expiresIn, scope, expiry, refreshToken); } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/PaginatedResponseExListModelEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.List; import java.util.Map; /** * This is a model class for PaginatedResponseExListModelEx type. */ public class PaginatedResponseExListModelEx { private Integer page; private Integer size; private List<ModelEx> data; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public PaginatedResponseExListModelEx() { } /** * Initialization constructor. * @param page Integer value for page. * @param size Integer value for size. * @param data List of ModelEx value for data. */ public PaginatedResponseExListModelEx( Integer page, Integer size, List<ModelEx> data) { this.page = page; this.size = size; this.data = data; } /** * Getter for Page. * @return Returns the Integer */ @JsonGetter("page") @JsonInclude(JsonInclude.Include.NON_NULL) public Integer getPage() { return page; } /** * Setter for Page. * @param page Value for Integer */ @JsonSetter("page") public void setPage(Integer page) { this.page = page; } /** * Getter for Size. * @return Returns the Integer */ @JsonGetter("size") @JsonInclude(JsonInclude.Include.NON_NULL) public Integer getSize() { return size; } /** * Setter for Size. * @param size Value for Integer */ @JsonSetter("size") public void setSize(Integer size) { this.size = size; } /** * Getter for Data. * @return Returns the List of ModelEx */ @JsonGetter("data") @JsonInclude(JsonInclude.Include.NON_NULL) public List<ModelEx> getData() { return data; } /** * Setter for Data. * @param data Value for List of ModelEx */ @JsonSetter("data") public void setData(List<ModelEx> data) { this.data = data; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this PaginatedResponseExListModelEx into string format. * @return String representation of this class */ @Override public String toString() { return "PaginatedResponseExListModelEx [" + "page=" + page + ", size=" + size + ", data=" + data + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link PaginatedResponseExListModelEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link PaginatedResponseExListModelEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder() .page(getPage()) .size(getSize()) .data(getData()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link PaginatedResponseExListModelEx}. */ public static class Builder { private Integer page; private Integer size; private List<ModelEx> data; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Setter for page. * @param page Integer value for page. * @return Builder */ public Builder page(Integer page) { this.page = page; return this; } /** * Setter for size. * @param size Integer value for size. * @return Builder */ public Builder size(Integer size) { this.size = size; return this; } /** * Setter for data. * @param data List of ModelEx value for data. * @return Builder */ public Builder data(List<ModelEx> data) { this.data = data; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link PaginatedResponseExListModelEx} object using the set fields. * @return {@link PaginatedResponseExListModelEx} */ public PaginatedResponseExListModelEx build() { PaginatedResponseExListModelEx model = new PaginatedResponseExListModelEx(page, size, data); model.additionalProperties = additionalProperties; return model; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/TokensEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.Map; /** * This is a model class for TokensEx type. */ public class TokensEx { private Integer inputTokens; private Integer outputTokens; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public TokensEx() { } /** * Initialization constructor. * @param inputTokens Integer value for inputTokens. * @param outputTokens Integer value for outputTokens. */ public TokensEx( Integer inputTokens, Integer outputTokens) { this.inputTokens = inputTokens; this.outputTokens = outputTokens; } /** * Getter for InputTokens. * Number of tokens of the request input * @return Returns the Integer */ @JsonGetter("inputTokens") @JsonInclude(JsonInclude.Include.NON_NULL) public Integer getInputTokens() { return inputTokens; } /** * Setter for InputTokens. * Number of tokens of the request input * @param inputTokens Value for Integer */ @JsonSetter("inputTokens") public void setInputTokens(Integer inputTokens) { this.inputTokens = inputTokens; } /** * Getter for OutputTokens. * Number of tokens of the response output * @return Returns the Integer */ @JsonGetter("outputTokens") @JsonInclude(JsonInclude.Include.NON_NULL) public Integer getOutputTokens() { return outputTokens; } /** * Setter for OutputTokens. * Number of tokens of the response output * @param outputTokens Value for Integer */ @JsonSetter("outputTokens") public void setOutputTokens(Integer outputTokens) { this.outputTokens = outputTokens; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this TokensEx into string format. * @return String representation of this class */ @Override public String toString() { return "TokensEx [" + "inputTokens=" + inputTokens + ", outputTokens=" + outputTokens + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link TokensEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link TokensEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder() .inputTokens(getInputTokens()) .outputTokens(getOutputTokens()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link TokensEx}. */ public static class Builder { private Integer inputTokens; private Integer outputTokens; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Setter for inputTokens. * @param inputTokens Integer value for inputTokens. * @return Builder */ public Builder inputTokens(Integer inputTokens) { this.inputTokens = inputTokens; return this; } /** * Setter for outputTokens. * @param outputTokens Integer value for outputTokens. * @return Builder */ public Builder outputTokens(Integer outputTokens) { this.outputTokens = outputTokens; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link TokensEx} object using the set fields. * @return {@link TokensEx} */ public TokensEx build() { TokensEx model = new TokensEx(inputTokens, outputTokens); model.additionalProperties = additionalProperties; return model; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/TotalUsageEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.Map; /** * This is a model class for TotalUsageEx type. */ public class TotalUsageEx { private Long totalInput; private Long totalOutput; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public TotalUsageEx() { } /** * Initialization constructor. * @param totalInput Long value for totalInput. * @param totalOutput Long value for totalOutput. */ public TotalUsageEx( Long totalInput, Long totalOutput) { this.totalInput = totalInput; this.totalOutput = totalOutput; } /** * Getter for TotalInput. * Total Input Tokens used for this month * @return Returns the Long */ @JsonGetter("totalInput") @JsonInclude(JsonInclude.Include.NON_NULL) public Long getTotalInput() { return totalInput; } /** * Setter for TotalInput. * Total Input Tokens used for this month * @param totalInput Value for Long */ @JsonSetter("totalInput") public void setTotalInput(Long totalInput) { this.totalInput = totalInput; } /** * Getter for TotalOutput. * Total Ouput Tokens used for this month * @return Returns the Long */ @JsonGetter("totalOutput") @JsonInclude(JsonInclude.Include.NON_NULL) public Long getTotalOutput() { return totalOutput; } /** * Setter for TotalOutput. * Total Ouput Tokens used for this month * @param totalOutput Value for Long */ @JsonSetter("totalOutput") public void setTotalOutput(Long totalOutput) { this.totalOutput = totalOutput; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this TotalUsageEx into string format. * @return String representation of this class */ @Override public String toString() { return "TotalUsageEx [" + "totalInput=" + totalInput + ", totalOutput=" + totalOutput + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link TotalUsageEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link TotalUsageEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder() .totalInput(getTotalInput()) .totalOutput(getTotalOutput()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link TotalUsageEx}. */ public static class Builder { private Long totalInput; private Long totalOutput; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Setter for totalInput. * @param totalInput Long value for totalInput. * @return Builder */ public Builder totalInput(Long totalInput) { this.totalInput = totalInput; return this; } /** * Setter for totalOutput. * @param totalOutput Long value for totalOutput. * @return Builder */ public Builder totalOutput(Long totalOutput) { this.totalOutput = totalOutput; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link TotalUsageEx} object using the set fields. * @return {@link TotalUsageEx} */ public TotalUsageEx build() { TotalUsageEx model = new TotalUsageEx(totalInput, totalOutput); model.additionalProperties = additionalProperties; return model; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/UsageCalculationEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.Map; /** * This is a model class for UsageCalculationEx type. */ public class UsageCalculationEx { private Integer estimatedTokens; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public UsageCalculationEx() { } /** * Initialization constructor. * @param estimatedTokens Integer value for estimatedTokens. */ public UsageCalculationEx( Integer estimatedTokens) { this.estimatedTokens = estimatedTokens; } /** * Getter for EstimatedTokens. * Estimated tokens for your request * @return Returns the Integer */ @JsonGetter("estimatedTokens") @JsonInclude(JsonInclude.Include.NON_NULL) public Integer getEstimatedTokens() { return estimatedTokens; } /** * Setter for EstimatedTokens. * Estimated tokens for your request * @param estimatedTokens Value for Integer */ @JsonSetter("estimatedTokens") public void setEstimatedTokens(Integer estimatedTokens) { this.estimatedTokens = estimatedTokens; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this UsageCalculationEx into string format. * @return String representation of this class */ @Override public String toString() { return "UsageCalculationEx [" + "estimatedTokens=" + estimatedTokens + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link UsageCalculationEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link UsageCalculationEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder() .estimatedTokens(getEstimatedTokens()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link UsageCalculationEx}. */ public static class Builder { private Integer estimatedTokens; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Setter for estimatedTokens. * @param estimatedTokens Integer value for estimatedTokens. * @return Builder */ public Builder estimatedTokens(Integer estimatedTokens) { this.estimatedTokens = estimatedTokens; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link UsageCalculationEx} object using the set fields. * @return {@link UsageCalculationEx} */ public UsageCalculationEx build() { UsageCalculationEx model = new UsageCalculationEx(estimatedTokens); model.additionalProperties = additionalProperties; return model; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/models/UsageEx.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.models; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import io.apimatic.core.types.AdditionalProperties; import io.apimatic.core.utilities.ConversionHelper; import java.util.Map; /** * This is a model class for UsageEx type. */ public class UsageEx { private TokensEx billedTokens; private TokensEx usedTokens; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(this.getClass()); /** * Default constructor. */ public UsageEx() { } /** * Initialization constructor. * @param billedTokens TokensEx value for billedTokens. * @param usedTokens TokensEx value for usedTokens. */ public UsageEx( TokensEx billedTokens, TokensEx usedTokens) { this.billedTokens = billedTokens; this.usedTokens = usedTokens; } /** * Getter for BilledTokens. * Tokens used * @return Returns the TokensEx */ @JsonGetter("billedTokens") @JsonInclude(JsonInclude.Include.NON_NULL) public TokensEx getBilledTokens() { return billedTokens; } /** * Setter for BilledTokens. * Tokens used * @param billedTokens Value for TokensEx */ @JsonSetter("billedTokens") public void setBilledTokens(TokensEx billedTokens) { this.billedTokens = billedTokens; } /** * Getter for UsedTokens. * Tokens used * @return Returns the TokensEx */ @JsonGetter("usedTokens") @JsonInclude(JsonInclude.Include.NON_NULL) public TokensEx getUsedTokens() { return usedTokens; } /** * Setter for UsedTokens. * Tokens used * @param usedTokens Value for TokensEx */ @JsonSetter("usedTokens") public void setUsedTokens(TokensEx usedTokens) { this.usedTokens = usedTokens; } /** * Hidden method for the serialization of additional properties. * @return The map of additionally set properties. */ @JsonAnyGetter private Map<String, Object> getAdditionalProperties() { return additionalProperties.getAdditionalProperties(); } /** * Hidden method for the de-serialization of additional properties. * @param name The name of the additional property. * @param value The Object value of the additional property. */ @JsonAnySetter private void setAdditionalProperties(String name, Object value) { additionalProperties.setAdditionalProperty(name, ConversionHelper.convertToSimpleType(value, x -> x), true); } /** * Getter for the value of additional properties based on provided property name. * @param name The name of the additional property. * @return Either the Object property value or null if not exist. */ public Object getAdditionalProperty(String name) { return additionalProperties.getAdditionalProperty(name); } /** * Converts this UsageEx into string format. * @return String representation of this class */ @Override public String toString() { return "UsageEx [" + "billedTokens=" + billedTokens + ", usedTokens=" + usedTokens + ", additionalProperties=" + additionalProperties + "]"; } /** * Builds a new {@link UsageEx.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link UsageEx.Builder} object */ public Builder toBuilder() { Builder builder = new Builder() .billedTokens(getBilledTokens()) .usedTokens(getUsedTokens()); builder.additionalProperties = additionalProperties; return builder; } /** * Class to build instances of {@link UsageEx}. */ public static class Builder { private TokensEx billedTokens; private TokensEx usedTokens; private AdditionalProperties<Object> additionalProperties = new AdditionalProperties<Object>(); /** * Setter for billedTokens. * @param billedTokens TokensEx value for billedTokens. * @return Builder */ public Builder billedTokens(TokensEx billedTokens) { this.billedTokens = billedTokens; return this; } /** * Setter for usedTokens. * @param usedTokens TokensEx value for usedTokens. * @return Builder */ public Builder usedTokens(TokensEx usedTokens) { this.usedTokens = usedTokens; return this; } /** * Setter for additional property that are not in model fields. * @param name The name of the additional property. * @param value The Object value of the additional property. * @return Builder. */ public Builder additionalProperty(String name, Object value) { this.additionalProperties.setAdditionalProperty(name, value); return this; } /** * Builds a new {@link UsageEx} object using the set fields. * @return {@link UsageEx} */ public UsageEx build() { UsageEx model = new UsageEx(billedTokens, usedTokens); model.additionalProperties = additionalProperties; return model; } } }
0
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api
java-sources/ai/cuadra/cuadra-ai-sdk/1.0.4/ai/cuadra/api/utilities/FileWrapper.java
/* * CuadraAiLib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ package ai.cuadra.api.utilities; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.File; import io.apimatic.coreinterfaces.type.CoreFileWrapper; /** * Class to wrap file and contentType to be sent as part of a HTTP request. */ public class FileWrapper implements CoreFileWrapper { @JsonInclude(JsonInclude.Include.NON_NULL) private File file; @JsonInclude(JsonInclude.Include.NON_NULL) private String contentType; /** * Initialization constructor. * @param file File object to be wrapped * @param contentType content type of file */ public FileWrapper(File file, String contentType) { this.file = file; this.contentType = contentType; } /** * Initialization constructor. * @param file File object to be wrapped */ public FileWrapper(File file) { this.file = file; } /** * Getter for file. * @return File instance */ public File getFile() { return file; } /** * Getter for loggable file. * @return loggable string of file. */ @SuppressWarnings("unused") private String getLoggableFile() { return file.getName(); } /** * Getter for content type. * @return content type of the file */ public String getContentType() { return contentType; } /** * Converts FileWrapper object into string format. * @return String representation of this class */ @Override public String toString() { return "FileWrapper [fileName=" + (file != null ? file.getName() : "") + ", contentType=" + contentType + "]"; } }
0
java-sources/ai/databand/azkaban/az-core/3.90.0
java-sources/ai/databand/azkaban/az-core/3.90.0/azkaban/AzkabanCoreModule.java
/* * Copyright 2017 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://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. * */ package azkaban; import azkaban.utils.Props; import com.codahale.metrics.MetricRegistry; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Guice launching place for az-core. */ public class AzkabanCoreModule extends AbstractModule { private static final Logger log = LoggerFactory.getLogger(AzkabanCoreModule.class); private final Props props; public AzkabanCoreModule(final Props props) { this.props = props; } @Override protected void configure() { bind(Props.class).toInstance(this.props); bind(MetricRegistry.class).in(Scopes.SINGLETON); } }
0
java-sources/ai/databand/azkaban/az-core/3.90.0
java-sources/ai/databand/azkaban/az-core/3.90.0/azkaban/Constants.java
/* * Copyright 2018 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://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. */ package azkaban; import java.time.Duration; /** * Constants used in configuration files or shared among classes. * * <p>Conventions: * * <p>Internal constants to be put in the {@link Constants} class * * <p>Configuration keys to be put in the {@link ConfigurationKeys} class * * <p>Flow level properties keys to be put in the {@link FlowProperties} class * * <p>Job level Properties keys to be put in the {@link JobProperties} class * * <p>Use '.' to separate name spaces and '_" to separate words in the same namespace. e.g. * azkaban.job.some_key</p> */ public class Constants { // Azkaban Flow Versions public static final double DEFAULT_AZKABAN_FLOW_VERSION = 1.0; public static final double AZKABAN_FLOW_VERSION_2_0 = 2.0; // Flow 2.0 file suffix public static final String PROJECT_FILE_SUFFIX = ".project"; public static final String FLOW_FILE_SUFFIX = ".flow"; // Flow 2.0 node type public static final String NODE_TYPE = "type"; public static final String FLOW_NODE_TYPE = "flow"; // Flow 2.0 flow and job path delimiter public static final String PATH_DELIMITER = ":"; // Job properties override suffix public static final String JOB_OVERRIDE_SUFFIX = ".jor"; // Names and paths of various file names to configure Azkaban public static final String AZKABAN_PROPERTIES_FILE = "azkaban.properties"; public static final String AZKABAN_PRIVATE_PROPERTIES_FILE = "azkaban.private.properties"; public static final String DEFAULT_CONF_PATH = "conf"; public static final String DEFAULT_EXECUTOR_PORT_FILE = "executor.port"; public static final String AZKABAN_SERVLET_CONTEXT_KEY = "azkaban_app"; // Internal username used to perform SLA action public static final String AZKABAN_SLA_CHECKER_USERNAME = "azkaban_sla"; // Memory check retry interval when OOM in ms public static final long MEMORY_CHECK_INTERVAL_MS = 1000 * 60 * 1; // Max number of memory check retry public static final int MEMORY_CHECK_RETRY_LIMIT = 720; public static final int DEFAULT_PORT_NUMBER = 8081; public static final int DEFAULT_SSL_PORT_NUMBER = 8443; public static final int DEFAULT_JETTY_MAX_THREAD_COUNT = 20; // One Schedule's default End Time: 01/01/2050, 00:00:00, UTC public static final long DEFAULT_SCHEDULE_END_EPOCH_TIME = 2524608000000L; // Default flow trigger max wait time public static final Duration DEFAULT_FLOW_TRIGGER_MAX_WAIT_TIME = Duration.ofDays(10); public static final Duration MIN_FLOW_TRIGGER_WAIT_TIME = Duration.ofMinutes(1); // The flow exec id for a flow trigger instance which hasn't started a flow yet public static final int UNASSIGNED_EXEC_ID = -1; // The flow exec id for a flow trigger instance unable to trigger a flow yet public static final int FAILED_EXEC_ID = -2; // Default locked flow error message public static final String DEFAULT_LOCKED_FLOW_ERROR_MESSAGE = "Flow %s in project %s is locked. This is either a repeatedly failing flow, or an ineffcient" + " flow. Please refer to the Dr. Elephant report for this flow for more information."; // Default maximum number of concurrent runs for a single flow public static final int DEFAULT_MAX_ONCURRENT_RUNS_ONEFLOW = 30; // How often executors will poll new executions in Poll Dispatch model public static final int DEFAULT_AZKABAN_POLLING_INTERVAL_MS = 1000; // Executors can use cpu load calculated from this period to take/skip polling turns public static final int DEFAULT_AZKABAN_POLLING_CRITERIA_CPU_LOAD_PERIOD_SEC = 60; // Default value to feature enable setting. To be backward compatible, this value === FALSE public static final boolean DEFAULT_AZKABAN_RAMP_ENABLED = false; // Due to multiple AzkabanExec Server instance scenario, it will be required to persistent the ramp result into the DB. // However, Frequent data persistence will sacrifice the performance with limited data accuracy. // This setting value controls to push result into DB every N finished ramped workflows public static final int DEFAULT_AZKABAN_RAMP_STATUS_PUSH_INTERVAL_MAX = 20; // Due to multiple AzkabanExec Server instance, it will be required to persistent the ramp result into the DB. // However, Frequent data persistence will sacrifice the performance with limited data accuracy. // This setting value controls to pull result from DB every N new ramped workflows public static final int DEFAULT_AZKABAN_RAMP_STATUS_PULL_INTERVAL_MAX = 50; // Use Polling Service to sync the ramp status cross EXEC Server. public static final boolean DEFAULT_AZKABAN_RAMP_STATUS_POOLING_ENABLED = false; // How often executors will poll ramp status in Poll Dispatch model public static final int DEFAULT_AZKABAN_RAMP_STATUS_POLLING_INTERVAL = 10; public static class ConfigurationKeys { public static final String AZKABAN_GLOBAL_PROPERTIES_EXT_PATH = "executor.global.properties"; // Configures Azkaban to use new polling model for dispatching public static final String AZKABAN_POLL_MODEL = "azkaban.poll.model"; public static final String AZKABAN_POLLING_INTERVAL_MS = "azkaban.polling.interval.ms"; public static final String AZKABAN_POLLING_LOCK_ENABLED = "azkaban.polling.lock.enabled"; public static final String AZKABAN_POLLING_CRITERIA_FLOW_THREADS_AVAILABLE = "azkaban.polling_criteria.flow_threads_available"; public static final String AZKABAN_POLLING_CRITERIA_MIN_FREE_MEMORY_GB = "azkaban.polling_criteria.min_free_memory_gb"; public static final String AZKABAN_POLLING_CRITERIA_MAX_CPU_UTILIZATION_PCT = "azkaban.polling_criteria.max_cpu_utilization_pct"; public static final String AZKABAN_POLLING_CRITERIA_CPU_LOAD_PERIOD_SEC = "azkaban.polling_criteria.cpu_load_period_sec"; // Configures properties for Azkaban executor health check public static final String AZKABAN_EXECUTOR_HEALTHCHECK_INTERVAL_MIN = "azkaban.executor.healthcheck.interval.min"; public static final String AZKABAN_EXECUTOR_MAX_FAILURE_COUNT = "azkaban.executor.max.failurecount"; public static final String AZKABAN_ADMIN_ALERT_EMAIL = "azkaban.admin.alert.email"; // Configures Azkaban Flow Version in project YAML file public static final String AZKABAN_FLOW_VERSION = "azkaban-flow-version"; // These properties are configurable through azkaban.properties public static final String AZKABAN_PID_FILENAME = "azkaban.pid.filename"; // Defines a list of external links, each referred to as a topic public static final String AZKABAN_SERVER_EXTERNAL_TOPICS = "azkaban.server.external.topics"; // External URL template of a given topic, specified in the list defined above public static final String AZKABAN_SERVER_EXTERNAL_TOPIC_URL = "azkaban.server.external.${topic}.url"; // Designates one of the external link topics to correspond to an execution analyzer public static final String AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC = "azkaban.server.external.analyzer.topic"; public static final String AZKABAN_SERVER_EXTERNAL_ANALYZER_LABEL = "azkaban.server.external.analyzer.label"; // Designates one of the external link topics to correspond to a job log viewer public static final String AZKABAN_SERVER_EXTERNAL_LOGVIEWER_TOPIC = "azkaban.server.external.logviewer.topic"; public static final String AZKABAN_SERVER_EXTERNAL_LOGVIEWER_LABEL = "azkaban.server.external.logviewer.label"; /* * Hadoop/Spark user job link. * Example: * a) azkaban.server.external.resource_manager_job_url=http://***rm***:8088/cluster/app/application_${application.id} * b) azkaban.server.external.history_server_job_url=http://***jh***:19888/jobhistory/job/job_${application.id} * c) azkaban.server.external.spark_history_server_job_url=http://***sh***:18080/history/application_${application.id}/1/jobs * */ public static final String RESOURCE_MANAGER_JOB_URL = "azkaban.server.external.resource_manager_job_url"; public static final String HISTORY_SERVER_JOB_URL = "azkaban.server.external.history_server_job_url"; public static final String SPARK_HISTORY_SERVER_JOB_URL = "azkaban.server.external.spark_history_server_job_url"; // Configures the Kafka appender for logging user jobs, specified for the exec server public static final String AZKABAN_SERVER_LOGGING_KAFKA_BROKERLIST = "azkaban.server.logging.kafka.brokerList"; public static final String AZKABAN_SERVER_LOGGING_KAFKA_TOPIC = "azkaban.server.logging.kafka.topic"; // Represent the class name of azkaban metrics reporter. public static final String CUSTOM_METRICS_REPORTER_CLASS_NAME = "azkaban.metrics.reporter.name"; // Represent the metrics server URL. public static final String METRICS_SERVER_URL = "azkaban.metrics.server.url"; public static final String IS_METRICS_ENABLED = "azkaban.is.metrics.enabled"; // User facing web server configurations used to construct the user facing server URLs. They are useful when there is a reverse proxy between Azkaban web servers and users. // enduser -> myazkabanhost:443 -> proxy -> localhost:8081 // when this parameters set then these parameters are used to generate email links. // if these parameters are not set then jetty.hostname, and jetty.port(if ssl configured jetty.ssl.port) are used. public static final String AZKABAN_WEBSERVER_EXTERNAL_HOSTNAME = "azkaban.webserver.external_hostname"; public static final String AZKABAN_WEBSERVER_EXTERNAL_SSL_PORT = "azkaban.webserver.external_ssl_port"; public static final String AZKABAN_WEBSERVER_EXTERNAL_PORT = "azkaban.webserver.external_port"; // Hostname for the host, if not specified, canonical hostname will be used public static final String AZKABAN_SERVER_HOST_NAME = "azkaban.server.hostname"; // List of users we prevent azkaban from running flows as. (ie: root, azkaban) public static final String BLACK_LISTED_USERS = "azkaban.server.blacklist.users"; // Path name of execute-as-user executable public static final String AZKABAN_SERVER_NATIVE_LIB_FOLDER = "azkaban.native.lib"; // Name of *nix group associated with the process running Azkaban public static final String AZKABAN_SERVER_GROUP_NAME = "azkaban.group.name"; // Legacy configs section, new configs should follow the naming convention of azkaban.server.<rest of the name> for server configs. public static final String EXECUTOR_PORT_FILE = "executor.portfile"; // To set a fixed port for executor-server. Otherwise some available port is used. public static final String EXECUTOR_PORT = "executor.port"; // Max flow running time in mins, server will kill flows running longer than this setting. // if not set or <= 0, then there's no restriction on running time. public static final String AZKABAN_MAX_FLOW_RUNNING_MINS = "azkaban.server.flow.max.running.minutes"; // Maximum number of tries to download a dependency (no more retry attempts will be made after this many download failures) public static final String AZKABAN_DEPENDENCY_MAX_DOWNLOAD_TRIES = "azkaban.dependency.max.download.tries"; public static final String AZKABAN_STORAGE_TYPE = "azkaban.storage.type"; public static final String AZKABAN_STORAGE_LOCAL_BASEDIR = "azkaban.storage.local.basedir"; public static final String HADOOP_CONF_DIR_PATH = "hadoop.conf.dir.path"; // This really should be azkaban.storage.hdfs.project_root.uri public static final String AZKABAN_STORAGE_HDFS_PROJECT_ROOT_URI = "azkaban.storage.hdfs.root.uri"; public static final String AZKABAN_STORAGE_CACHE_DEPENDENCY_ENABLED = "azkaban.storage.cache.dependency.enabled"; public static final String AZKABAN_STORAGE_CACHE_DEPENDENCY_ROOT_URI = "azkaban.storage.cache.dependency_root.uri"; public static final String AZKABAN_STORAGE_ORIGIN_DEPENDENCY_ROOT_URI = "azkaban.storage.origin.dependency_root.uri"; public static final String AZKABAN_KERBEROS_PRINCIPAL = "azkaban.kerberos.principal"; public static final String AZKABAN_KEYTAB_PATH = "azkaban.keytab.path"; public static final String PROJECT_TEMP_DIR = "project.temp.dir"; // Event reporting properties public static final String AZKABAN_EVENT_REPORTING_CLASS_PARAM = "azkaban.event.reporting.class"; public static final String AZKABAN_EVENT_REPORTING_ENABLED = "azkaban.event.reporting.enabled"; // Comma separated list of properties to propagate from flow to Event reporter metadata public static final String AZKABAN_EVENT_REPORTING_PROPERTIES_TO_PROPAGATE = "azkaban.event.reporting.propagateProperties"; public static final String AZKABAN_EVENT_REPORTING_KAFKA_BROKERS = "azkaban.event.reporting.kafka.brokers"; public static final String AZKABAN_EVENT_REPORTING_KAFKA_TOPIC = "azkaban.event.reporting.kafka.topic"; public static final String AZKABAN_EVENT_REPORTING_KAFKA_SCHEMA_REGISTRY_URL = "azkaban.event.reporting.kafka.schema.registry.url"; /* * The max number of artifacts retained per project. * Accepted Values: * - 0 : Save all artifacts. No clean up is done on storage. * - 1, 2, 3, ... (any +ve integer 'n') : Maintain 'n' latest versions in storage * * Note: Having an unacceptable value results in an exception and the service would REFUSE * to start. * * Example: * a) azkaban.storage.artifact.max.retention=all * implies save all artifacts * b) azkaban.storage.artifact.max.retention=3 * implies save latest 3 versions saved in storage. **/ public static final String AZKABAN_STORAGE_ARTIFACT_MAX_RETENTION = "azkaban.storage.artifact.max.retention"; // enable quartz scheduler and flow trigger if true. public static final String ENABLE_QUARTZ = "azkaban.server.schedule.enable_quartz"; public static final String CUSTOM_CREDENTIAL_NAME = "azkaban.security.credential"; public static final String OAUTH_CREDENTIAL_NAME = "azkaban.oauth.credential"; public static final String SECURITY_USER_GROUP = "azkaban.security.user.group"; // dir to keep dependency plugins public static final String DEPENDENCY_PLUGIN_DIR = "azkaban.dependency.plugin.dir"; public static final String USE_MULTIPLE_EXECUTORS = "azkaban.use.multiple.executors"; public static final String MAX_CONCURRENT_RUNS_ONEFLOW = "azkaban.max.concurrent.runs.oneflow"; // list of whitelisted flows, with specific max number of concurrent runs. Format: // <project 1>,<flow 1>,<number>;<project 2>,<flow 2>,<number> public static final String CONCURRENT_RUNS_ONEFLOW_WHITELIST = "azkaban.concurrent.runs.oneflow.whitelist"; public static final String WEBSERVER_QUEUE_SIZE = "azkaban.webserver.queue.size"; public static final String ACTIVE_EXECUTOR_REFRESH_IN_MS = "azkaban.activeexecutor.refresh.milisecinterval"; public static final String ACTIVE_EXECUTOR_REFRESH_IN_NUM_FLOW = "azkaban.activeexecutor.refresh.flowinterval"; public static final String EXECUTORINFO_REFRESH_MAX_THREADS = "azkaban.executorinfo.refresh.maxThreads"; public static final String MAX_DISPATCHING_ERRORS_PERMITTED = "azkaban.maxDispatchingErrors"; public static final String EXECUTOR_SELECTOR_FILTERS = "azkaban.executorselector.filters"; public static final String EXECUTOR_SELECTOR_COMPARATOR_PREFIX = "azkaban.executorselector.comparator."; public static final String QUEUEPROCESSING_ENABLED = "azkaban.queueprocessing.enabled"; public static final String SESSION_TIME_TO_LIVE = "session.time.to.live"; // allowed max number of sessions per user per IP public static final String MAX_SESSION_NUMBER_PER_IP_PER_USER = "azkaban.session" + ".max_number_per_ip_per_user"; // allowed max size of shared project dir (percentage of partition size), e.g 0.8 public static final String PROJECT_CACHE_SIZE_PERCENTAGE = "azkaban.project_cache_size_percentage_of_disk"; public static final String PROJECT_CACHE_THROTTLE_PERCENTAGE = "azkaban.project_cache_throttle_percentage"; // how many older versions of project files are kept in DB before deleting them public static final String PROJECT_VERSION_RETENTION = "project.version.retention"; // number of rows to be displayed on the executions page. public static final String DISPLAY_EXECUTION_PAGE_SIZE = "azkaban.display.execution_page_size"; // locked flow error message. Parameters passed in are the flow name and project name. public static final String AZKABAN_LOCKED_FLOW_ERROR_MESSAGE = "azkaban.locked.flow.error.message"; // flow ramp related setting keys // Default value to feature enable setting. To be backward compatible, this value === FALSE public static final String AZKABAN_RAMP_ENABLED = "azkaban.ramp.enabled"; // Due to multiple AzkabanExec Server instance scenario, it will be required to persistent the ramp result into the DB. // However, Frequent data persistence will sacrifice the performance with limited data accuracy. // This setting value controls to push result into DB every N finished ramped workflows public static final String AZKABAN_RAMP_STATUS_PUSH_INTERVAL_MAX = "azkaban.ramp.status.push.interval.max"; // Due to multiple AzkabanExec Server instance, it will be required to persistent the ramp result into the DB. // However, Frequent data persistence will sacrifice the performance with limited data accuracy. // This setting value controls to pull result from DB every N new ramped workflows public static final String AZKABAN_RAMP_STATUS_PULL_INTERVAL_MAX = "azkaban.ramp.status.pull.interval.max"; // A Polling Service can be applied to determine the ramp status synchronization interval. public static final String AZKABAN_RAMP_STATUS_POLLING_ENABLED = "azkaban.ramp.status.polling.enabled"; public static final String AZKABAN_RAMP_STATUS_POLLING_INTERVAL = "azkaban.ramp.status.polling.interval"; public static final String AZKABAN_RAMP_STATUS_POLLING_CPU_MAX = "azkaban.ramp.status.polling.cpu.max"; public static final String AZKABAN_RAMP_STATUS_POLLING_MEMORY_MIN = "azkaban.ramp.status.polling.memory.min"; public static final String EXECUTION_LOGS_RETENTION_MS = "execution.logs.retention.ms"; public static final String EXECUTION_LOGS_CLEANUP_INTERVAL_SECONDS = "execution.logs.cleanup.interval.seconds"; public static final String EXECUTION_LOGS_CLEANUP_RECORD_LIMIT = "execution.logs.cleanup.record.limit"; } public static class FlowProperties { // Basic properties of flows as set by the executor server public static final String AZKABAN_FLOW_PROJECT_NAME = "azkaban.flow.projectname"; public static final String AZKABAN_FLOW_FLOW_ID = "azkaban.flow.flowid"; public static final String AZKABAN_FLOW_SUBMIT_USER = "azkaban.flow.submituser"; public static final String AZKABAN_FLOW_EXEC_ID = "azkaban.flow.execid"; public static final String AZKABAN_FLOW_PROJECT_VERSION = "azkaban.flow.projectversion"; } public static class JobProperties { // Job property that enables/disables using Kafka logging of user job logs public static final String AZKABAN_JOB_LOGGING_KAFKA_ENABLE = "azkaban.job.logging.kafka.enable"; /* * this parameter is used to replace EXTRA_HCAT_LOCATION that could fail when one of the uris is not available. * EXTRA_HCAT_CLUSTERS has the following format: * other_hcat_clusters = "thrift://hcat1:port,thrift://hcat2:port;thrift://hcat3:port,thrift://hcat4:port" * Each string in the parenthesis is regarded as a "cluster", and we will get a delegation token from each cluster. * The uris(hcat servers) in a "cluster" ensures HA is provided. **/ public static final String EXTRA_HCAT_CLUSTERS = "azkaban.job.hive.other_hcat_clusters"; /* * the settings to be defined by user indicating if there are hcat locations other than the * default one the system should pre-fetch hcat token from. Note: Multiple thrift uris are * supported, use comma to separate the values, values are case insensitive. **/ // Use EXTRA_HCAT_CLUSTERS instead @Deprecated public static final String EXTRA_HCAT_LOCATION = "other_hcat_location"; // If true, AZ will fetches the jobs' certificate from remote Certificate Authority. public static final String ENABLE_JOB_SSL = "azkaban.job.enable.ssl"; // If true, AZ will fetch OAuth token from credential provider public static final String ENABLE_OAUTH = "azkaban.enable.oauth"; // Job properties that indicate maximum memory size public static final String JOB_MAX_XMS = "job.max.Xms"; public static final String MAX_XMS_DEFAULT = "1G"; public static final String JOB_MAX_XMX = "job.max.Xmx"; public static final String MAX_XMX_DEFAULT = "2G"; // The hadoop user the job should run under. If not specified, it will default to submit user. public static final String USER_TO_PROXY = "user.to.proxy"; /** * Format string for Log4j's EnhancedPatternLayout */ public static final String JOB_LOG_LAYOUT = "azkaban.job.log.layout"; } public static class JobCallbackProperties { public static final String JOBCALLBACK_CONNECTION_REQUEST_TIMEOUT = "jobcallback.connection.request.timeout"; public static final String JOBCALLBACK_CONNECTION_TIMEOUT = "jobcallback.connection.timeout"; public static final String JOBCALLBACK_SOCKET_TIMEOUT = "jobcallback.socket.timeout"; public static final String JOBCALLBACK_RESPONSE_WAIT_TIMEOUT = "jobcallback.response.wait.timeout"; public static final String JOBCALLBACK_THREAD_POOL_SIZE = "jobcallback.thread.pool.size"; } public static class FlowTriggerProps { // Flow trigger props public static final String SCHEDULE_TYPE = "type"; public static final String CRON_SCHEDULE_TYPE = "cron"; public static final String SCHEDULE_VALUE = "value"; public static final String DEP_NAME = "name"; // Flow trigger dependency run time props public static final String START_TIME = "startTime"; public static final String TRIGGER_INSTANCE_ID = "triggerInstanceId"; } public static class PluginManager { public static final String JOBTYPE_DEFAULTDIR = "plugins/jobtypes"; public static final String RAMPPOLICY_DEFAULTDIR = "plugins/ramppolicies"; // need jars.to.include property, will be loaded with user property public static final String CONFFILE = "plugin.properties"; // not exposed to users public static final String SYSCONFFILE = "private.properties"; // common properties for multiple plugins public static final String COMMONCONFFILE = "common.properties"; // common private properties for multiple plugins public static final String COMMONSYSCONFFILE = "commonprivate.properties"; } }
0
java-sources/ai/databand/azkaban/az-core/3.90.0/azkaban
java-sources/ai/databand/azkaban/az-core/3.90.0/azkaban/metrics/MetricsManager.java
/* * Copyright 2017 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://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. */ package azkaban.metrics; import static azkaban.Constants.ConfigurationKeys.CUSTOM_METRICS_REPORTER_CLASS_NAME; import static azkaban.Constants.ConfigurationKeys.METRICS_SERVER_URL; import azkaban.utils.Props; import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.Histogram; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.codahale.metrics.jvm.GarbageCollectorMetricSet; import com.codahale.metrics.jvm.MemoryUsageGaugeSet; import com.codahale.metrics.jvm.ThreadStatesGaugeSet; import java.lang.reflect.Constructor; import java.util.function.Supplier; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The singleton class, MetricsManager, is the place to have MetricRegistry and ConsoleReporter in * this class. Also, web servers and executors can call {@link #startReporting(String, Props)} to * start reporting AZ metrics to remote metrics server. */ @Singleton public class MetricsManager { private static final Logger log = LoggerFactory.getLogger(MetricsManager.class); private final MetricRegistry registry; @Inject public MetricsManager(final MetricRegistry registry) { this.registry = registry; registerJvmMetrics(); } private void registerJvmMetrics() { this.registry.register("MEMORY_Gauge", new MemoryUsageGaugeSet()); this.registry.register("GC_Gauge", new GarbageCollectorMetricSet()); this.registry.register("Thread_State_Gauge", new ThreadStatesGaugeSet()); } /** * A {@link Meter} measures the rate of events over time (e.g., “requests per second”). */ public Meter addMeter(final String name) { return this.registry.meter(name); } /** * A {@link Gauge} is an instantaneous reading of a particular value. This method leverages * Supplier, a Functional Interface, to get Generics metrics values. With this support, no matter * what our interesting metrics is a Double or a Long, we could pass it to Metrics Parser. * * E.g., in {@link CommonMetrics#setupAllMetrics()}, we construct a supplier lambda by having a * AtomicLong object and its get method, in order to collect dbConnection metric. */ public <T> void addGauge(final String name, final Supplier<T> gaugeFunc) { this.registry.register(name, (Gauge<T>) gaugeFunc::get); } /** * A {@link Counter} is just a gauge for an AtomicLong instance. */ public Counter addCounter(final String name) { return this.registry.counter(name); } /** * A {@link Histogram} measures the statistical distribution of values in a stream of data. In * addition to minimum, maximum, mean, etc., it also measures median, 75th, * 90th, 95th, 98th, 99th, and 99.9th percentiles. */ public Histogram addHistogram(final String name) { return this.registry.histogram(name); } /** * A {@link Timer} measures both the rate that a particular piece of code is called and the * distribution of its duration. */ public Timer addTimer(final String name) { return this.registry.timer(name); } /** * reporting metrics to remote metrics collector. Note: this method must be synchronized, since * both web server and executor will call it during initialization. */ public synchronized void startReporting(final String reporterName, final Props props) { final String metricsReporterClassName = props.get(CUSTOM_METRICS_REPORTER_CLASS_NAME); final String metricsServerURL = props.get(METRICS_SERVER_URL); if (metricsReporterClassName != null && metricsServerURL != null) { try { log.info("metricsReporterClassName: " + metricsReporterClassName); final Class metricsClass = Class.forName(metricsReporterClassName); final Constructor[] constructors = metricsClass.getConstructors(); constructors[0].newInstance(reporterName, this.registry, metricsServerURL); } catch (final Exception e) { log.error("Encountered error while loading and instantiating " + metricsReporterClassName, e); throw new IllegalStateException("Encountered error while loading and instantiating " + metricsReporterClassName, e); } } else { log.error(String.format("No value for property: %s or %s was found", CUSTOM_METRICS_REPORTER_CLASS_NAME, METRICS_SERVER_URL)); } } }
0
java-sources/ai/databand/azkaban/az-core/3.90.0/azkaban
java-sources/ai/databand/azkaban/az-core/3.90.0/azkaban/utils/ExecutorServiceUtils.java
/* * Copyright 2018 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://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. */ package azkaban.utils; import java.time.Duration; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Executor service related utilities. */ public class ExecutorServiceUtils { private static final Logger logger = LoggerFactory.getLogger(ExecutorServiceUtils.class); private static final TimeUnit MILLI_SECONDS_TIME_UNIT = TimeUnit.MILLISECONDS; /** * Gracefully shuts down the given executor service. * * <p>Adopted from * <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html"> * the Oracle JAVA Documentation. * </a> * * @param service the service to shutdown * @param timeout max wait time for the tasks to shutdown. Note that the max wait time is 2 * times this value due to the two stages shutdown strategy. * @throws InterruptedException if the current thread is interrupted */ public void gracefulShutdown(final ExecutorService service, final Duration timeout) throws InterruptedException { service.shutdown(); // Disable new tasks from being submitted final long timeout_in_unit_of_miliseconds = timeout.toMillis(); // Wait a while for existing tasks to terminate if (!service.awaitTermination(timeout_in_unit_of_miliseconds, MILLI_SECONDS_TIME_UNIT)) { service.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!service.awaitTermination(timeout_in_unit_of_miliseconds, MILLI_SECONDS_TIME_UNIT)) { logger.error("The executor service did not terminate."); } } } }