index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/request/RequestExtractor.java
|
package ai.agentscentral.http.request;
import jakarta.servlet.http.HttpServletRequest;
/**
* RequestExtractor
*
* @author Rizwan Idrees
*/
public interface RequestExtractor {
MessageRequest extract(HttpServletRequest request);
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/request/SessionIdExtractor.java
|
package ai.agentscentral.http.request;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;
/**
* SessionIdExtractor
*
* @author Rizwan Idrees
*/
public interface SessionIdExtractor {
Optional<String> extract(HttpServletRequest request);
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/request/TrailingRequestPathConversationIdExtractor.java
|
package ai.agentscentral.http.request;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import java.util.Optional;
import static org.apache.commons.lang3.StringUtils.*;
/**
* TrailingRequestPathConversationIdExtractor
*
* @author Rizwan Idrees
*/
public class TrailingRequestPathConversationIdExtractor implements SessionIdExtractor {
private static final String WILDCARD = "*";
private static final String SLASH = "/";
private final String path;
public TrailingRequestPathConversationIdExtractor(String path) {
this.path = cleanPath(path);
}
@Override
public Optional<String> extract(HttpServletRequest request) {
return extractConversationId(request.getRequestURI());
}
private Optional<String> extractConversationId(String requestUri) {
final String uri = endsWith(requestUri, SLASH)? requestUri : requestUri + SLASH;
return Optional.ofNullable(uri)
.map(this::removePath)
.map(this::removeSlash)
.filter(StringUtils::isNotBlank);
}
private String cleanPath(String path) {
final String pathWithoutWildCard = replaceEach(path, new String[]{WILDCARD}, new String[]{StringUtils.EMPTY});
return pathWithoutWildCard.endsWith(SLASH) ? pathWithoutWildCard : pathWithoutWildCard + SLASH;
}
private String removePath(String uriPath) {
return replaceEach(uriPath, new String[]{path}, new String[]{EMPTY});
}
private String removeSlash(String uriPath) {
return replaceEach(uriPath, new String[]{SLASH}, new String[]{EMPTY});
}
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/response/JsonResponseSender.java
|
package ai.agentscentral.http.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
/**
* JsonResponseSender
*
* @author Rizwan Idrees
*/
public class JsonResponseSender implements ResponseSender {
private static final String CONTENT_TYPE = "application/json";
private final ObjectMapper objectMapper;
public JsonResponseSender(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void send(HttpServletResponse response, MessageResponse messageResponse) {
response.setContentType(CONTENT_TYPE);
response.setStatus(SC_OK);
try (PrintWriter writer = response.getWriter()) {
objectMapper.writeValue(writer, messageResponse);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/response/Message.java
|
package ai.agentscentral.http.response;
public interface Message {
MessageType type();
String id();
long timestamp();
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/response/MessageResponse.java
|
package ai.agentscentral.http.response;
import jakarta.annotation.Nonnull;
import java.util.List;
/**
* MessageResponse
*
* @param sessionId
* @param messages
* @author Rizwan Idrees
*/
public record MessageResponse(@Nonnull String sessionId, @Nonnull List<? extends Message> messages) {
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/response/MessageType.java
|
package ai.agentscentral.http.response;
public enum MessageType {
text
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/response/ResponseSender.java
|
package ai.agentscentral.http.response;
import jakarta.servlet.http.HttpServletResponse;
/**
* ResponseSender
*
* @author Rizwan Idrees
*/
public interface ResponseSender {
void send(HttpServletResponse response, MessageResponse messageResponse);
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/response/TextMessage.java
|
package ai.agentscentral.http.response;
public record TextMessage(MessageType type, String id, String text, long timestamp) implements Message {
public MessageType type() {
return MessageType.text;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/runner/AgentJHttpRunner.java
|
package ai.agentscentral.http.runner;
/**
* AgentJHttpRunner
*
* @author Rizwan Idrees
*/
public interface AgentJHttpRunner {
void start() throws Exception;
void stop() throws Exception;
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/runner/AgentJStarter.java
|
package ai.agentscentral.http.runner;
import static ai.agentscentral.http.banner.Banner.printBanner;
/**
* AgentJStarter
*
* @author Rizwan Idrees
*/
public class AgentJStarter {
private AgentJStarter() {
}
public static void run(AgentJHttpRunner runner) throws Exception {
printBanner();
runner.start();
}
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/servlet/AgentJServlet.java
|
package ai.agentscentral.http.servlet;
import ai.agentscentral.core.session.id.MessageIdGenerator;
import ai.agentscentral.core.session.id.SessionIdGenerator;
import ai.agentscentral.core.session.message.*;
import ai.agentscentral.core.session.processor.SessionProcessor;
import ai.agentscentral.http.request.MessageRequest;
import ai.agentscentral.http.request.RequestExtractor;
import ai.agentscentral.http.request.SessionIdExtractor;
import ai.agentscentral.http.response.MessageResponse;
import ai.agentscentral.http.response.MessageType;
import ai.agentscentral.http.response.ResponseSender;
import ai.agentscentral.http.response.TextMessage;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static ai.agentscentral.core.session.message.MessagePartType.text;
import static java.lang.System.currentTimeMillis;
/**
* AgentJServlet
*
* @author Rizwan Idrees
*/
public class AgentJServlet extends HttpServlet {
private final SessionProcessor processor;
private final RequestExtractor requestExtractor;
private final ResponseSender responseSender;
private final SessionIdExtractor sessionIdExtractor;
private final SessionIdGenerator sessionIdGenerator;
private final MessageIdGenerator messageIdGenerator;
public AgentJServlet(SessionProcessor processor,
RequestExtractor requestExtractor,
ResponseSender responseSender,
SessionIdExtractor sessionIdExtractor,
SessionIdGenerator sessionIdGenerator,
MessageIdGenerator messageIdGenerator) {
this.processor = processor;
this.requestExtractor = requestExtractor;
this.responseSender = responseSender;
this.sessionIdExtractor = sessionIdExtractor;
this.sessionIdGenerator = sessionIdGenerator;
this.messageIdGenerator = messageIdGenerator;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
final MessageRequest messageRequest = requestExtractor.extract(request);
final String sessionId = sessionIdExtractor.extract(request)
.orElse(sessionIdGenerator.generate());
final List<AssistantMessage> assistantMessages = Optional.of(messageRequest)
.map(r -> new UserMessage(sessionId, messageId(), toTextParts(r), currentTimeMillis()))
.map(um -> processor.process(sessionId, um, null)).orElse(List.of());
final List<TextMessage> textMessages = assistantMessages.stream()
.map(am -> toTextMessage(am.messageId(), am.parts(), am.timestamp()))
.toList();
responseSender.send(response, new MessageResponse(sessionId, textMessages));
}
private String messageId() {
return messageIdGenerator.generate();
}
private TextMessage toTextMessage(String id, MessagePart[] parts, long timestamp) {
final String text = Stream.of(parts)
.filter(messagePart -> messagePart.type() == MessagePartType.text)
.map(t -> (TextPart) t)
.map(TextPart::text).collect(Collectors.joining());
return new TextMessage(MessageType.text, id, text, timestamp);
}
private static TextPart[] toTextParts(MessageRequest messageRequest) {
return new TextPart[]{new TextPart(text, messageRequest.message())};
}
}
|
0
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http
|
java-sources/ai/agentscentral/agentj-http/0.0.5/ai/agentscentral/http/servlet/HealthCheckServlet.java
|
package ai.agentscentral.http.servlet;
import ai.agentscentral.http.health.LivenessProbe;
import ai.agentscentral.http.health.ReadinessProbe;
import ai.agentscentral.http.health.response.HealthCheckResponse;
import ai.agentscentral.http.health.response.LivenessResponse;
import ai.agentscentral.http.health.response.ReadinessResponse;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.IntStream;
import static ai.agentscentral.http.json.Jsonify.asJson;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static org.apache.commons.lang3.StringUtils.endsWithIgnoreCase;
/**
* HealthCheckServlet
*
* @author Rizwan Idrees
*/
public class HealthCheckServlet extends HttpServlet {
private static final String CONTENT_TYPE = "application/json";
private final LivenessProbe livenessProbe;
private final ReadinessProbe readinessProbe;
public HealthCheckServlet(LivenessProbe livenessProbe, ReadinessProbe readinessProbe) {
this.livenessProbe = livenessProbe;
this.readinessProbe = readinessProbe;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
if (endsWithIgnoreCase(request.getRequestURI(), "/liveness")) {
doLivenessCheck(response);
} else if (endsWithIgnoreCase(request.getRequestURI(), "/readiness")) {
doReadinessCheck(response);
}
doHealthCheck(response);
}
void doHealthCheck(HttpServletResponse response) throws IOException {
final LivenessResponse liveness = livenessProbe.probe();
final ReadinessResponse readiness = readinessProbe.probe();
final int status = IntStream.of(liveness.getHttpStatus(), readiness.getHttpStatus()).filter(s -> s != SC_OK)
.findFirst().orElse(SC_OK);
final HealthCheckResponse healthCheckResponse = new HealthCheckResponse(liveness.getBody(),
readiness.getBody());
response.setContentType(CONTENT_TYPE);
response.setStatus(status);
try (PrintWriter writer = response.getWriter()) {
writer.println(asJson(healthCheckResponse));
}
}
void doLivenessCheck(HttpServletResponse response) throws IOException {
final LivenessResponse liveness = livenessProbe.probe();
response.setContentType(CONTENT_TYPE);
response.setStatus(liveness.getHttpStatus());
try (PrintWriter writer = response.getWriter()) {
writer.println(asJson(liveness.getBody()));
}
}
void doReadinessCheck(HttpServletResponse response) throws IOException {
final ReadinessResponse readinessResponse = readinessProbe.probe();
response.setContentType(CONTENT_TYPE);
response.setStatus(readinessResponse.getHttpStatus());
try (PrintWriter writer = response.getWriter()) {
writer.println(asJson(readinessResponse.getBody()));
}
}
}
|
0
|
java-sources/ai/agentscentral/agentj-jetty/0.0.5/ai/agentscentral/jetty
|
java-sources/ai/agentscentral/agentj-jetty/0.0.5/ai/agentscentral/jetty/config/JettyConfig.java
|
package ai.agentscentral.jetty.config;
/**
* JettyConfig
*
* @param port
* @param maxVirtualThreads
* @param reservedThreads
* @author Rizwan Idrees
*/
public record JettyConfig(int port, int maxVirtualThreads, int reservedThreads) {
public static JettyConfig defaultJettyConfig() {
return new JettyConfig(8181, 128, 2);
}
}
|
0
|
java-sources/ai/agentscentral/agentj-jetty/0.0.5/ai/agentscentral/jetty
|
java-sources/ai/agentscentral/agentj-jetty/0.0.5/ai/agentscentral/jetty/runner/JettyHttpRunner.java
|
package ai.agentscentral.jetty.runner;
import ai.agentscentral.core.context.InMemoryContextManager;
import ai.agentscentral.core.context.InMemoryContextStateManager;
import ai.agentscentral.core.factory.AgentJFactory;
import ai.agentscentral.core.factory.DefaultAgentJFactory;
import ai.agentscentral.core.session.processor.DefaultSessionProcessor;
import ai.agentscentral.http.config.AgentJConfig;
import ai.agentscentral.http.config.HttpConfig;
import ai.agentscentral.http.filter.AgentJAuthorizationFilter;
import ai.agentscentral.http.health.LivenessProbe;
import ai.agentscentral.http.health.ReadinessProbe;
import ai.agentscentral.http.request.JsonRequestExtractor;
import ai.agentscentral.http.request.TrailingRequestPathConversationIdExtractor;
import ai.agentscentral.http.response.JsonResponseSender;
import ai.agentscentral.http.runner.AgentJHttpRunner;
import ai.agentscentral.http.servlet.AgentJServlet;
import ai.agentscentral.http.servlet.HealthCheckServlet;
import ai.agentscentral.jetty.config.JettyConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.DispatcherType;
import org.eclipse.jetty.ee10.servlet.ServletContextHandler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.VirtualThreadPool;
import java.util.EnumSet;
import java.util.Objects;
import java.util.concurrent.Executors;
import static ai.agentscentral.core.session.config.ExecutionLimits.defaultExecutionLimits;
/**
* JettyHttpRunner
* Jetty implementation of AgentJHttpRunner
*
* @author Rizwan Idrees
*/
public class JettyHttpRunner implements AgentJHttpRunner {
private final JettyConfig jettyConfig;
private final AgentJConfig agentJConfig;
private final Server server;
public JettyHttpRunner(JettyConfig jettyConfig, AgentJConfig agentJConfig) {
this.jettyConfig = jettyConfig;
this.agentJConfig = agentJConfig;
this.server = new Server(queuedThreadPool());
}
@Override
public void start() throws Exception {
final HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(new HttpConfiguration());
final ServletContextHandler servletContextHandler = new ServletContextHandler();
addHttpAgentSystems(servletContextHandler);
addHealthChecks(servletContextHandler);
server.setHandler(servletContextHandler);
try (ServerConnector connector = new ServerConnector(server, httpConnectionFactory)) {
connector.setPort(jettyConfig.port());
server.addConnector(connector);
}
server.setStopAtShutdown(true);
server.start();
}
private QueuedThreadPool queuedThreadPool() {
final QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setVirtualThreadsExecutor(Executors.newVirtualThreadPerTaskExecutor());
VirtualThreadPool virtualExecutor = new VirtualThreadPool();
virtualExecutor.setMaxThreads(jettyConfig.maxVirtualThreads());
threadPool.setVirtualThreadsExecutor(virtualExecutor);
threadPool.setReservedThreads(jettyConfig.reservedThreads());
return threadPool;
}
private void addHealthChecks(ServletContextHandler servletContextHandler) {
final LivenessProbe livenessProbe = new LivenessProbe() {
};
final ReadinessProbe readinessProbe = new ReadinessProbe() {
};
servletContextHandler.addServlet(new HealthCheckServlet(livenessProbe, readinessProbe), "/health/*");
}
private void addHttpAgentSystems(ServletContextHandler servletContextHandler) {
for (HttpConfig httpConfig : agentJConfig.httpConfigs()) {
AgentJFactory agentJFactory = DefaultAgentJFactory.getInstance();
final DefaultSessionProcessor processor = new DefaultSessionProcessor(httpConfig.agentic(),
agentJFactory,
new InMemoryContextStateManager(),
new InMemoryContextManager(), defaultExecutionLimits());
final ObjectMapper objectMapper = new ObjectMapper(); //TODO use singleton object mapper
final AgentJServlet servlet = new AgentJServlet(processor,
new JsonRequestExtractor(objectMapper),
new JsonResponseSender(objectMapper),
new TrailingRequestPathConversationIdExtractor(httpConfig.path()),
agentJFactory.getSessionIdGenerator(),
agentJFactory.getMessageIdGenerator());
servletContextHandler.addServlet(servlet, httpConfig.path());
servletContextHandler.addFilter(new AgentJAuthorizationFilter(httpConfig.authorizers()),
httpConfig.path(), EnumSet.of(DispatcherType.REQUEST));
}
}
@Override
public void stop() throws Exception {
if (Objects.nonNull(server)) {
server.stop();
}
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/Jsonify.java
|
package ai.agentscentral.openai.client;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Jsonify
*
* @author Rizwan Idrees
*/
class Jsonify {
private static final ObjectMapper mapper = new ObjectMapper() {{
setSerializationInclusion(JsonInclude.Include.NON_NULL);
}};
private Jsonify() {
}
static String asJson(Object o) throws JsonProcessingException {
return mapper.writeValueAsString(o);
}
static <T> T asObject(String stringValue, Class<T> clazz) throws JsonProcessingException {
return mapper.readValue(stringValue, clazz);
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/OpenAIClient.java
|
package ai.agentscentral.openai.client;
import ai.agentscentral.core.model.ProviderClient;
import ai.agentscentral.openai.client.request.CompletionRequest;
import ai.agentscentral.openai.client.response.CompletionResponse;
import org.apache.hc.client5.http.HttpResponseException;
import java.io.IOException;
import static ai.agentscentral.openai.client.Jsonify.asJson;
import static org.apache.hc.client5.http.fluent.Request.post;
import static org.apache.hc.core5.http.ContentType.APPLICATION_JSON;
import static org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION;
import static org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE;
/**
* OpenAIClient
*
* @author Rizwan Idrees
*/
public class OpenAIClient implements ProviderClient {
public static final String BEARER = "Bearer ";
private final String url;
private final String authorization;
public OpenAIClient(String url, String apiKey) {
this.url = url;
this.authorization = BEARER + apiKey;
}
public CompletionResponse complete(CompletionRequest request) {
try {
final String responseAsString = post(url)
.addHeader(AUTHORIZATION, authorization)
.addHeader(CONTENT_TYPE, APPLICATION_JSON.getMimeType())
.bodyString(asJson(request), APPLICATION_JSON)
.execute().returnContent().asString();
return Jsonify.asObject(responseAsString, CompletionResponse.class);
} catch (HttpResponseException e) {
e.printStackTrace();
//todo:: better error handling
throw new RuntimeException(e);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/CompletionRequest.java
|
package ai.agentscentral.openai.client.request;
import ai.agentscentral.openai.client.request.attributes.*;
import ai.agentscentral.openai.config.OpenAIConfig;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import jakarta.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import static java.util.Objects.nonNull;
/**
* CompletionRequest
*
* @param messages
* @param model
* @param frequencyPenalty
* @param logitBias
* @param logProbs
* @param maxCompletionTokens
* @param modalities
* @param n
* @param parallelToolCalls
* @param presencePenalty
* @param responseFormat
* @param seed
* @param serviceTier
* @param stop
* @param store
* @param stream
* @param streamOptions
* @param temperature
* @param toolChoice
* @param tools
* @param topLogprobs
* @param topP
* @param user
* @param webSearchOptions
*
* @author Rizwan Idrees
*/
public record CompletionRequest(List<OpenAIMessage> messages,
@Nonnull String model,
@JsonProperty("frequency_penalty") Double frequencyPenalty,
@JsonProperty("logit_bias") Map<Integer, Integer> logitBias,
@JsonProperty("logprobs") Boolean logProbs,
@JsonProperty("max_completion_tokens") Integer maxCompletionTokens,
List<String> modalities,
Integer n,
@JsonProperty("parallel_tool_calls") Boolean parallelToolCalls,
@JsonProperty("presence_penalty") Double presencePenalty,
@JsonProperty("response_format") ResponseFormat responseFormat,
Integer seed,
@JsonProperty("service_tier") String serviceTier,
List<String> stop,
Boolean store,
Boolean stream,
@JsonProperty("stream_options") StreamOptions streamOptions,
Double temperature,
@JsonProperty("tool_choice") @JsonUnwrapped ToolChoice toolChoice,
List<OpenAITool> tools,
@JsonProperty("top_logprobs") Integer topLogprobs,
@JsonProperty("top_p") Double topP,
String user,
@JsonProperty("web_search_options") WebSearchOptions webSearchOptions
) {
public static CompletionRequest from(String model,
OpenAIConfig config,
String user,
List<OpenAITool> tools,
List<OpenAIMessage> messages){
return new CompletionRequest(
messages,
model,
config.getFrequencyPenalty(),
config.getLogitBias(),
config.getLogprobs(),
config.getMaxCompletionTokens(),
config.getModalities(),
config.getN(),
config.isParallelToolCalls(),
config.getPresencePenalty(),
config.getResponseFormat(),
config.getSeed(),
config.getServiceTier(),
config.getStop(),
config.getStore(),
config.getStream(),
nonNull(config.getStream()) && config.getStream()? new StreamOptions(config.isIncludeUsage()) : null,
config.getTemperature(),
config.getToolChoice(),
tools,
config.getTopLogprobs(),
config.getTopP(),
user,
config.getWebSearchOptions()
);
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ApproximateLocation.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ApproximateLocation
*
* @param city
* @param country
* @param region
* @param timezone
* @author Rizwan Idrees
*/
public record ApproximateLocation(String city, String country, String region, String timezone) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ContentPart.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ContentPart
*
* @author Rizwan Idrees
*/
public interface ContentPart {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/EnumFunctionProperty.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* EnumFunctionProperty
*
* @param type
* @param enums
* @author Rizwan Idrees
*/
public record EnumFunctionProperty(String type, String[] enums) implements FunctionProperty {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/FunctionParameters.java
|
package ai.agentscentral.openai.client.request.attributes;
import java.util.Map;
import java.util.Set;
/**
* FunctionParameters
*
* @param type
* @param properties
* @param required
* @author Rizwan Idrees
*/
public record FunctionParameters(String type,
Map<String, ? extends FunctionProperty> properties,
Set<String> required) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/FunctionProperty.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* FunctionProperty
*
* @author Rizwan Idrees
*/
public interface FunctionProperty {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/JSONSchemaResponseFormat.java
|
package ai.agentscentral.openai.client.request.attributes;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* JSONSchemaResponseFormat
* @param type
* @param jsonSchema
*
* @author Rizwan Idrees
*/
public record JSONSchemaResponseFormat(String type,
@JsonProperty("json_schema") String jsonSchema) implements ResponseFormat {
private static final String JSON_SCHEMA = "json_schema";
@Override
public String type() {
return JSON_SCHEMA;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/MessageContent.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* MessageContent
*
* @author Rizwan Idrees
*/
public interface MessageContent {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/MessageContents.java
|
package ai.agentscentral.openai.client.request.attributes;
import java.util.List;
/**
* TextContents
*
* @param content
* @author Rizwan Idrees
*/
public record MessageContents(List<ContentPart> content) implements MessageContent {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/OpenAIAssistantMessage.java
|
package ai.agentscentral.openai.client.request.attributes;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import java.util.List;
/**
* OpenAIAssistantMessage
* @param role
* @param content
* @param name
* @param refusal
* @param toolCalls
*
* @author Rizwan Idrees
*/
public record OpenAIAssistantMessage(String role,
@JsonUnwrapped MessageContent content,
String name,
String refusal,
@JsonProperty("tool_calls") List<OpenAIToolCall> toolCalls) implements OpenAIMessage {
public static final String ASSISTANT = "assistant";
@Override
public String role() {
return ASSISTANT;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/OpenAIDeveloperMessage.java
|
package ai.agentscentral.openai.client.request.attributes;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
/**
* OpenAIDeveloperMessage
*
* @param role
* @param name
* @param content
* @author Rizwan Idrees
*/
public record OpenAIDeveloperMessage(String role, String name,
@JsonUnwrapped MessageContent content) implements OpenAIMessage {
public static final String DEVELOPER = "developer";
public String role() {
return DEVELOPER;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/OpenAIMessage.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* OpenAIMessage
*
* @author Rizwan Idrees
*/
public interface OpenAIMessage {
String role();
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/OpenAITool.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* OpenAITool
*
* @param type
* @param function
* @author Rizwan Idrees
*/
public record OpenAITool(String type, ToolFunction function) {
public static final String FUNCTION = "function";
@Override
public String type() {
return FUNCTION;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/OpenAIToolCall.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* OpenAIToolCall
* @param id
* @param type
* @param function
* @author Rizwan Idrees
*/
public record OpenAIToolCall(String id, String type, ToolCallFunction function) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/OpenAIToolMessage.java
|
package ai.agentscentral.openai.client.request.attributes;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
/**
* OpenAIToolMessage
*
* @param role
* @param toolCallId
* @param content
* @author Rizwan Idrees
*/
public record OpenAIToolMessage(String role,
@JsonProperty("tool_call_id") String toolCallId,
@JsonUnwrapped MessageContent content) implements OpenAIMessage {
public static final String TOOL = "tool";
@Override
public String role() {
return TOOL;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/OpenAIUserMessage.java
|
package ai.agentscentral.openai.client.request.attributes;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
/**
* OpenAIUserMessage
*
* @param role
* @param name
* @param content
* @author Rizwan Idrees
*/
public record OpenAIUserMessage(String role,
String name,
@JsonUnwrapped MessageContent content) implements OpenAIMessage {
public static final String USER = "user";
public String role() {
return USER;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ReasoningEffort.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ReasoningEffort
*
* @author Rizwan Idrees
*/
public enum ReasoningEffort {
low, medium, high
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/RefusalContentPart.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* RefusalContentPart
*
* @param type
* @param refusal
* @author Rizwan Idrees
*/
public record RefusalContentPart(String type, String refusal) implements ContentPart {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ResponseFormat.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ResponseFormat
*
* @author Rizwan Idrees
*/
public interface ResponseFormat {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/SearchContextSize.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* SearchContextSize
*
* @author Rizwan Idrees
*/
public enum SearchContextSize {
low, medium, high
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/StreamOptions.java
|
package ai.agentscentral.openai.client.request.attributes;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* StreamOptions
*
* @param includeUsage
* @author Rizwan Idrees
*/
public record StreamOptions(@JsonProperty("include_usage") boolean includeUsage) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/TextContent.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* TextContent
*
* @param content
* @author Rizwan Idrees
*/
public record TextContent(String content) implements MessageContent {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/TextContentPart.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* TextContentPart
*
* @param type
* @param text
* @author Rizwan Idrees
*/
public record TextContentPart(String type, String text) implements ContentPart {
public static final String TEXT = "text";
public String type() {
return TEXT;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/TextResponseFormat.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* TextResponseFormat
*
* @param type
* @author Rizwan Idrees
*/
public record TextResponseFormat(String type) implements ResponseFormat {
private static final String TEXT = "text";
@Override
public String type() {
return TEXT;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ToolCallFunction.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ToolCallFunction
*
* @param name
* @param arguments
* @author Rizwan Idrees
*/
public record ToolCallFunction(String name, String arguments) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ToolChoice.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ToolChoice
*
* @author Rizwan Idrees
*/
public interface ToolChoice {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ToolChoiceFunction.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ToolChoiceFunction
*
* @param name
*/
public record ToolChoiceFunction(String name) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ToolChoiceFunctionCall.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ToolChoiceFunctionCall
*
* @param type
* @param function
* @author Rizwan Idrees
*/
public record ToolChoiceFunctionCall(String type, ToolChoiceFunction function) implements ToolChoice {
private static final String FUNCTION = "function";
@Override
public String type() {
return FUNCTION;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ToolChoiceMode.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ToolChoiceMode
*
* @author Rizwan Idrees
*/
public enum ToolChoiceMode implements ToolChoice {
auto, none
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/ToolFunction.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* ToolFunction
*
* @param name
* @param description
* @param parameters
* @param strict
* @author Rizwan Idrees
*/
public record ToolFunction(String name,
String description,
FunctionParameters parameters,
Boolean strict) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/TypedFunctionProperty.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* TypedFunctionProperty
*
* @param type
* @param description
* @author Rizwan Idrees
*/
public record TypedFunctionProperty(String type, String description) implements FunctionProperty {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/UserLocation.java
|
package ai.agentscentral.openai.client.request.attributes;
/**
* UserLocation
*
* @param type
* @param approximate
* @author Rizwan Idrees
*/
public record UserLocation(String type, ApproximateLocation approximate) {
private static final String APPROXIMATE = "approximate";
@Override
public String type() {
return APPROXIMATE;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/request/attributes/WebSearchOptions.java
|
package ai.agentscentral.openai.client.request.attributes;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* WebSearchOptions
*
* @param searchContextSize
* @param userLocation
* @author Rizwan Idrees
*/
public record WebSearchOptions(@JsonProperty("search_context_size") SearchContextSize searchContextSize,
@JsonProperty("user_location") UserLocation userLocation) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/CompletionResponse.java
|
package ai.agentscentral.openai.client.response;
import ai.agentscentral.openai.client.response.parameters.Choice;
import ai.agentscentral.openai.client.response.parameters.Usage;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/**
* CompletionResponse
*
* @param id
* @param object
* @param created
* @param model
* @param choices
* @param serviceTier
* @param systemFingerprint
* @param usage
* @author Rizwan Idrees
*/
public record CompletionResponse(String id,
String object,
Long created,
String model,
List<Choice> choices,
@JsonProperty("service_tier") String serviceTier,
@JsonProperty("system_fingerprint") String systemFingerprint,
Usage usage) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/Annotation.java
|
package ai.agentscentral.openai.client.response.parameters;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Annotation
*
* @param type
* @param urlCitation
* @author Rizwan Idrees
*/
public record Annotation(String type, @JsonProperty("url_citation") UrlCitation urlCitation) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/Choice.java
|
package ai.agentscentral.openai.client.response.parameters;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Choice
*
* @param index
* @param finishReason
* @param logProbs
* @param message
* @author Rizwan Idrees
*/
public record Choice(@JsonProperty("index") Integer index,
@JsonProperty("finish_reason") String finishReason,
@JsonProperty("logprobs") LogProbs logProbs,
ChoiceMessage message
) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/ChoiceMessage.java
|
package ai.agentscentral.openai.client.response.parameters;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Objects;
/**
* ChoiceMessage
*
* @param content
* @param refusal
* @param role
* @param annotations
* @param toolCalls
* @author Rizwan Idrees
*/
public record ChoiceMessage(String content,
String refusal,
String role,
List<Annotation> annotations,
@JsonProperty("tool_calls") List<ToolCall> toolCalls) {
public boolean hasToolCalls() {
return Objects.nonNull(toolCalls) && !toolCalls.isEmpty();
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/CompletionTokenDetails.java
|
package ai.agentscentral.openai.client.response.parameters;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* CompletionTokenDetails
*
* @param acceptedPredictionTokens
* @param audioTokens
* @param reasoningTokens
* @param rejectedPredictionTokens
* @author Rizwan Idrees
*/
public record CompletionTokenDetails(@JsonProperty("accepted_prediction_tokens") Integer acceptedPredictionTokens,
@JsonProperty("audio_tokens") Integer audioTokens,
@JsonProperty("reasoning_tokens") Integer reasoningTokens,
@JsonProperty("rejected_prediction_tokens") Integer rejectedPredictionTokens) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/Function.java
|
package ai.agentscentral.openai.client.response.parameters;
/**
* Function
*
* @param name
* @param arguments
* @author Rizwan Idrees
*/
public record Function(String name, String arguments) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/LogProb.java
|
package ai.agentscentral.openai.client.response.parameters;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/**
* LogProb
*
* @param bytes
* @param logprob
* @param token
* @param top_logprobs
* @author Rizwan Idrees
*/
public record LogProb(byte[] bytes,
Integer logprob,
String token,
@JsonProperty("top_logprobs") List<LogProb> top_logprobs) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/LogProbs.java
|
package ai.agentscentral.openai.client.response.parameters;
/**
* LogProbs
*
* @param content
* @param refusal
* @author Rizwan Idrees
*/
public record LogProbs(LogProb content, LogProb refusal) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/PromptTokenDetails.java
|
package ai.agentscentral.openai.client.response.parameters;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* PromptTokenDetails
*
* @param audioTokens
* @param cachedTokens
* @author Rizwan Idrees
*/
public record PromptTokenDetails(@JsonProperty("audio_tokens") Integer audioTokens,
@JsonProperty("cached_tokens") Integer cachedTokens) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/ToolCall.java
|
package ai.agentscentral.openai.client.response.parameters;
/**
* ToolCall
*
* @param id
* @param type
* @param function
* @author Rizwan Idrees
*/
public record ToolCall(String id, String type, Function function) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/UrlCitation.java
|
package ai.agentscentral.openai.client.response.parameters;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* UrlCitation
*
* @param endIndex
* @param startIndex
* @param title
* @param url
* @author Rizwan Idrees
*/
public record UrlCitation(@JsonProperty("end_index") Integer endIndex,
@JsonProperty("start_index") Integer startIndex,
String title,
String url) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/client/response/parameters/Usage.java
|
package ai.agentscentral.openai.client.response.parameters;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Usage
*
* @param completionTokens
* @param promptTokens
* @param totalTokens
* @param completionTokensDetails
* @param promptTokensDetails
* @author Rizwan Idrees
*/
public record Usage(@JsonProperty("completion_tokens") Integer completionTokens,
@JsonProperty("prompt_tokens") Integer promptTokens,
@JsonProperty("total_tokens") Integer totalTokens,
@JsonProperty("completion_tokens_details") CompletionTokenDetails completionTokensDetails,
@JsonProperty("prompt_tokens_details") PromptTokenDetails promptTokensDetails) {
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/config/OpenAIConfig.java
|
package ai.agentscentral.openai.config;
import ai.agentscentral.core.model.ModelConfig;
import ai.agentscentral.core.model.ProviderFactory;
import ai.agentscentral.core.provider.ProviderAgentExecutor;
import ai.agentscentral.openai.client.OpenAIClient;
import ai.agentscentral.openai.client.request.attributes.ResponseFormat;
import ai.agentscentral.openai.client.request.attributes.ToolChoice;
import ai.agentscentral.openai.client.request.attributes.WebSearchOptions;
import ai.agentscentral.openai.factory.OpenAIFactory;
import java.util.List;
import java.util.Map;
import static java.util.Optional.ofNullable;
/**
* OpenAIConfig
*
* @author Rizwan Idrees
*/
public class OpenAIConfig implements ModelConfig {
private OpenAIFactory factory;
private String url = "https://api.openai.com/v1/chat/completions";
private String apiKey;
private Double frequencyPenalty;
private Map<Integer, Integer> logitBias;
private Boolean logprobs;
private Integer maxCompletionTokens;
private List<String> modalities;
private Integer n;
private Boolean parallelToolCalls;
private Double presencePenalty;
private ResponseFormat responseFormat;
private Integer seed;
private String serviceTier;
private List<String> stop;
private Boolean store;
private Boolean stream;
private Double temperature;
private Boolean includeUsage;
private ToolChoice toolChoice;
private Integer topLogprobs;
private Double topP;
private WebSearchOptions webSearchOptions;
public OpenAIConfig(String apiKey) {
this.apiKey = apiKey;
}
public OpenAIConfig(Double temperature, String apiKey) {
this(apiKey);
this.temperature = temperature;
}
public OpenAIConfig(Double temperature, String apiKey, String url) {
this(temperature, apiKey);
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public Double getFrequencyPenalty() {
return frequencyPenalty;
}
public void setFrequencyPenalty(Double frequencyPenalty) {
this.frequencyPenalty = frequencyPenalty;
}
public Map<Integer, Integer> getLogitBias() {
return logitBias;
}
public void setLogitBias(Map<Integer, Integer> logitBias) {
this.logitBias = logitBias;
}
public Boolean getLogprobs() {
return logprobs;
}
public void setLogprobs(Boolean logprobs) {
this.logprobs = logprobs;
}
public Integer getMaxCompletionTokens() {
return maxCompletionTokens;
}
public void setMaxCompletionTokens(Integer maxCompletionTokens) {
this.maxCompletionTokens = maxCompletionTokens;
}
public List<String> getModalities() {
return modalities;
}
public void setModalities(List<String> modalities) {
this.modalities = modalities;
}
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public Boolean isParallelToolCalls() {
return parallelToolCalls;
}
public void setParallelToolCalls(Boolean parallelToolCalls) {
this.parallelToolCalls = parallelToolCalls;
}
public Double getPresencePenalty() {
return presencePenalty;
}
public void setPresencePenalty(Double presencePenalty) {
this.presencePenalty = presencePenalty;
}
public ResponseFormat getResponseFormat() {
return responseFormat;
}
public void setResponseFormat(ResponseFormat responseFormat) {
this.responseFormat = responseFormat;
}
public Integer getSeed() {
return seed;
}
public void setSeed(Integer seed) {
this.seed = seed;
}
public String getServiceTier() {
return serviceTier;
}
public void setServiceTier(String serviceTier) {
this.serviceTier = serviceTier;
}
public List<String> getStop() {
return stop;
}
public void setStop(List<String> stop) {
this.stop = stop;
}
public Boolean getStore() {
return store;
}
public void setStore(Boolean store) {
this.store = store;
}
public Boolean getStream() {
return stream;
}
public void setStream(Boolean stream) {
this.stream = stream;
}
public Double getTemperature() {
return temperature;
}
public void setTemperature(Double temperature) {
this.temperature = temperature;
}
public Boolean isIncludeUsage() {
return includeUsage;
}
public void setIncludeUsage(Boolean includeUsage) {
this.includeUsage = includeUsage;
}
public ToolChoice getToolChoice() {
return toolChoice;
}
public void setToolChoice(ToolChoice toolChoice) {
this.toolChoice = toolChoice;
}
public Integer getTopLogprobs() {
return topLogprobs;
}
public void setTopLogprobs(Integer topLogprobs) {
this.topLogprobs = topLogprobs;
}
public Double getTopP() {
return topP;
}
public void setTopP(Double topP) {
this.topP = topP;
}
public WebSearchOptions getWebSearchOptions() {
return webSearchOptions;
}
public void setWebSearchOptions(WebSearchOptions webSearchOptions) {
this.webSearchOptions = webSearchOptions;
}
@Override
public ProviderFactory<? extends ProviderAgentExecutor> getFactory() {
factory = ofNullable(factory).orElseGet(() -> new OpenAIFactory(new OpenAIClient(this.url, this.apiKey)));
return factory;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/factory/OpenAIFactory.java
|
package ai.agentscentral.openai.factory;
import ai.agentscentral.core.agent.Agent;
import ai.agentscentral.core.factory.AgentJFactory;
import ai.agentscentral.core.model.ProviderFactory;
import ai.agentscentral.openai.client.OpenAIClient;
import ai.agentscentral.openai.processor.OpenAIAgentExecutor;
import jakarta.annotation.Nonnull;
import java.util.Optional;
/**
* OpenAIFactory
*
* @author Rizwan Idrees
*/
public class OpenAIFactory implements ProviderFactory<OpenAIAgentExecutor> {
private final OpenAIClient client;
public OpenAIFactory(OpenAIClient client) {
this.client = client;
}
@Override
public OpenAIAgentExecutor createAgentExecutor(@Nonnull Agent agent, @Nonnull AgentJFactory agentJFactory) {
return Optional.of(agent)
.map(a -> new OpenAIAgentExecutor(a, agentJFactory, client))
.orElseThrow(() -> new RuntimeException("Cannot process agent of type " + agent.getClass()));
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/processor/ArgumentExtractor.java
|
package ai.agentscentral.openai.processor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
/**
* ArgumentExtractor
*
* @author Rizwan Idrees
*/
class ArgumentExtractor {
private static final ObjectMapper mapper = new ObjectMapper();
private ArgumentExtractor() {
}
static Map<String, Object> extractFromJson(String json) {
if (StringUtils.isBlank(json)) {
return Map.of();
}
try {
return mapper.readValue(json, new TypeReference<>() {
});
} catch (JsonProcessingException e) {
return Map.of();
}
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/processor/MessageConvertor.java
|
package ai.agentscentral.openai.processor;
import ai.agentscentral.core.handoff.DefaultHandoffInstruction;
import ai.agentscentral.core.handoff.Handoff;
import ai.agentscentral.core.handoff.HandoffInstruction;
import ai.agentscentral.core.session.message.*;
import ai.agentscentral.core.tool.DefaultToolCallInstruction;
import ai.agentscentral.core.tool.ToolCallInstruction;
import ai.agentscentral.openai.client.request.attributes.*;
import ai.agentscentral.openai.client.response.parameters.ChoiceMessage;
import ai.agentscentral.openai.client.response.parameters.Function;
import ai.agentscentral.openai.client.response.parameters.ToolCall;
import jakarta.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
import static ai.agentscentral.core.session.message.MessagePartType.text;
import static ai.agentscentral.openai.client.request.attributes.OpenAIAssistantMessage.ASSISTANT;
import static ai.agentscentral.openai.client.request.attributes.OpenAIDeveloperMessage.DEVELOPER;
import static ai.agentscentral.openai.client.request.attributes.OpenAIToolMessage.TOOL;
import static ai.agentscentral.openai.client.request.attributes.OpenAIUserMessage.USER;
import static ai.agentscentral.openai.processor.ArgumentExtractor.extractFromJson;
import static java.util.stream.Collectors.joining;
import static org.apache.commons.lang3.StringUtils.EMPTY;
/**
* MessageConvertor
*
* @author Rizwan Idrees
*/
class MessageConvertor {
private final Map<String, ai.agentscentral.core.tool.ToolCall> tools;
private final Map<String, Handoff> handOffs;
public MessageConvertor(Map<String, ai.agentscentral.core.tool.ToolCall> tools,
Map<String, Handoff> handOffs) {
this.tools = tools;
this.handOffs = handOffs;
}
List<OpenAIMessage> toOpenAIMessages(DeveloperMessage message, List<Message> messages) {
final List<OpenAIMessage> context = messages.stream().map(this::toOpenAIMessage).toList();
final OpenAIMessage agentContext = toOpenAIMessage(message);
final List<OpenAIMessage> fullContext = new ArrayList<>();
fullContext.add(agentContext);
fullContext.addAll(context);
return fullContext;
}
AssistantMessage toAssistantMessage(String contextId, String responseId, List<ChoiceMessage> messages, Long created) {
final List<ChoiceMessage> assistantMessages = messages.stream().filter(m -> m.role().equals("assistant"))
.toList();
final List<TextPart> textParts = assistantMessages.stream().map(ChoiceMessage::content).filter(StringUtils::isNotBlank)
.map(c -> new TextPart(text, c)).toList();
final TextPart[] parts = textParts.isEmpty() ? null : textParts.toArray(new TextPart[0]);
final List<ToolCall> choiceToolCalls = assistantMessages.stream().filter(ChoiceMessage::hasToolCalls)
.flatMap(m -> m.toolCalls().stream())
.toList();
final List<ToolCallInstruction> toolCalls = choiceToolCalls.isEmpty() ?
List.of() : toToolCallInstructions(choiceToolCalls);
final List<HandoffInstruction> handoffCalls = choiceToolCalls.isEmpty() ?
List.of() : toHandOffs(choiceToolCalls);
return new AssistantMessage(contextId, responseId, parts, toolCalls, handoffCalls, System.currentTimeMillis());
}
private List<ToolCallInstruction> toToolCallInstructions(List<ToolCall> toolCalls) {
return toolCalls.stream()
.filter(toolCall -> tools.containsKey(toolCall.function().name()))
.map(this::toToolCallInstruction).toList();
}
private List<HandoffInstruction> toHandOffs(List<ToolCall> toolCalls) {
return toolCalls.stream()
.filter(toolCall -> handOffs.containsKey(toolCall.function().name()))
.map(this::toHandffInstruction)
.toList();
}
private ToolCallInstruction toToolCallInstruction(ToolCall toolCall) {
final Function function = toolCall.function();
final String toolName = function.name();
return new DefaultToolCallInstruction(toolCall.id(),
toolName,
function.arguments(),
extractFromJson(function.arguments()),
tools.get(toolName));
}
private HandoffInstruction toHandffInstruction(ToolCall toolCall) {
return new DefaultHandoffInstruction(toolCall.id(), handOffs.get(toolCall.function().name()));
}
private OpenAIMessage toOpenAIMessage(@Nonnull Message message) {
return switch (message) {
case DeveloperMessage dm -> new OpenAIDeveloperMessage(DEVELOPER, null, toMessageContent(dm.parts()));
case UserMessage um -> new OpenAIUserMessage(USER, null, toMessageContent(um.parts()));
case AssistantMessage am -> new OpenAIAssistantMessage(ASSISTANT, toMessageContent(am.parts()), null,
null, toolCalls(am));
case ToolMessage tm -> new OpenAIToolMessage(TOOL, tm.toolCallId(), toMessageContent(tm.parts()));
case HandOffMessage ho -> new OpenAIToolMessage(TOOL, ho.handOffId(), toMessageContent(ho.parts()));
default -> throw new RuntimeException("Cannot convert message of type " + message.getClass());
};
}
private MessageContent toMessageContent(MessagePart[] parts) {
if (Objects.isNull(parts)) {
return new TextContent(EMPTY);
}
if (parts instanceof TextPart[] textParts) {
String text = Stream.of(textParts).map(TextPart::text).collect(joining());
return new TextContent(text);
}
return new TextContent(EMPTY);
}
private List<OpenAIToolCall> toolCalls(AssistantMessage assistantMessage) {
if (assistantMessage.hasToolCalls()) {
return assistantMessage.toolCalls().stream().map(OpenAIToolConvertor::toOpenAIToolCall).toList();
} else if (assistantMessage.hasHandOffs()) {
return assistantMessage.handoffs().stream().map(OpenAIToolConvertor::toOpenAIToolCall).toList();
}
return null;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/processor/OpenAIAgentExecutor.java
|
package ai.agentscentral.openai.processor;
import ai.agentscentral.core.agent.Agent;
import ai.agentscentral.core.agent.instructor.Instructor;
import ai.agentscentral.core.factory.AgentJFactory;
import ai.agentscentral.core.handoff.Handoff;
import ai.agentscentral.core.provider.ProviderAgentExecutor;
import ai.agentscentral.core.session.message.AssistantMessage;
import ai.agentscentral.core.session.message.DeveloperMessage;
import ai.agentscentral.core.session.message.Message;
import ai.agentscentral.core.session.message.TextPart;
import ai.agentscentral.core.session.user.User;
import ai.agentscentral.core.tool.ToolCall;
import ai.agentscentral.openai.client.OpenAIClient;
import ai.agentscentral.openai.client.request.CompletionRequest;
import ai.agentscentral.openai.client.request.attributes.OpenAITool;
import ai.agentscentral.openai.client.response.CompletionResponse;
import ai.agentscentral.openai.client.response.parameters.Choice;
import ai.agentscentral.openai.client.response.parameters.ChoiceMessage;
import ai.agentscentral.openai.config.OpenAIConfig;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static ai.agentscentral.core.session.message.MessagePartType.text;
import static ai.agentscentral.openai.processor.OpenAIToolConvertor.handOffsToOpenAITools;
import static ai.agentscentral.openai.processor.OpenAIToolConvertor.toolsToOpenAITools;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.joining;
/**
* OpenAISimpleAgentExecutor
*
* @author Rizwan Idrees
*/
public class OpenAIAgentExecutor implements ProviderAgentExecutor {
private final Agent agent;
private final Map<String, OpenAITool> openAITools = new HashMap<>();
private final String modelName;
private final OpenAIConfig config;
private final OpenAIClient client;
private final MessageConvertor messageConvertor;
public OpenAIAgentExecutor(Agent agent, AgentJFactory agentJFactory, OpenAIClient client) {
this.agent = agent;
this.modelName = agent.model().name();
this.config = agent.model().config() instanceof OpenAIConfig c ? c : null;
this.client = client;
final Map<String, ToolCall> tools = agentJFactory.getToolBagToolsExtractor().extractTools(agent.toolBags());
final Map<String, Handoff> handOffs = agentJFactory.getHandoffsExtractor().extractHandOffs(agent.handoffs());
final Map<String, OpenAITool> mappedTools = toolsToOpenAITools(tools);
final Map<String, OpenAITool> mappedHandOffs = handOffsToOpenAITools(handOffs);
ofNullable(mappedTools).ifPresent(openAITools::putAll);
ofNullable(mappedHandOffs).ifPresent(openAITools::putAll);
this.messageConvertor = new MessageConvertor(tools, handOffs);
}
public List<AssistantMessage> execute(String contextId, User user, List<Message> messages) {
final DeveloperMessage agentMessage = new DeveloperMessage(contextId, "",
new TextPart[]{new TextPart(text, agentInstructions())}, System.currentTimeMillis());
final String userId = Optional.ofNullable(user).map(User::id).orElse(null);
final CompletionRequest request = CompletionRequest.from(modelName, config, userId,
List.copyOf(openAITools.values()), messageConvertor.toOpenAIMessages(agentMessage, messages));
final CompletionResponse completed = client.complete(request);
final String completionId = completed.id();
final Long createdAt = completed.created();
final List<ChoiceMessage> choiceMessages = completed.choices().stream()
.map(Choice::message)
.toList();
return List.of(messageConvertor.toAssistantMessage(contextId, completionId, choiceMessages, createdAt));
}
private String agentInstructions() {
if (agent.instructors().isEmpty()) {
return "You are a helpful assistant";
}
return agent.instructors().stream().map(Instructor::instruct).collect(joining());
}
@Override
public Agent getAgent() {
return this.agent;
}
}
|
0
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai
|
java-sources/ai/agentscentral/agentj-openai/0.0.5/ai/agentscentral/openai/processor/OpenAIToolConvertor.java
|
package ai.agentscentral.openai.processor;
import ai.agentscentral.core.handoff.Handoff;
import ai.agentscentral.core.handoff.HandoffInstruction;
import ai.agentscentral.core.tool.EnumToolParameter;
import ai.agentscentral.core.tool.ToolCall;
import ai.agentscentral.core.tool.ToolCallInstruction;
import ai.agentscentral.core.tool.ToolParameter;
import ai.agentscentral.openai.client.request.attributes.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator;
import java.util.*;
import static ai.agentscentral.openai.client.request.attributes.OpenAITool.FUNCTION;
import static java.util.stream.Collectors.toSet;
/**
* OpenAIToolConvertor
*
* @author Rizwan Idrees
*/
class OpenAIToolConvertor {
private static final ObjectMapper mapper = new ObjectMapper();
private static final JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(mapper);
static Map<String, OpenAITool> toolsToOpenAITools(Map<String, ToolCall> tools) {
if (Objects.isNull(tools) || tools.isEmpty()) {
return null;
}
final Map<String, OpenAITool> openAIToolMap = new HashMap<>();
tools.forEach((key, value) -> openAIToolMap.put(key, toOpenAITool(value)));
return openAIToolMap;
}
static Map<String, OpenAITool> handOffsToOpenAITools(Map<String, Handoff> handOffs) {
if (Objects.isNull(handOffs) || handOffs.isEmpty()) {
return null;
}
final Map<String, OpenAITool> openAIHandoffMap = new HashMap<>();
handOffs.forEach((key, value) -> openAIHandoffMap.put(key, toOpenAITool(value)));
return openAIHandoffMap;
}
private static OpenAITool toOpenAITool(ToolCall toolCall) {
final ToolFunction function = new ToolFunction(toolCall.name(), toolCall.description(), toFunctionParameters(toolCall.parameters()), false);
return new OpenAITool(FUNCTION, function);
}
private static OpenAITool toOpenAITool(Handoff handoff) {
final ToolFunction function = new ToolFunction(handoff.id(), handoff.description(), null, false);
return new OpenAITool(FUNCTION, function);
}
private static FunctionParameters toFunctionParameters(List<ToolParameter> parameters) {
if (Objects.isNull(parameters)) {
return null;
}
Set<String> requiredParameters = parameters.stream().filter(ToolParameter::required)
.map(ToolParameter::name)
.collect(toSet());
return new FunctionParameters("object", functionProperties(parameters), requiredParameters);
}
private static Map<String, ? extends FunctionProperty> functionProperties(List<ToolParameter> parameters) {
final Map<String, FunctionProperty> properties = new HashMap<>();
parameters.forEach(p -> properties.put(p.name(), functionProperty(p)));
return properties;
}
private static FunctionProperty functionProperty(ToolParameter parameter) {
final String jsonType = javaTypeToJsonType(parameter.type());
if (parameter instanceof EnumToolParameter enumParameter) {
return new EnumFunctionProperty(jsonType, enumParameter.enumValues().toArray(String[]::new));
}
return new TypedFunctionProperty(jsonType, parameter.description());
}
private static String javaTypeToJsonType(Class<?> type) {
try {
final JsonSchema jsonSchema = jsonSchemaGenerator.generateSchema(type);
return jsonSchema.getType().value();
} catch (Exception e) {
throw new UnsupportedOperationException("Unable to process tool parameter type " + type);
}
}
static OpenAIToolCall toOpenAIToolCall(ToolCallInstruction toolCallInstruction) {
final String id = toolCallInstruction.id();
final String name = toolCallInstruction.toolCall().name();
final String arguments = toolCallInstruction.rawArguments();
return new OpenAIToolCall(id, FUNCTION, new ToolCallFunction(name, arguments));
}
static OpenAIToolCall toOpenAIToolCall(HandoffInstruction handoffInstruction) {
final String id = handoffInstruction.callId();
final String name = handoffInstruction.handoff().id();
return new OpenAIToolCall(id, FUNCTION, new ToolCallFunction(name, "{}"));
}
}
|
0
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library/ArrowheadService.java
|
/********************************************************************************
* Copyright (c) 2020 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
********************************************************************************/
package ai.aitia.arrowhead.application.library;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceConfigurationError;
import java.util.UUID;
import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.internal.security.SSLSocketFactoryFactory;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import ai.aitia.arrowhead.application.library.util.ApplicationCommonConstants;
import ai.aitia.arrowhead.application.library.util.CoreServiceUri;
import eu.arrowhead.common.CommonConstants;
import eu.arrowhead.common.SSLProperties;
import eu.arrowhead.common.Utilities;
import eu.arrowhead.common.core.CoreSystem;
import eu.arrowhead.common.core.CoreSystemService;
import eu.arrowhead.common.dto.shared.DeviceRegistryOnboardingWithCsrRequestDTO;
import eu.arrowhead.common.dto.shared.DeviceRegistryOnboardingWithCsrResponseDTO;
import eu.arrowhead.common.dto.shared.DeviceRegistryOnboardingWithNameRequestDTO;
import eu.arrowhead.common.dto.shared.DeviceRegistryOnboardingWithNameResponseDTO;
import eu.arrowhead.common.dto.shared.DeviceRegistryRequestDTO;
import eu.arrowhead.common.dto.shared.DeviceRegistryResponseDTO;
import eu.arrowhead.common.dto.shared.EventPublishRequestDTO;
import eu.arrowhead.common.dto.shared.OrchestrationFormRequestDTO;
import eu.arrowhead.common.dto.shared.OrchestrationFormRequestDTO.Builder;
import eu.arrowhead.common.dto.shared.OrchestrationResponseDTO;
import eu.arrowhead.common.dto.shared.ServiceQueryFormDTO;
import eu.arrowhead.common.dto.shared.ServiceQueryResultDTO;
import eu.arrowhead.common.dto.shared.ServiceRegistryRequestDTO;
import eu.arrowhead.common.dto.shared.ServiceRegistryResponseDTO;
import eu.arrowhead.common.dto.shared.SubscriptionRequestDTO;
import eu.arrowhead.common.dto.shared.SystemRegistryOnboardingWithCsrRequestDTO;
import eu.arrowhead.common.dto.shared.SystemRegistryOnboardingWithNameRequestDTO;
import eu.arrowhead.common.dto.shared.SystemRegistryOnboardingWithNameResponseDTO;
import eu.arrowhead.common.dto.shared.SystemRegistryRequestDTO;
import eu.arrowhead.common.dto.shared.SystemRegistryResponseDTO;
import eu.arrowhead.common.dto.shared.SystemRequestDTO;
import eu.arrowhead.common.dto.shared.SystemResponseDTO;
import eu.arrowhead.common.exception.ArrowheadException;
import eu.arrowhead.common.exception.AuthException;
import eu.arrowhead.common.exception.BadPayloadException;
import eu.arrowhead.common.exception.InvalidParameterException;
import eu.arrowhead.common.exception.UnavailableServerException;
import eu.arrowhead.common.http.HttpService;
@Component("ArrowheadService")
public class ArrowheadService {
//=================================================================================================
// members
@Value(ApplicationCommonConstants.$APPLICATION_SYSTEM_NAME)
private String applicationSystemName;
@Value(ApplicationCommonConstants.$APPLICATION_SERVER_ADDRESS_WD)
private String applicationSystemAddress;
@Value(ApplicationCommonConstants.$APPLICATION_SERVER_PORT_WD)
private int applicationSystemPort;
@Value(CommonConstants.$SERVICEREGISTRY_ADDRESS_WD)
private String serviceReqistryAddress;
@Value(CommonConstants.$SERVICEREGISTRY_PORT_WD)
private int serviceRegistryPort;
@Resource(name = CommonConstants.ARROWHEAD_CONTEXT)
private Map<String,Object> arrowheadContext;
@Autowired
private SSLProperties sslProperties;
@Autowired
private HttpService httpService;
private final static String INTERFACE_SECURE_FLAG = "SECURE";
private final static String INTERFACE_INSECURE_FLAG = "INSECURE";
private final Logger logger = LogManager.getLogger(ArrowheadService.class);
//=================================================================================================
// General Core System services and support methods
//------------------------------------------------------------------------------------------------
/**
* @param coreSystemService CoreSystemService enum which represents an Arrowhead Core System Service
* @return the URI details of the Arrowhead Core System or null when the specified coreSystemService is not a public one or ArrowhedContext component not contains the the given core service.
*/
public CoreServiceUri getCoreServiceUri(final CoreSystemService coreSystemService) {
if (!CommonConstants.PUBLIC_CORE_SYSTEM_SERVICES.contains(coreSystemService)) {
logger.debug("'{}' core service is not a public service.", coreSystemService);
return null;
} else if (!arrowheadContext.containsKey(coreSystemService.getServiceDefinition() + ApplicationCommonConstants.CORE_SERVICE_DEFINITION_SUFFIX)) {
logger.debug("'{}' core service is not contained by Arrowhead Context.", coreSystemService);
return null;
} else {
return (CoreServiceUri) arrowheadContext.get(coreSystemService.getServiceDefinition() + ApplicationCommonConstants.CORE_SERVICE_DEFINITION_SUFFIX);
}
}
//-------------------------------------------------------------------------------------------------
/**
* Queries and stores the public service URIs of the given Arrowhead Core System in the ArrowheadContext component.
* If the specified Core System has no public service or the server is not available, then ArrowheadContext won't contain the core service and a log info message will be triggered.
*
* @param coreSystem CoreSystem enum which represents an Arrowhead Core System
*/
public void updateCoreServiceURIs(final CoreSystem coreSystem) {
final List<CoreSystemService> publicServices = getPublicServicesOfCoreSystem(coreSystem);
if (publicServices.isEmpty()) {
logger.info("'{}' core system has no public service.", coreSystem.name());
return;
}
for (final CoreSystemService coreService : publicServices) {
try {
final ResponseEntity<ServiceQueryResultDTO> response = queryServiceReqistryByCoreService(coreService);
if (response.getBody().getServiceQueryData().isEmpty()) {
logger.info("'{}' core service couldn't be retrieved due to the following reason: not registered by Serivce Registry", coreService.getServiceDefinition());
arrowheadContext.remove(coreService.getServiceDefinition() + ApplicationCommonConstants.CORE_SERVICE_DEFINITION_SUFFIX);
} else {
final ServiceRegistryResponseDTO serviceRegistryResponseDTO = response.getBody().getServiceQueryData().get(0);
arrowheadContext.put(coreService.getServiceDefinition() + ApplicationCommonConstants.CORE_SERVICE_DEFINITION_SUFFIX, new CoreServiceUri(serviceRegistryResponseDTO.getProvider().getAddress(),
serviceRegistryResponseDTO.getProvider().getPort(), serviceRegistryResponseDTO.getServiceUri()));
}
} catch (final ArrowheadException ex) {
logger.debug("'{}' core service couldn't be retrieved due to the following reason: {}", coreService.getServiceDefinition(), ex.getMessage());
}
}
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) request to the 'echo' end point of the given Arrowhead Core System.
*
* @param coreSystem CoreSystem enum which represents an Arrowhead Core System
* @return true if answer received from core system server and false if not or the specified core system has no public service or it is not known by Service Registry Core System
*/
public boolean echoCoreSystem(final CoreSystem coreSystem) {
String address = null;
Integer port = null;
String coreUri = null;
try {
if (coreSystem == CoreSystem.SERVICEREGISTRY) {
address = serviceReqistryAddress;
port = serviceRegistryPort;
coreUri = CommonConstants.SERVICEREGISTRY_URI;
} else {
final List<CoreSystemService> publicServices = getPublicServicesOfCoreSystem(coreSystem);
if (publicServices.isEmpty()) {
logger.debug("'{}' core system has no public service.", coreSystem.name());
return false;
} else {
final ResponseEntity<ServiceQueryResultDTO> srResponse = queryServiceReqistryByCoreService(publicServices.get(0));
if (srResponse.getBody().getServiceQueryData().isEmpty()) {
logger.debug("'{}' core system not known by Service Registry", coreSystem.name());
return false;
} else {
address = srResponse.getBody().getServiceQueryData().get(0).getProvider().getAddress();
port = srResponse.getBody().getServiceQueryData().get(0).getProvider().getPort();
coreUri = publicServices.get(0).getServiceUri().split("/")[1];
}
}
}
httpService.sendRequest(Utilities.createURI(getUriScheme(), address, port, coreUri + CommonConstants.ECHO_URI), HttpMethod.GET, String.class);
} catch (final Exception ex) {
logger.debug("Exception occured during the {} core system 'echo' request. Message : {}", coreSystem.name(), ex.getMessage());
return false;
}
return true;
}
//=================================================================================================
// Service Registry Services
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'register' request to Service Registry Core System.
*
* @param request ServiceRegistryRequestDTO which represents the required payload of the http(s) request
* @return the ServiceRegistryResponseDTO received from Service Registry Core System
* @throws AuthException when you are not authorized by Service Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Service Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Service Registry Core System
* @throws ArrowheadException when internal server error happened at Service Registry Core System
* @throws UnavailableServerException when Service Registry Core System is not available
*/
public ServiceRegistryResponseDTO registerServiceToServiceRegistry(final ServiceRegistryRequestDTO request) {
final String registerUriStr = CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_REGISTER_URI;
final UriComponents registerUri = Utilities.createURI(getUriScheme(), serviceReqistryAddress, serviceRegistryPort, registerUriStr);
return httpService.sendRequest(registerUri, HttpMethod.POST, ServiceRegistryResponseDTO.class, request).getBody();
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'register' request to Service Registry Core System. In the case of service already registered, then the old service registry entry will be overwritten.
*
* @param request ServiceRegistryRequestDTO which represents the required payload of the http(s) request
* @return the ServiceRegistryResponseDTO received from Service Registry Core System
* @throws AuthException when you are not authorized by Service Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Service Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Service Registry Core System
* @throws ArrowheadException when internal server error happened at Service Registry Core System
* @throws UnavailableServerException when Service Registry Core System is not available
*/
public ServiceRegistryResponseDTO forceRegisterServiceToServiceRegistry(final ServiceRegistryRequestDTO request) {
final String registerUriStr = CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_REGISTER_URI;
final UriComponents registerUri = Utilities.createURI(getUriScheme(), serviceReqistryAddress, serviceRegistryPort, registerUriStr);
try {
return httpService.sendRequest(registerUri, HttpMethod.POST, ServiceRegistryResponseDTO.class, request).getBody();
} catch (final InvalidParameterException ex) {
unregisterServiceFromServiceRegistry(request.getServiceDefinition(), request.getServiceUri());
return httpService.sendRequest(registerUri, HttpMethod.POST, ServiceRegistryResponseDTO.class, request).getBody();
}
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'unregister' request to Service Registry Core System.
*
* @param serviceDefinition String value which represents the service being deleted from service registry
* @param serviceUri String value which represents the service URI (path after the hostname and port) of the service being deleted from service registry
* @throws AuthException when you are not authorized by Service Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Service Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Service Registry Core System
* @throws ArrowheadException when internal server error happened at Service Registry Core System
* @throws UnavailableServerException when Service Registry Core System is not available
*/
public void unregisterServiceFromServiceRegistry(final String serviceDefinition, final String serviceUri) {
final String unregisterUriStr = CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_URI;
final String _serviceUri = serviceUri != null ? serviceUri.trim() : "";
final MultiValueMap<String,String> queryMap = new LinkedMultiValueMap<>(5);
queryMap.put(CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_SYSTEM_NAME, List.of(applicationSystemName));
queryMap.put(CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_ADDRESS, List.of(applicationSystemAddress));
queryMap.put(CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_PORT, List.of(String.valueOf(applicationSystemPort)));
queryMap.put(CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_SERVICE_DEFINITION, List.of(serviceDefinition));
queryMap.put(CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_SERVICE_URI, List.of(_serviceUri));
final UriComponents unregisterUri = Utilities.createURI(getUriScheme(), serviceReqistryAddress, serviceRegistryPort, queryMap, unregisterUriStr);
httpService.sendRequest(unregisterUri, HttpMethod.DELETE, Void.class);
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'register-system' request to Service Registry Core System.
*
* @param request SystemRequestDTO which represents the required payload of the http(s) request
* @return the SystemResponseDTO received from Service Registry Core System
* @throws AuthException when you are not authorized by Service Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Service Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Service Registry Core System
* @throws ArrowheadException when internal server error happened at Service Registry Core System
* @throws UnavailableServerException when Service Registry Core System is not available
*/
public SystemResponseDTO registerSystemToServiceRegistry(final SystemRequestDTO request) {
final String registerUriStr = CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_REGISTER_SYSTEM_URI;
final UriComponents registerUri = Utilities.createURI(getUriScheme(), serviceReqistryAddress, serviceRegistryPort, registerUriStr);
return httpService.sendRequest(registerUri, HttpMethod.POST, SystemResponseDTO.class, request).getBody();
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'register-system' request to Service Registry Core System. In the case of service already registered, then the old service registry entry will be overwritten.
*
* @param request SystemRequestDTO which represents the required payload of the http(s) request
* @return the SystemResponseDTO received from Service Registry Core System
* @throws AuthException when you are not authorized by Service Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Service Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Service Registry Core System
* @throws ArrowheadException when internal server error happened at Service Registry Core System
* @throws UnavailableServerException when Service Registry Core System is not available
*/
public SystemResponseDTO forceRegisterSystemToServiceRegistry(final SystemRequestDTO request) {
final String registerUriStr = CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_REGISTER_SYSTEM_URI;
final UriComponents registerUri = Utilities.createURI(getUriScheme(), serviceReqistryAddress, serviceRegistryPort, registerUriStr);
try {
return httpService.sendRequest(registerUri, HttpMethod.POST, SystemResponseDTO.class, request).getBody();
} catch (final InvalidParameterException ex) {
unregisterSystemFromServiceRegistry();
return httpService.sendRequest(registerUri, HttpMethod.POST, SystemResponseDTO.class, request).getBody();
}
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'unregister-system' request to Service Registry Core System.
*
* @throws AuthException when you are not authorized by Service Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Service Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Service Registry Core System
* @throws ArrowheadException when internal server error happened at Service Registry Core System
* @throws UnavailableServerException when Service Registry Core System is not available
*/
public void unregisterSystemFromServiceRegistry() {
final String unregisterUriStr = CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_SYSTEM_URI;
final MultiValueMap<String,String> queryMap = new LinkedMultiValueMap<>(3);
queryMap.put(CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_SYSTEM_NAME, List.of(applicationSystemName));
queryMap.put(CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_ADDRESS, List.of(applicationSystemAddress));
queryMap.put(CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_PORT, List.of(String.valueOf(applicationSystemPort)));
final UriComponents unregisterUri = Utilities.createURI(getUriScheme(), serviceReqistryAddress, serviceRegistryPort, queryMap, unregisterUriStr);
httpService.sendRequest(unregisterUri, HttpMethod.DELETE, Void.class);
}
//=================================================================================================
// Authorization Services
//-------------------------------------------------------------------------------------------------
/**
* Queries its public key from Authorization Core System.
*
* @return the public key of Authorization Core System or null when the public key core service URI is not known by ArrowheadContext component.
* @throws AuthException when you are not authorized by Authorization Core System
* @throws ArrowheadException when internal server error happened at Authorization Core System
* @throws UnavailableServerException when Authorization Core System is not available
*/
public PublicKey queryAuthorizationPublicKey() {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.AUTH_PUBLIC_KEY_SERVICE);
if (uri == null) {
logger.debug("Authorization Public Key couldn't be retrieved due to the following reason: " + CoreSystemService.AUTH_PUBLIC_KEY_SERVICE.name() + " not known by Arrowhead Context");
return null;
}
final ResponseEntity<String> response = httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.GET, String.class);
final String encodedKey = Utilities.fromJson(response.getBody(), String.class);
return Utilities.getPublicKeyFromBase64EncodedString(encodedKey);
}
//=================================================================================================
// Orchestrator Services
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'orchestration' request to Orchestrator Core System.
*
* @param request OrchestrationFormRequestDTO which represents the required payload of the http(s) request
* @return the OrchestrationResponseDTO received from Orchestrator Core System or null when the orchestration service URI is not known by Arrowhead Context
* @throws AuthException when you are not authorized by Orchestrator Core System
* @throws BadPayloadException when the payload couldn't be validated by Orchestrator Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Orchestrator Core System
* @throws ArrowheadException when internal server error happened at one of the core system involved in orchestration process
* @throws UnavailableServerException when one of the core system involved in orchestration process is not available
*/
public OrchestrationResponseDTO proceedOrchestration(final OrchestrationFormRequestDTO request) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.ORCHESTRATION_SERVICE);
if (uri == null) {
logger.debug("Orchestration couldn't be proceeded due to the following reason: " + CoreSystemService.ORCHESTRATION_SERVICE.name() + " not known by Arrowhead Context");
return null;
}
return httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.POST, OrchestrationResponseDTO.class, request).getBody();
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'orchestration/{systemId}' request to Orchestrator Core System.
*
* @param systemId long value which represents the required system id path variable
* @return the OrchestrationResponseDTO with all top priority provider from Orchestration Store or null when the orchestration service URI is not known by Arrowhead Context
* @throws AuthException when you are not authorized by Orchestrator Core System
* @throws BadPayloadException when the systemId couldn't be validated by Orchestrator Core System
* @throws InvalidParameterException when the system is not found by Service Registry Core System
* @throws ArrowheadException when internal server error happened at one of the core system involved in orchestration process
* @throws UnavailableServerException when one of the core system involved in orchestration process is not available
*/
public OrchestrationResponseDTO queryOrchestrationStore(final long systemId) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.ORCHESTRATION_SERVICE);
if (uri == null) {
logger.debug("Orchestration from store couldn't be proceeded due to the following reason: " + CoreSystemService.ORCHESTRATION_SERVICE.name() + " not known by Arrowhead Context");
return null;
}
return httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath() + "/" + systemId), HttpMethod.GET, OrchestrationResponseDTO.class).getBody();
}
//=================================================================================================
// System Registry Services
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'system-register' request to System Registry Core System.
*
* @param request SystemRegistryRequestDTO which represents the required payload of the http(s) request
* @return the SystemRegistryResponseDTO received from System Registry Core System
* @throws AuthException when you are not authorized by System Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by System Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by System Registry Core System
* @throws ArrowheadException when internal server error happened at System Registry Core System
* @throws UnavailableServerException when System Registry Core System is not available
*/
public SystemRegistryResponseDTO registerSystemToSystemRegistry(final SystemRegistryRequestDTO request) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.SYSTEMREGISTRY_REGISTER_SERVICE);
if (uri == null) {
logger.debug("System registration couldn't be proceeded due to the following reason: " + CoreSystemService.SYSTEMREGISTRY_REGISTER_SERVICE.name() + " not known by Arrowhead Context");
return null;
}
return httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.POST, SystemRegistryResponseDTO.class, request).getBody();
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'system-register' request to System Registry Core System. In the case of system is already registered, then the old system registry entry will be overwritten.
*
* @param request SystemRegistryRequestDTO which represents the required payload of the http(s) request
* @return the SystemRegistryResponseDTO received from System Registry Core System
* @throws AuthException when you are not authorized by System Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by System Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by System Registry Core System
* @throws ArrowheadException when internal server error happened at System Registry Core System
* @throws UnavailableServerException when System Registry Core System is not available
*/
public SystemRegistryResponseDTO forceRegisterSystemToSystemRegistry(final SystemRegistryRequestDTO request) {
try {
return registerSystemToSystemRegistry(request);
} catch (final InvalidParameterException ex) {
unregisterSystemFromSystemRegistry();
return registerSystemToSystemRegistry(request);
}
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'system-unregister' request to System Registry Core System.
*
* @return true if successfully deregistered or false if the service is not known by Arrowhead Context
* @throws AuthException when you are not authorized by System Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by System Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by System Registry Core System
* @throws ArrowheadException when internal server error happened at System Registry Core System
* @throws UnavailableServerException when System Registry Core System is not available
*/
public boolean unregisterSystemFromSystemRegistry() {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.SYSTEMREGISTRY_UNREGISTER_SERVICE);
if (uri == null) {
logger.debug("System deregistration couldn't be proceeded due to the following reason: " + CoreSystemService.SYSTEMREGISTRY_UNREGISTER_SERVICE.name() + " not known by Arrowhead Context");
return false;
}
final MultiValueMap<String,String> queryMap = new LinkedMultiValueMap<>(3);
queryMap.put(CommonConstants.OP_SYSTEMREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_SYSTEM_NAME, List.of(applicationSystemName));
queryMap.put(CommonConstants.OP_SYSTEMREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_ADDRESS, List.of(applicationSystemAddress));
queryMap.put(CommonConstants.OP_SYSTEMREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_PORT, List.of(String.valueOf(applicationSystemPort)));
final UriComponents unregisterUri = Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), queryMap, uri.getPath());
httpService.sendRequest(unregisterUri, HttpMethod.DELETE, Void.class);
return true;
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'system-onboarding-with-name' request to System Registry Core System.
*
* @param request SystemRegistryOnboardingWithNameRequestDTO which represents the required payload of the http(s) request
* @return the DeviceRegistryOnboardingWithNameResponseDTO received from System Registry Core System
* @throws AuthException when you are not authorized by System Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by System Registry Core System
* @throws ArrowheadException when internal server error happened at System Registry Core System
* @throws UnavailableServerException when System Registry Core System is not available
*/
public SystemRegistryOnboardingWithNameResponseDTO onboardSystemWithName(final SystemRegistryOnboardingWithNameRequestDTO request) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.SYSTEMREGISTRY_ONBOARDING_WITH_NAME_SERVICE);
if (uri == null) {
logger.debug("Onboarding of system couldn't be proceeded due to the following reason: " + CoreSystemService.SYSTEMREGISTRY_ONBOARDING_WITH_NAME_SERVICE.name() + " not known by Arrowhead Context");
return null;
}
return httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.POST, SystemRegistryOnboardingWithNameResponseDTO.class, request).getBody();
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'system-onboarding-with-csr' request to System Registry Core System.
*
* @param request SystemRegistryOnboardingWithCsrRequestDTO which represents the required payload of the http(s) request
* @return the SystemRegistryOnboardingWithCsrRequestDTO received from System Registry Core System
* @throws AuthException when you are not authorized by System Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by System Registry Core System
* @throws ArrowheadException when internal server error happened at System Registry Core System
* @throws UnavailableServerException when System Registry Core System is not available
*/
public SystemRegistryOnboardingWithCsrRequestDTO onboardSystemWithCSR(final SystemRegistryOnboardingWithCsrRequestDTO request) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.SYSTEMREGISTRY_ONBOARDING_WITH_CSR_SERVICE);
if (uri == null) {
logger.debug("Onboarding of system couldn't be proceeded due to the following reason: " + CoreSystemService.SYSTEMREGISTRY_ONBOARDING_WITH_CSR_SERVICE.name() + " not known by Arrowhead Context");
return null;
}
return httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.POST, SystemRegistryOnboardingWithCsrRequestDTO.class, request).getBody();
}
//=================================================================================================
// Device Registry Services
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'device-register' request to Device Registry Core System.
*
* @param request DeviceRegistryRequestDTO which represents the required payload of the http(s) request
* @return the DeviceRegistryResponseDTO received from Device Registry Core System
* @throws AuthException when you are not authorized by Device Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Device Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Device Registry Core System
* @throws ArrowheadException when internal server error happened at Device Registry Core System
* @throws UnavailableServerException when Device Registry Core System is not available
*/
public DeviceRegistryResponseDTO registerDeviceToDeviceRegistry(final DeviceRegistryRequestDTO request) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.DEVICEREGISTRY_REGISTER_SERVICE);
if (uri == null) {
logger.debug("Device registration couldn't be proceeded due to the following reason: " + CoreSystemService.DEVICEREGISTRY_REGISTER_SERVICE.name() + " not known by Arrowhead Context");
return null;
}
return httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.POST, DeviceRegistryResponseDTO.class, request).getBody();
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'device-unregister' request to Device Registry Core System.
*
* @return true if successfully deregistered or false if the service is not known by Arrowhead Context
* @throws AuthException when you are not authorized by Device Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Device Registry Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Device Registry Core System
* @throws ArrowheadException when internal server error happened at Device Registry Core System
* @throws UnavailableServerException when Device Registry Core System is not available
*/
public boolean unregisterDeviceFromDeviceRegistry(final String deviceName, final String macAdders) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.DEVICEREGISTRY_UNREGISTER_SERVICE);
if (uri == null) {
logger.debug("Device deregistration couldn't be proceeded due to the following reason: " + CoreSystemService.DEVICEREGISTRY_UNREGISTER_SERVICE.name() + " not known by Arrowhead Context");
return false;
}
final MultiValueMap<String,String> queryMap = new LinkedMultiValueMap<>(2);
queryMap.put(CommonConstants.OP_DEVICEREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_DEVICE_NAME, List.of(deviceName));
queryMap.put(CommonConstants.OP_DEVICEREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_MAC_ADDRESS, List.of(macAdders));
final UriComponents unregisterUri = Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), queryMap, uri.getPath());
httpService.sendRequest(unregisterUri, HttpMethod.DELETE, Void.class);
return true;
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'device-onboarding-with-name' request to Device Registry Core System.
*
* @param request DeviceRegistryOnboardingWithNameRequestDTO which represents the required payload of the http(s) request
* @return the DeviceRegistryOnboardingWithNameResponseDTO received from Device Registry Core System
* @throws AuthException when you are not authorized by Device Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Device Registry Core System
* @throws ArrowheadException when internal server error happened at Device Registry Core System
* @throws UnavailableServerException when Device Registry Core System is not available
*/
public DeviceRegistryOnboardingWithNameResponseDTO onboardDeviceWithName(final DeviceRegistryOnboardingWithNameRequestDTO request) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.DEVICEREGISTRY_ONBOARDING_WITH_NAME_SERVICE);
if (uri == null) {
logger.debug("Onboarding of device couldn't be proceeded due to the following reason: " + CoreSystemService.DEVICEREGISTRY_ONBOARDING_WITH_NAME_SERVICE.name() + " not known by Arrowhead Context");
return null;
}
return httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.POST, DeviceRegistryOnboardingWithNameResponseDTO.class, request).getBody();
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'device-onboarding-with-csr' request to Device Registry Core System.
*
* @param request DeviceRegistryOnboardingWithCsrRequestDTO which represents the required payload of the http(s) request
* @return the DeviceRegistryOnboardingWithCsrResponseDTO received from Device Registry Core System
* @throws AuthException when you are not authorized by Device Registry Core System
* @throws BadPayloadException when the payload couldn't be validated by Device Registry Core System
* @throws ArrowheadException when internal server error happened at Device Registry Core System
* @throws UnavailableServerException when Device Registry Core System is not available
*/
public DeviceRegistryOnboardingWithCsrResponseDTO onboardDeviceWithCSR(final DeviceRegistryOnboardingWithCsrRequestDTO request) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.DEVICEREGISTRY_ONBOARDING_WITH_CSR_SERVICE);
if (uri == null) {
logger.debug("Onboarding of device couldn't be proceeded due to the following reason: " + CoreSystemService.DEVICEREGISTRY_ONBOARDING_WITH_CSR_SERVICE.name() + " not known by Arrowhead Context");
return null;
}
return httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.POST, DeviceRegistryOnboardingWithCsrResponseDTO.class, request).getBody();
}
//=================================================================================================
// Event Handler Services
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'subscription' request to Event Handler Core System.
*
* @param request SubscriptionRequestDTO which represents the required payload of the http(s) request
* @throws AuthException when you are not authorized by Event Handler Core System
* @throws BadPayloadException when the payload couldn't be validated by Event Handler Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Event Handler Core System
* @throws ArrowheadException when internal server error happened at Event Handler Core System
* @throws UnavailableServerException when Event Handler Core System is not available
*/
public void subscribeToEventHandler(final SubscriptionRequestDTO request) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.EVENT_SUBSCRIBE_SERVICE);
if (uri == null) {
logger.debug("Subscription couldn't be proceeded due to the following reason: " + CoreSystemService.EVENT_SUBSCRIBE_SERVICE.name() + " not known by Arrowhead Context");
return;
}
httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.POST, Void.class, request);
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'unsubscription' request to Event Handler Core System.
*
* @param eventType String which represents the required eventType parameter of the http(s) request
* @param subscriberName String which represents the required subscriberName parameter of the http(s) request
* @param subscriberAddress String which represents the required subscriberAddress parameter of the http(s) request
* @param subscriberPort int which represents the required subscriberPort parameter of the http(s) request
* @throws AuthException when you are not authorized by Event Handler Core System
* @throws BadPayloadException when the payload couldn't be validated by Event Handler Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Event Handler Core System
* @throws ArrowheadException when internal server error happened at Event Handler Core System
* @throws UnavailableServerException when Event Handler Core System is not available
*/
public void unsubscribeFromEventHandler(final String eventType, final String subscriberName, final String subscriberAddress, final int subscriberPort ) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.EVENT_UNSUBSCRIBE_SERVICE);
if (uri == null) {
logger.debug("Unsubscription couldn't be proceeded due to the following reason: " + CoreSystemService.EVENT_UNSUBSCRIBE_SERVICE.name() + " not known by Arrowhead Context");
return;
}
final MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
requestParams.add(CommonConstants.OP_EVENTHANDLER_UNSUBSCRIBE_REQUEST_PARAM_EVENT_TYPE, eventType);
requestParams.add(CommonConstants.OP_EVENTHANDLER_UNSUBSCRIBE_REQUEST_PARAM_SUBSCRIBER_SYSTEM_NAME, subscriberName);
requestParams.add(CommonConstants.OP_EVENTHANDLER_UNSUBSCRIBE_REQUEST_PARAM_SUBSCRIBER_ADDRESS, subscriberAddress);
requestParams.add(CommonConstants.OP_EVENTHANDLER_UNSUBSCRIBE_REQUEST_PARAM_SUBSCRIBER_PORT, String.valueOf(subscriberPort));
final UriComponents unsubscribeUri = Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), requestParams, uri.getPath());
httpService.sendRequest(unsubscribeUri, HttpMethod.DELETE, Void.class);
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) 'publish' request to Event Handler Core System.
*
* @param request EventPublishRequestDTO which represents the required payload of the http(s) request
* @throws AuthException when you are not authorized by Event Handler Core System
* @throws BadPayloadException when the payload couldn't be validated by Event Handler Core System
* @throws InvalidParameterException when the payload content couldn't be validated by Event Handler Core System
* @throws ArrowheadException when internal server error happened at Event Handler Core System
* @throws UnavailableServerException when Event Handler Core System is not available
*/
public void publishToEventHandler(final EventPublishRequestDTO request) {
final CoreServiceUri uri = getCoreServiceUri(CoreSystemService.EVENT_PUBLISH_SERVICE);
if (uri == null) {
logger.debug("Publishing couldn't be proceeded due to the following reason: " + CoreSystemService.EVENT_PUBLISH_SERVICE.name() + " not known by Arrowhead Context");
return;
}
httpService.sendRequest(Utilities.createURI(getUriScheme(), uri.getAddress(), uri.getPort(), uri.getPath()), HttpMethod.POST, Void.class, request);
}
//=================================================================================================
// Application System support methods
//-------------------------------------------------------------------------------------------------
/**
* @return your public key or null when https mode is not enabled
*/
public PublicKey getMyPublicKey() {
if (sslProperties.isSslEnabled()) {
return (PublicKey) arrowheadContext.get(CommonConstants.SERVER_PUBLIC_KEY);
} else {
return null;
}
}
//-------------------------------------------------------------------------------------------------
/**
* @return your private key or null when https mode is not enabled
*/
public PrivateKey getMyPrivateKey() {
if (sslProperties.isSslEnabled()) {
return (PrivateKey) arrowheadContext.get(CommonConstants.SERVER_PRIVATE_KEY);
} else {
return null;
}
}
//-------------------------------------------------------------------------------------------------
/**
* @return an Orchestration form builder prefilled with your system properties
*/
public Builder getOrchestrationFormBuilder() {
final SystemRequestDTO thisSystem = new SystemRequestDTO();
thisSystem.setSystemName(applicationSystemName);
thisSystem.setAddress(applicationSystemAddress);
thisSystem.setPort(applicationSystemPort);
if (sslProperties.isSslEnabled()) {
final PublicKey publicKey = (PublicKey) arrowheadContext.get(CommonConstants.SERVER_PUBLIC_KEY);
thisSystem.setAuthenticationInfo(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
}
return new OrchestrationFormRequestDTO.Builder(thisSystem);
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) request with the specified service reachability details.
*
* @param <T> responseType which represents the expected response body.
* @param httpMethod HttpMethod enum which represents the method how the service is available.
* @param address String value which represents the host where the service is available.
* @param port int value which represents the port where the service is available
* @param serviceUri String value which represents the URI where the service is available.
* @param interfaceName String value which represents the name of the interface used for the communication. Usable interfaces could be received in orchestration response.
* @param token (nullable) String value which represents the token for being authorized at the provider side if necessary. Token could be received in orchestration response per interface type.
* @param payload (nullable) Object type which represents the required payload of the http(s) request if any necessary.
* @param queryParams (nullable) String... variable arguments which represent the additional key-value http(s) query parameters if any necessary. E.g.: "k1", "v1", "k2", "v2".
* @return the response received from the provider
*
* @throws InvalidParameterException when service URL can't be assembled.
* @throws AuthException when ssl context or access control related issue happened.
* @throws ArrowheadException when the communication is managed via Gateway Core System and internal server error happened.
* @throws UnavailableServerException when the specified server is not available.
*/
public <T> T consumeServiceHTTP(final Class<T> responseType, final HttpMethod httpMethod, final String address, final int port, final String serviceUri, final String interfaceName, final String token,
final Object payload, final String... queryParams) {
if (responseType == null) {
throw new InvalidParameterException("responseType cannot be null.");
}
if (httpMethod == null) {
throw new InvalidParameterException("httpMethod cannot be null.");
}
if (Utilities.isEmpty(address)) {
throw new InvalidParameterException("address cannot be null or blank.");
}
if (Utilities.isEmpty(serviceUri)) {
throw new InvalidParameterException("serviceUri cannot be null or blank.");
}
if (Utilities.isEmpty(interfaceName)) {
throw new InvalidParameterException("interfaceName cannot be null or blank.");
}
String[] validatedQueryParams;
if (queryParams == null) {
validatedQueryParams = new String[0];
} else {
validatedQueryParams = queryParams;
}
UriComponents uri;
if(!Utilities.isEmpty(token)) {
final List<String> query = new ArrayList<>();
query.addAll(Arrays.asList(validatedQueryParams));
query.add(CommonConstants.REQUEST_PARAM_TOKEN);
query.add(token);
uri = Utilities.createURI(getUriSchemeFromInterfaceName(interfaceName), address, port, serviceUri, query.toArray(new String[query.size()]));
} else {
uri = Utilities.createURI(getUriSchemeFromInterfaceName(interfaceName), address, port, serviceUri, validatedQueryParams);
}
final ResponseEntity<T> response = httpService.sendRequest(uri, httpMethod, responseType, payload);
return response.getBody();
}
//-------------------------------------------------------------------------------------------------
/**
* Sends a http(s) request with the specified service reachability details.
*
* @param <T> responseType which represents the expected response body.
* @param httpMethod HttpMethod enum which represents the method how the service is available.
* @param uriComponents UriComponents object which represents the URI where the service is available.
* @param token (nullable) String value which represents the token for being authorized at the provider side if necessary. Token could be received in orchestration response per interface type.
* @param payload (nullable) Object type which represents the required payload of the http(s) request if any necessary.
* @return the response received from the provider
*
* @throws InvalidParameterException when service URL can't be assembled.
* @throws AuthException when ssl context or access control related issue happened.
* @throws ArrowheadException when the communication is managed via Gateway Core System and internal server error happened.
* @throws UnavailableServerException when the specified server is not available.
*/
public <T> T consumeServiceHTTP(final Class<T> responseType, final HttpMethod httpMethod, final UriComponents uriComponents, final String token, final Object payload) {
UriComponents uri = uriComponents;
if (responseType == null) {
throw new InvalidParameterException("responseType cannot be null.");
}
if (httpMethod == null) {
throw new InvalidParameterException("httpMethod cannot be null.");
}
if (uri == null) {
throw new InvalidParameterException("uriComponents cannot be null.");
}
if (!Utilities.isEmpty(token)) {
final String uriToExpand = uri.toUriString();
final UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uriToExpand);
uri = builder.queryParam(CommonConstants.REQUEST_PARAM_TOKEN, token).build();
}
final ResponseEntity<T> response = httpService.sendRequest(uri, httpMethod, responseType, payload);
return response.getBody();
}
//-------------------------------------------------------------------------------------------------
/**
* Make WS(S) connection with the specified service reachability details.
*
* @param handler WebSocket handler to use for message exchanges
* @param address String value which represents the host where the service is available.
* @param port int value which represents the port where the service is available
* @param serviceUri String value which represents the URI where the service is available.
* @param token (nullable) String value which represents the token for being authorized at the provider side if necessary. Token could be received in orchestration response per interface type.
* @param queryParams (nullable) String... variable arguments which represent the additional key-value http(s) query parameters if any necessary. E.g.: "k1", "v1", "k2", "v2".
* @return A string ID for the WebSocketConnection manager created and used for the full-duplex communication
*
* @throws InvalidParameterException when service URL can't be assembled.
* @throws ArrowheadException when WSS connection failed or the communication is managed via Gateway Core System and internal server error happened.
*/
public String connnectServiceWS(final WebSocketHandler handler, final String address, final int port, final String serviceUri, final String token, final String... queryParams) {
if (handler == null) {
throw new InvalidParameterException("handler cannot be null.");
}
if (Utilities.isEmpty(address)) {
throw new InvalidParameterException("address cannot be null or blank.");
}
if (Utilities.isEmpty(serviceUri)) {
throw new InvalidParameterException("serviceUri cannot be null or blank.");
}
if (port < CommonConstants.SYSTEM_PORT_RANGE_MIN || port > CommonConstants.SYSTEM_PORT_RANGE_MAX){
throw new InvalidParameterException("Port must be between " + CommonConstants.SYSTEM_PORT_RANGE_MIN + " and " + CommonConstants.SYSTEM_PORT_RANGE_MAX + ".");
}
// Handle query parameters
String[] validatedQueryParams;
if (queryParams == null) {
validatedQueryParams = new String[0];
} else {
validatedQueryParams = queryParams;
}
// prepare the URI
UriComponents uri;
if(!Utilities.isEmpty(token)) {
final List<String> query = new ArrayList<>();
query.addAll(Arrays.asList(validatedQueryParams));
query.add(CommonConstants.REQUEST_PARAM_TOKEN);
query.add(token);
uri = Utilities.createURI(getUriSchemeWS(), address, port, serviceUri, query.toArray(new String[query.size()]));
} else {
uri = Utilities.createURI(getUriSchemeWS(), address, port, serviceUri, validatedQueryParams);
}
// try to establish WS(S) connection
final StandardWebSocketClient wsClient = new StandardWebSocketClient();
if(sslProperties.isSslEnabled()) {
try {
final KeyStore trustStore = getTrustStore();
final KeyStore keyStore = getKeyStore();
final TrustStrategy acceptingTrustStrategy = (final X509Certificate[] chain, final String authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, acceptingTrustStrategy).loadKeyMaterial(keyStore, sslProperties.getKeyStorePassword().toCharArray()).build();
wsClient.getUserProperties().clear();
wsClient.getUserProperties().put(ApplicationCommonConstants.TOMCAT_WS_SSL_CONTEXT, sslContext);
} catch(final Exception e) {
throw new ArrowheadException("WSS connection failed: " + e.getMessage());
}
}
final WebSocketConnectionManager manager = new WebSocketConnectionManager(wsClient, handler, uri.toString());
manager.start();
final String managerId = ApplicationCommonConstants.WS_MANAGER_ID_PREFIX + UUID.randomUUID().toString();
arrowheadContext.put(managerId, manager);
return managerId;
}
//-------------------------------------------------------------------------------------------------
/**
* Close the WS(S) connection by the given WebSocketConnectionManager ID if any.
*
* @param wsManagerId string id of the WebSocketConnectionManager
* @return true if and only if the connection was alive, otherwise false
* @throws InvalidParameterException when wsManagerId is null or blank..
*/
public boolean closeWSConnection(final String wsManagerId) {
if (Utilities.isEmpty(wsManagerId)) {
throw new InvalidParameterException("wsManagerId cannot be null or blank.");
}
if (arrowheadContext.containsKey(wsManagerId)) {
final WebSocketConnectionManager manager = (WebSocketConnectionManager) arrowheadContext.get(wsManagerId);
final boolean alive = manager.isRunning();
if (alive) {
manager.stop();
}
arrowheadContext.remove(wsManagerId);
return alive;
}
return false;
}
//-------------------------------------------------------------------------------------------------
/**
* Connect to MQTT broker.
*
* @param handler string id of the MqttCallback handler
* @param brokerAddress address to the broker
* @param mqttBrokerUsername user name to the broker if necessary
* @param mqttBrokerPassword password to the broker if necessary
* @param port port to the broker
* @param clientId the client name to use
* @return an MQTTclient if successful
* @throws MqttException if communication related error occurs
* @throws InvalidParameterException if a parameter error occurs
* @throws ArrowheadException if a certificate error occurs
*/
public MqttClient connectMQTTBroker(final MqttCallback handler, final String brokerAddress, final String mqttBrokerUsername, final String mqttBrokerPassword, final int port, final String clientId) throws MqttException {
if (handler == null) {
throw new InvalidParameterException("handler cannot be null.");
}
if (Utilities.isEmpty(brokerAddress)) {
throw new InvalidParameterException("brokerAddress cannot be null or blank.");
}
if (Utilities.isEmpty(clientId)) {
throw new InvalidParameterException("clientId cannot be null or blank.");
}
if (port < CommonConstants.SYSTEM_PORT_RANGE_MIN || port > CommonConstants.SYSTEM_PORT_RANGE_MAX){
throw new InvalidParameterException("Port must be between " + CommonConstants.SYSTEM_PORT_RANGE_MIN + " and " + CommonConstants.SYSTEM_PORT_RANGE_MAX + ".");
}
final MemoryPersistence persistence = new MemoryPersistence();
final MqttClient client = new MqttClient(brokerAddress, clientId, persistence);
final MqttConnectOptions connOpts = new MqttConnectOptions();
if(!Utilities.isEmpty(mqttBrokerUsername) && !Utilities.isEmpty(mqttBrokerPassword)) {
connOpts.setUserName(mqttBrokerUsername);
connOpts.setPassword(mqttBrokerPassword.toCharArray());
}
if(sslProperties.isSslEnabled()) {
try {
final Properties sslMQTTProperties = new Properties();
sslMQTTProperties.put(SSLSocketFactoryFactory.KEYSTORE, sslProperties.getKeyStore().getFile().getAbsolutePath());
sslMQTTProperties.put(SSLSocketFactoryFactory.KEYSTOREPWD, sslProperties.getKeyPassword());
sslMQTTProperties.put(SSLSocketFactoryFactory.KEYSTORETYPE, sslProperties.getKeyStoreType());
sslMQTTProperties.put(SSLSocketFactoryFactory.TRUSTSTORE, sslProperties.getTrustStore().getFile().getAbsolutePath());
sslMQTTProperties.put(SSLSocketFactoryFactory.TRUSTSTOREPWD, sslProperties.getTrustStorePassword());
sslMQTTProperties.put(SSLSocketFactoryFactory.TRUSTSTORETYPE, sslProperties.getKeyStoreType()); //intentionally the same
connOpts.setSSLProperties(sslMQTTProperties);
} catch(final Exception err) {
logger.error("MQTTS security exception: " + err);
throw new ArrowheadException("Bad certificate settings");
}
}
connOpts.setCleanSession(true);
client.setCallback(handler);
logger.info("Connecting to MQTT(S) broker: " + brokerAddress);
client.connect(connOpts);
return client;
}
//-------------------------------------------------------------------------------------------------
/**
* Close connection and release resources
*
* @param client the client to close
* @throws MqttException if the client is not disconnected
*/
public void closeMQTTBroker(final MqttClient client) throws MqttException {
if (client == null) {
throw new InvalidParameterException("client cannot be null.");
}
logger.info("Closing client");
client.close();
}
//-------------------------------------------------------------------------------------------------
/**
* Disconnect from MQTT broker
*
* @param client the client to disconnect
* @throws MqttException if a problem is encountered while disconnecting
*/
public void disconnectMQTTBroker(final MqttClient client) throws MqttException {
if (client == null) {
throw new InvalidParameterException("client cannot be null.");
}
logger.info("Disconnecting from MQTT broker");
client.disconnect();
}
//-------------------------------------------------------------------------------------------------
/**
* Get the serverCN from arrowheadContext
*
* @return Arrowhead Application-System ServerCN
*/
public String getServerCN(){
return (String) arrowheadContext.get(CommonConstants.SERVER_COMMON_NAME);
}
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private ResponseEntity<ServiceQueryResultDTO> queryServiceReqistryByCoreService(final CoreSystemService coreService) {
final ServiceQueryFormDTO request = new ServiceQueryFormDTO();
request.setServiceDefinitionRequirement(coreService.getServiceDefinition());
return httpService.sendRequest(Utilities.createURI(getUriScheme(), serviceReqistryAddress, serviceRegistryPort, CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_QUERY_URI),
HttpMethod.POST, ServiceQueryResultDTO.class, request);
}
//-------------------------------------------------------------------------------------------------
private String getUriScheme() {
return sslProperties.isSslEnabled() ? CommonConstants.HTTPS : CommonConstants.HTTP;
}
//-------------------------------------------------------------------------------------------------
private String getUriSchemeWS() {
return sslProperties.isSslEnabled() ? CommonConstants.WSS : CommonConstants.WS;
}
//-------------------------------------------------------------------------------------------------
private String getUriSchemeFromInterfaceName(final String interfaceName) {
final String[] splitInterf = interfaceName.split("-");
final String protocolStr = splitInterf[0];
if (!protocolStr.equalsIgnoreCase(CommonConstants.HTTP) && !protocolStr.equalsIgnoreCase(CommonConstants.HTTPS)) {
// Currently only HTTP(S) is supported
throw new InvalidParameterException("Invalid interfaceName: protocol should be 'http' or 'https'.");
}
final boolean isSecure = INTERFACE_SECURE_FLAG.equalsIgnoreCase(splitInterf[1]);
final boolean isInsecure = INTERFACE_INSECURE_FLAG.equalsIgnoreCase(splitInterf[1]);
if (!isSecure && !isInsecure) {
return getUriScheme();
}
return isSecure ? CommonConstants.HTTPS : CommonConstants.HTTP;
}
//-------------------------------------------------------------------------------------------------
private List<CoreSystemService> getPublicServicesOfCoreSystem(final CoreSystem coreSystem) {
final List<CoreSystemService> publicServices = new ArrayList<>();
publicServices.addAll(coreSystem.getServices());
publicServices.retainAll(CommonConstants.PUBLIC_CORE_SYSTEM_SERVICES);
return publicServices;
}
//-------------------------------------------------------------------------------------------------
private KeyStore getKeyStore() {
try {
final KeyStore keystore = KeyStore.getInstance(sslProperties.getKeyStoreType());
keystore.load(sslProperties.getKeyStore().getInputStream(), sslProperties.getKeyStorePassword().toCharArray());
return keystore;
} catch (final KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) {
throw new ServiceConfigurationError("Cannot open keystore: " + e.getMessage());
}
}
//-------------------------------------------------------------------------------------------------
private KeyStore getTrustStore() {
try {
final KeyStore truststore = KeyStore.getInstance(sslProperties.getKeyStoreType());
truststore.load(sslProperties.getTrustStore().getInputStream(), sslProperties.getTrustStorePassword().toCharArray());
return truststore;
} catch (final KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) {
throw new ServiceConfigurationError("Cannot open truststore: " + e.getMessage());
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library/config/ApplicationInitListener.java
|
/********************************************************************************
* Copyright (c) 2020 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
********************************************************************************/
package ai.aitia.arrowhead.application.library.config;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PreDestroy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.util.Assert;
import ai.aitia.arrowhead.application.library.ArrowheadService;
import eu.arrowhead.common.CommonConstants;
import eu.arrowhead.common.SSLProperties;
import eu.arrowhead.common.Utilities;
import eu.arrowhead.common.core.CoreSystem;
import eu.arrowhead.common.exception.AuthException;
public abstract class ApplicationInitListener {
//=================================================================================================
// members
@Autowired
private ArrowheadService arrowheadService;
@Autowired
protected SSLProperties sslProperties;
protected final Logger logger = LogManager.getLogger(ApplicationInitListener.class);
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
@EventListener
@Order(10)
public void onApplicationEvent(final ContextRefreshedEvent event) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InterruptedException {
logger.info("Security mode: {}", getModeString());
if (sslProperties.isSslEnabled()) {
final KeyStore keyStore = initializeKeyStore();
checkServerCertificate(keyStore, event.getApplicationContext());
obtainKeys(keyStore, event.getApplicationContext());
}
customInit(event);
}
//-------------------------------------------------------------------------------------------------
@PreDestroy
public void destroy() throws InterruptedException {
customDestroy();
}
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
protected void customInit(final ContextRefreshedEvent event) {}
//-------------------------------------------------------------------------------------------------
protected void customDestroy() {}
//-------------------------------------------------------------------------------------------------
protected String getModeString() {
return sslProperties.isSslEnabled() ? "SECURED" : "NOT SECURED";
}
//-------------------------------------------------------------------------------------------------
protected void checkCoreSystemReachability(final CoreSystem coreSystem) {
if (arrowheadService.echoCoreSystem(coreSystem)) {
logger.info("'{}' core system is reachable.", coreSystem.name());
} else {
logger.info("'{}' core system is NOT reachable.", coreSystem.name());
}
}
//-------------------------------------------------------------------------------------------------
private KeyStore initializeKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
logger.debug("initializeKeyStore started...");
Assert.isTrue(sslProperties.isSslEnabled(), "SSL is not enabled.");
final String messageNotDefined = " is not defined.";
Assert.isTrue(!Utilities.isEmpty(sslProperties.getKeyStoreType()), CommonConstants.KEYSTORE_TYPE + messageNotDefined);
Assert.notNull(sslProperties.getKeyStore(), CommonConstants.KEYSTORE_PATH + messageNotDefined);
Assert.isTrue(sslProperties.getKeyStore().exists(), CommonConstants.KEYSTORE_PATH + " file is not found.");
Assert.notNull(sslProperties.getKeyStorePassword(), CommonConstants.KEYSTORE_PASSWORD + messageNotDefined);
final KeyStore keystore = KeyStore.getInstance(sslProperties.getKeyStoreType());
keystore.load(sslProperties.getKeyStore().getInputStream(), sslProperties.getKeyStorePassword().toCharArray());
return keystore;
}
//-------------------------------------------------------------------------------------------------
private void checkServerCertificate(final KeyStore keyStore, final ApplicationContext appContext) {
logger.debug("checkServerCertificate started...");
final X509Certificate serverCertificate = Utilities.getSystemCertFromKeyStore(keyStore);
final String serverCN = Utilities.getCertCNFromSubject(serverCertificate.getSubjectDN().getName());
if (!Utilities.isKeyStoreCNArrowheadValid(serverCN)) {
logger.info("Application system CN ({}) is not compliant with the Arrowhead certificate structure, since it does not have 5 parts, or does not end with \"arrowhead.eu\".", serverCN);
throw new AuthException("Server CN (" + serverCN + ") is not compliant with the Arrowhead certificate structure, since it does not have 5 parts, or does not end with \"arrowhead.eu\".");
}
logger.info("Application system CN: {}", serverCN);
@SuppressWarnings("unchecked")
final Map<String,Object> context = appContext.getBean(CommonConstants.ARROWHEAD_CONTEXT, Map.class);
context.put(CommonConstants.SERVER_COMMON_NAME, serverCN);
}
//-------------------------------------------------------------------------------------------------
private void obtainKeys(final KeyStore keyStore, final ApplicationContext appContext) {
logger.debug("obtainKeys started...");
@SuppressWarnings("unchecked")
final Map<String,Object> context = appContext.getBean(CommonConstants.ARROWHEAD_CONTEXT, Map.class);
context.put(CommonConstants.SERVER_PUBLIC_KEY, Utilities.getSystemCertFromKeyStore(keyStore).getPublicKey());
final PrivateKey privateKey = Utilities.getPrivateKey(keyStore, sslProperties.getKeyPassword());
context.put(CommonConstants.SERVER_PRIVATE_KEY, privateKey);
}
}
|
0
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library/config/DefaultSecurityConfig.java
|
/********************************************************************************
* Copyright (c) 2020 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
********************************************************************************/
package ai.aitia.arrowhead.application.library.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import eu.arrowhead.common.CommonConstants;
public class DefaultSecurityConfig extends WebSecurityConfigurerAdapter {
//=================================================================================================
// members
@Value(CommonConstants.$SERVER_SSL_ENABLED_WD)
private boolean sslEnabled;
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.httpBasic().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
if (sslEnabled) {
http.requiresChannel().anyRequest().requiresSecure();
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library/util/ApplicationCommonConstants.java
|
/********************************************************************************
* Copyright (c) 2020 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
********************************************************************************/
package ai.aitia.arrowhead.application.library.util;
public class ApplicationCommonConstants {
//=================================================================================================
// members
public static final String APPLICATION_SYSTEM_NAME = "application_system_name";
public static final String $APPLICATION_SYSTEM_NAME = "${" + APPLICATION_SYSTEM_NAME + "}";
public static final String APPLICATION_SERVER_ADDRESS = "server.address";
public static final String $APPLICATION_SERVER_ADDRESS_WD = "${" + APPLICATION_SERVER_ADDRESS + ": localhost" + "}";
public static final String APPLICATION_SERVER_PORT = "server.port";
public static final String $APPLICATION_SERVER_PORT_WD = "${" + APPLICATION_SERVER_PORT + ": 8080" + "}";
public static final String TOKEN_SECURITY_FILTER_ENABLED = "token.security.filter.enabled";
public static final String $TOKEN_SECURITY_FILTER_ENABLED_WD = "${" + TOKEN_SECURITY_FILTER_ENABLED + ":true" + "}";
public static final String CORE_SERVICE_DEFINITION_SUFFIX = "-ah.core";
public static final String TOMCAT_WS_SSL_CONTEXT = "org.apache.tomcat.websocket.SSL_CONTEXT";
public static final String WS_MANAGER_ID_PREFIX = "ws.manager.";
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private ApplicationCommonConstants() {
throw new UnsupportedOperationException();
}
}
|
0
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library/util/ArrowheadBeans.java
|
/********************************************************************************
* Copyright (c) 2020 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
********************************************************************************/
package ai.aitia.arrowhead.application.library.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import ai.aitia.arrowhead.application.library.ArrowheadService;
import eu.arrowhead.common.SSLProperties;
import eu.arrowhead.common.http.HttpService;
@Component
public class ArrowheadBeans implements ApplicationContextAware {
//=================================================================================================
// members
private static ApplicationContext appContext;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
/**
* @return the ArrowheadService spring managed bean
*/
public static ArrowheadService getArrowheadService() {
return appContext.getBean(ArrowheadService.class);
}
//-------------------------------------------------------------------------------------------------
/**
* @return the SSLProperties spring managed bean
*/
public static SSLProperties getSSLProperties() {
return appContext.getBean(SSLProperties.class);
}
//-------------------------------------------------------------------------------------------------
/**
* @return the HttpService spring managed bean
*/
public static HttpService getHttpService() {
return appContext.getBean(HttpService.class);
}
//-------------------------------------------------------------------------------------------------
@SuppressWarnings("static-access")
@Override
public void setApplicationContext(final ApplicationContext ac) throws BeansException {
this.appContext = ac;
}
}
|
0
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library/util/ArrowheadContext.java
|
package ai.aitia.arrowhead.application.library.util;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Component;
import eu.arrowhead.common.CommonConstants;
@Component(CommonConstants.ARROWHEAD_CONTEXT)
public class ArrowheadContext extends ConcurrentHashMap<String,Object> {
private static final long serialVersionUID = -4506616943869170913L;
}
|
0
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library
|
java-sources/ai/aitia/arrowhead-application-library-java-spring/4.6.0.0/ai/aitia/arrowhead/application/library/util/CoreServiceUri.java
|
/********************************************************************************
* Copyright (c) 2020 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
********************************************************************************/
package ai.aitia.arrowhead.application.library.util;
import org.springframework.util.Assert;
import eu.arrowhead.common.Utilities;
public class CoreServiceUri {
//=================================================================================================
// members
private String address;
private int port;
private String path;
//-------------------------------------------------------------------------------------------------
public CoreServiceUri(final String address, final int port, final String uri) {
Assert.isTrue(!Utilities.isEmpty(address), "address is null or blank");
Assert.isTrue(!Utilities.isEmpty(uri), "uri is null or blank");
this.address = address;
this.port = port;
this.path = uri;
}
//-------------------------------------------------------------------------------------------------
public String getAddress() { return address; }
public int getPort() { return port; }
public String getPath() { return path; }
//-------------------------------------------------------------------------------------------------
public void setAddress(final String address) { this.address = address; }
public void setPort(final int port) { this.port = port; }
public void setPath(final String uri) { this.path = uri; }
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/CommonConstants.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common;
import java.util.List;
import eu.arrowhead.common.core.CoreSystemService;
import org.jose4j.jwe.ContentEncryptionAlgorithmIdentifiers;
import org.jose4j.jwe.KeyManagementAlgorithmIdentifiers;
import org.jose4j.jws.AlgorithmIdentifiers;
public class CommonConstants {
//=================================================================================================
// members
public static final String BASE_PACKAGE = "eu.arrowhead";
public static final String CORE_SYSTEM_AUTHORIZATION = "Authorization";
public static final String CORE_SYSTEM_CERTIFICATEAUTHORITY = "Certificate Authority";
public static final String CORE_SYSTEM_CONFIGURATION = "Configuration";
public static final String CORE_SYSTEM_CHOREOGRAPHER = "Choreographer";
public static final String CORE_SYSTEM_EVENTHANDLER = "Event Handler";
public static final String CORE_SYSTEM_DATAMANAGER = "DataManager";
public static final String CORE_SYSTEM_TIMEMANAGER = "TimeManager";
public static final String CORE_SYSTEM_GATEKEEPER = "Gatekeeper";
public static final String CORE_SYSTEM_GATEWAY = "Gateway";
public static final String CORE_SYSTEM_ORCHESTRATOR = "Orchestrator";
public static final String CORE_SYSTEM_SERVICEREGISTRY = "Service Registry";
public static final String CORE_SYSTEM_QOSMONITOR = "Quality of Service Monitor";
public static final String CORE_SYSTEM_TRANSLATOR = "Translator";
public static final String CORE_SYSTEM_SYSTEMREGISTRY = "System Registry";
public static final String CORE_SYSTEM_DEVICEREGISTRY = "Device Registry";
public static final String CORE_SYSTEM_ONBOARDING = "Onboarding Controller";
public static final String CORE_SYSTEM_MSCV = "Monitoring and Standard Compliance Verification";
public static final String CORE_SYSTEM_GAMS = "Generic Autonomic Management System";
public static final String CORE_SERVICE_AUTH_TOKEN_GENERATION = "token-generation";
public static final String CORE_SERVICE_AUTH_TOKEN_GENERATION_MULTI_SERVICE = "token-generation-multi-service";
public static final String CORE_SERVICE_AUTH_PUBLIC_KEY = "auth-public-key";
public static final String CORE_SERVICE_AUTH_CONTROL_INTRA = "authorization-control-intra";
public static final String CORE_SERVICE_AUTH_CONTROL_INTER = "authorization-control-inter";
public static final String CORE_SERVICE_AUTH_CONTROL_SUBSCRIPTION = "authorization-control-subscription";
public static final String CORE_SERVICE_ORCH_PROCESS = "orchestration-service";
public static final String CORE_SERVICE_ORCH_PROCESS_BY_PROXY = "orchestration-service-by-proxy";
public static final String CORE_SERVICE_ORCH_CREATE_FLEXIBLE_STORE_RULES = "orchestration-create-flexible-store-rules";
public static final String CORE_SERVICE_ORCH_REMOVE_FLEXIBLE_STORE_RULE = "orchestration-remove-flexible-store-rule";
public static final String CORE_SERVICE_ORCH_CLEAN_FLEXIBLE_STORE = "orchestration-clean-flexible-store";
public static final String CORE_SERVICE_ORCH_QOS_ENABLED = "orchestration-qos-enabled";
public static final String CORE_SERVICE_ORCH_QOS_RESERVATIONS = "orchestration-qos-reservations";
public static final String CORE_SERVICE_ORCH_QOS_TEMPORARY_LOCK = "orchestration-qos-temporary-lock";
public static final String CORE_SERVICE_ORCH_QOS_CONFIRM_RESERVATION = "orchestration-qos-confirm-reservation";
public static final String CORE_SERVICE_GATEKEEPER_GSD = "global-service-discovery";
public static final String CORE_SERVICE_GATEKEEPER_MULTI_GSD = "multi-global-service-discovery";
public static final String CORE_SERVICE_GATEKEEPER_ICN = "inter-cloud-negotiations";
public static final String CORE_SERVICE_GATEKEEPER_PULL_CLOUDS = "pull-clouds";
public static final String CORE_SERVICE_GATEKEEPER_COLLECT_SYSTEM_ADDRESSES = "collect-system-addresses";
public static final String CORE_SERVICE_GATEKEEPER_COLLECT_ACCESS_TYPES = "collect-access-types";
public static final String CORE_SERVICE_GATEKEEPER_RELAY_TEST = "gatekeeper-relay-test";
public static final String CORE_SERVICE_GATEKEEPER_GET_CLOUD = "gatekeeper-get-cloud";
public static final String CORE_SERVICE_GATEWAY_PUBLIC_KEY = "gw-public-key";
public static final String CORE_SERVICE_GATEWAY_CONNECT_CONSUMER = "gw-connect-consumer";
public static final String CORE_SERVICE_GATEWAY_CONNECT_PROVIDER = "gw-connect-provider";
public static final String CORE_SERVICE_GATEWAY_CLOSE_SESSIONS = "gw-close-sessions";
public static final String CORE_SERVICE_EVENTHANDLER_PUBLISH = "event-publish";
public static final String CORE_SERVICE_EVENTHANDLER_SUBSCRIBE = "event-subscribe";
public static final String CORE_SERVICE_EVENTHANDLER_UNSUBSCRIBE = "event-unsubscribe";
public static final String CORE_SERVICE_EVENTHANDLER_PUBLISH_AUTH_UPDATE = "event-publish-auth-update";
public static final String CORE_SERVICE_DATAMANAGER_PROXY = "proxy";
public static final String CORE_SERVICE_DATAMANAGER_HISTORIAN = "historian";
public static final String CORE_SERVICE_TIMEMANAGER_TIME = "time";
public static final String CORE_SERVICE_CONFIGURATION_CONF = "conf";
public static final String CORE_SERVICE_CONFIGURATION_RAWCONF = "confraw";
public static final String CORE_SERVICE_CHOREOGRAPHER_PROCESS = "choreographer-service";
public static final String CORE_SERVICE_CHOREOGRAPHER_REGISTER_EXECUTOR = "executor-register";
public static final String CORE_SERVICE_CHOREOGRAPHER_UNREGISTER_EXECUTOR = "executor-unregister";
public static final String CORE_SERVICE_CERTIFICATEAUTHORITY_SIGN = "ca-sign";
public static final String CORE_SERVICE_CERTIFICATEAUTHORITY_LIST_CERTIFICATES = "ca-list-certificates";
public static final String CORE_SERVICE_CERTIFICATEAUTHORITY_CHECK_CERTIFICATE = "ca-check-certificate";
public static final String CORE_SERVICE_CERTIFICATEAUTHORITY_REVOKE_CERTIFICATE = "ca-revoke-certificate";
public static final String CORE_SERVICE_CERTIFICATEAUTHORITY_LIST_TRUSTED_KEYS = "ca-list-trusted-keys";
public static final String CORE_SERVICE_CERTIFICATEAUTHORITY_CHECK_TRUSTED_KEY = "ca-check-trusted-key";
public static final String CORE_SERVICE_CERTIFICATEAUTHORITY_ADD_TRUSTED_KEY = "ca-add-trusted-key";
public static final String CORE_SERVICE_CERTIFICATEAUTHORITY_DELETE_TRUSTED_KEY = "ca-delete-trusted-key";
public static final String CORE_SERVICE_QOSMONITOR_INTRA_PING_MEASUREMENT = "qos-monitor-intra-ping-measurement";
public static final String CORE_SERVICE_QOSMONITOR_INTRA_PING_MEDIAN_MEASUREMENT = "qos-monitor-intra-ping-median-measurement";
public static final String CORE_SERVICE_QOSMONITOR_INTER_DIRECT_PING_MEASUREMENT = "qos-monitor-inter-direct-ping-measurement";
public static final String CORE_SERVICE_QOSMONITOR_INTER_RELAY_ECHO_MEASUREMENT = "qos-monitor-inter-relay-echo-measurement";
public static final String CORE_SERVICE_QOSMONITOR_PUBLIC_KEY = "qos-monitor-public-key";
public static final String CORE_SERVICE_QOSMONITOR_JOIN_RELAY_TEST = "qos-monitor-join-relay-test";
public static final String CORE_SERVICE_QOSMONITOR_INIT_RELAY_TEST = "qos-monitor-init-relay-test";
public static final String CORE_SERVICE_SERVICEREGISTRY_REGISTER = "service-register";
public static final String CORE_SERVICE_SERVICEREGISTRY_UNREGISTER = "service-unregister";
public static final String CORE_SERVICE_SERVICEREGISTRY_REGISTER_SYSTEM = "register-system";
public static final String CORE_SERVICE_SERVICEREGISTRY_UNREGISTER_SYSTEM = "unregister-system";
public static final String CORE_SERVICE_SERVICEREGISTRY_PULL_SYSTEMS = "pull-systems";
public static final String CORE_SERVICE_SERVICEREGISTRY_PULL_CONFIG = "pull-config";
public static final String CORE_SERVICE_MSCV_VERIFICATION = "standard-verification";
public static final String CORE_SERVICE_MSCV_PUBLIC_KEY = "standard-verification-public-key";
public static final String CORE_SERVICE_MSCV_LOGIN = "standard-verification-remote-login";
public static final String CORE_SERVICE_SYSTEMREGISTRY_REGISTER = "system-register";
public static final String CORE_SERVICE_SYSTEMREGISTRY_UNREGISTER = "system-unregister";
public static final String CORE_SERVICE_SYSTEMREGISTRY_ONBOARDING_WITH_NAME = "system-onboarding-with-name";
public static final String CORE_SERVICE_SYSTEMREGISTRY_ONBOARDING_WITH_CSR = "system-onboarding-with-csr";
public static final String CORE_SERVICE_DEVICEREGISTRY_REGISTER = "device-register";
public static final String CORE_SERVICE_DEVICEREGISTRY_UNREGISTER = "device-unregister";
public static final String CORE_SERVICE_DEVICEREGISTRY_ONBOARDING_WITH_NAME = "device-onboarding-with-name";
public static final String CORE_SERVICE_DEVICEREGISTRY_ONBOARDING_WITH_CSR = "device-onboarding-with-csr";
public static final String CORE_SERVICE_ONBOARDING_WITH_CERTIFICATE_AND_NAME = "onboarding-with-certificate-and-name";
public static final String CORE_SERVICE_ONBOARDING_WITH_CERTIFICATE_AND_CSR = "onboarding-with-certificate-and-csr";
public static final String CORE_SERVICE_ONBOARDING_WITH_SHARED_SECRET_AND_NAME = "onboarding-with-shared-secret-and-name";
public static final String CORE_SERVICE_ONBOARDING_WITH_SHARED_SECRET_AND_CSR = "onboarding-with-shared-secret-and-csr";
public static final String CORE_SERVICE_TRANSLATOR = "translation-service";
public static final String CORE_SERVICE_TRANSLATOR_FIWARE = "translation-fiware-service";
public static final String CORE_SERVICE_TRANSLATOR_PLUGIN = "translation-plugin-service";
public static final String CORE_SERVICE_GAMS_SERVICE = "gams-service";
public static final String CORE_SERVICE_GAMS_SENSOR_SERVICE = "gams-sensor-service";
public static final String DOT = ".";
public static final String COMMON_FIELD_NAME_ID = "id";
public static final String ARROWHEAD_CONTEXT = "arrowheadContext";
public static final String SERVER_COMMON_NAME = "server.common.name";
public static final String SERVER_PUBLIC_KEY = "server.public.key";
public static final String SERVER_PRIVATE_KEY = "server.private.key";
public static final String SERVER_CERTIFICATE = "server.certificate";
public static final String SECURE_INTF = "-SECURE-";
public static final String INSECURE_INTF = "-INSECURE-";
public static final String HTTPS = "https";
public static final String HTTP = "http";
public static final String WSS = "wss";
public static final String WS = "ws";
public static final String MQTTS = "mqtts";
public static final String MQTT = "mqtt";
public static final String JSON = "JSON";
public static final String XML = "XML";
public static final String CBOR = "CBOR";
public static final String EXI = "EXI";
public static final String BINARY = "BINARY";
public static final String HTTP_SECURE_JSON = HTTP.toUpperCase() + SECURE_INTF + JSON;
public static final String HTTP_INSECURE_JSON = HTTP.toUpperCase() + INSECURE_INTF + JSON;
public static final String WS_SECURE_JSON = WS.toUpperCase() + SECURE_INTF + JSON;
public static final String WS_INSECURE_JSON = WS.toUpperCase() + INSECURE_INTF + JSON;
public static final String MQTT_SECURE_JSON = MQTT.toUpperCase() + SECURE_INTF + JSON;
public static final String MQTT_INSECURE_JSON = MQTT.toUpperCase() + INSECURE_INTF + JSON;
public static final String UNKNOWN_ORIGIN = "<unknown>";
public static final String SERVICEREGISTRY_ADDRESS = "sr_address";
public static final String $SERVICEREGISTRY_ADDRESS_WD = "${" + SERVICEREGISTRY_ADDRESS + ":" + Defaults.DEFAULT_SERVICEREGISTRY_ADDRESS + "}";
public static final String SERVICEREGISTRY_PORT = "sr_port";
public static final String $SERVICEREGISTRY_PORT_WD = "${" + SERVICEREGISTRY_PORT + ":" + Defaults.DEFAULT_SERVICEREGISTRY_PORT + "}";
public static final String GAMS_URI = "/gams";
public static final String ONBOARDING_URI = "/onboarding";
public static final String ONBOARDING_AUTH_WITH_CERTIFICATE_URI = "/certificate";
public static final String ONBOARDING_AUTH_WITH_SHARED_SECRET_URI = "/sharedsecret";
public static final String ONBOARDING_WITH_NAME_URI = "/name";
public static final String ONBOARDING_WITH_CSR_URI = "/csr";
public static final String OP_ONBOARDING_WITH_CERTIFICATE_AND_NAME = ONBOARDING_AUTH_WITH_CERTIFICATE_URI + ONBOARDING_WITH_NAME_URI;
public static final String OP_ONBOARDING_WITH_CERTIFICATE_AND_CSR = ONBOARDING_AUTH_WITH_CERTIFICATE_URI + ONBOARDING_WITH_CSR_URI;
public static final String OP_ONBOARDING_WITH_SHARED_SECRET_AND_NAME = ONBOARDING_AUTH_WITH_SHARED_SECRET_URI + ONBOARDING_WITH_NAME_URI;
public static final String OP_ONBOARDING_WITH_SHARED_SECRET_AND_CSR = ONBOARDING_AUTH_WITH_SHARED_SECRET_URI + ONBOARDING_WITH_CSR_URI;
public static final String SERVICEREGISTRY_URI = "/serviceregistry";
public static final String OP_SERVICEREGISTRY_REGISTER_URI = "/register";
public static final String OP_SERVICEREGISTRY_UNREGISTER_URI = "/unregister";
public static final String OP_SERVICEREGISTRY_REGISTER_SYSTEM_URI = "/register-system";
public static final String OP_SERVICEREGISTRY_UNREGISTER_SYSTEM_URI = "/unregister-system";
public static final String OP_SERVICEREGISTRY_PULL_SYSTEMS_URI = "/pull-systems";
public static final String OP_SERVICEREGISTRY_QUERY_URI = "/query";
public static final String OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_SYSTEM_NAME = "system_name";
public static final String OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_ADDRESS = "address";
public static final String OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_PORT = "port";
public static final String OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_SERVICE_DEFINITION = "service_definition";
public static final String OP_SERVICEREGISTRY_UNREGISTER_REQUEST_PARAM_SERVICE_URI = "service_uri";
public static final String SYSTEMREGISTRY_URI = "/systemregistry";
public static final String OP_SYSTEMREGISTRY_REGISTER_URI = "/register";
public static final String OP_SYSTEMREGISTRY_UNREGISTER_URI = "/unregister";
public static final String OP_SYSTEMREGISTRY_QUERY_URI = "/query";
public static final String OP_SYSTEMREGISTRY_ONBOARDING_WITH_NAME_URI = ONBOARDING_WITH_NAME_URI;
public static final String OP_SYSTEMREGISTRY_ONBOARDING_WITH_CSR_URI = ONBOARDING_WITH_CSR_URI;
public static final String OP_SYSTEMREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_SYSTEM_NAME = "system_name";
public static final String OP_SYSTEMREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_ADDRESS = "address";
public static final String OP_SYSTEMREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_PORT = "port";
public static final String DEVICEREGISTRY_URI = "/deviceregistry";
public static final String OP_DEVICEREGISTRY_REGISTER_URI = "/register";
public static final String OP_DEVICEREGISTRY_UNREGISTER_URI = "/unregister";
public static final String OP_DEVICEREGISTRY_QUERY_URI = "/query";
public static final String OP_DEVICEREGISTRY_ONBOARDING_WITH_NAME_URI = ONBOARDING_WITH_NAME_URI;
public static final String OP_DEVICEREGISTRY_ONBOARDING_WITH_CSR_URI = ONBOARDING_WITH_CSR_URI;
public static final String OP_DEVICEREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_DEVICE_NAME = "device_name";
public static final String OP_DEVICEREGISTRY_UNREGISTER_REQUEST_PARAM_PROVIDER_MAC_ADDRESS = "mac_address";
public static final String AUTHORIZATION_URI = "/authorization";
public static final String OP_AUTH_TOKEN_URI = "/token";
public static final String OP_AUTH_TOKEN_MULTI_SERVICE_URI = OP_AUTH_TOKEN_URI +"/multi";
public static final String OP_AUTH_KEY_URI = "/publickey";
public static final String OP_AUTH_INTRA_CHECK_URI = "/intracloud/check";
public static final String OP_AUTH_INTER_CHECK_URI = "/intercloud/check";
public static final String OP_AUTH_SUBSCRIPTION_CHECK_URI = "/subscription/check";
public static final String CERTIFICATEAUTHRORITY_URI = "/certificate-authority";
public static final String OP_CA_MGMT_CERTIFICATES_URI = "/mgmt/certificates";
public static final String OP_CA_MGMT_CERTIFICATES_URI_SUFFIX = "/{" + COMMON_FIELD_NAME_ID + "}";
public static final String OP_CA_MGMT_TRUSTED_KEYS_URI = "/mgmt/keys";
public static final String OP_CA_MGMT_TRUSTED_KEYS_URI_SUFFIX = "/{" + COMMON_FIELD_NAME_ID + "}";
public static final String OP_CA_CHECK_CERTIFICATE_URI = "/checkCertificate";
public static final String OP_CA_CHECK_TRUSTED_KEY_URI = "/checkTrustedKey";
public static final String OP_CA_SIGN_CERTIFICATE_URI = "/sign";
public static final String ORCHESTRATOR_URI = "/orchestrator";
public static final String OP_ORCH_PROCESS_URI = "/orchestration";
public static final String OP_ORCH_PROCESS_BY_PROXY_URI = "/orchestration-by-proxy";
public static final String OP_ORCH_CREATE_FLEXIBLE_STORE_RULES_URI = "/store/flexible";
public static final String OP_ORCH_REMOVE_FLEXIBLE_STORE_RULE_URI = "/store/flexible" + "/{" + COMMON_FIELD_NAME_ID + "}";
public static final String OP_ORCH_CLEAN_FLEXIBLE_STORE_URI = "/store/flexible/all";
public static final String OP_ORCH_QOS_ENABLED_URI = "/qos_enabled";
public static final String OP_ORCH_QOS_RESERVATIONS_URI = "/qos_reservations";
public static final String OP_ORCH_QOS_TEMPORARY_LOCK_URI = "/qos_temporary_lock";
public static final String ORCHESTRATION_FLAG_MATCHMAKING = "matchmaking";
public static final String ORCHESTRATION_FLAG_METADATA_SEARCH = "metadataSearch";
public static final String ORCHESTRATION_FLAG_ONLY_PREFERRED = "onlyPreferred";
public static final String ORCHESTRATION_FLAG_PING_PROVIDERS = "pingProviders";
public static final String ORCHESTRATION_FLAG_OVERRIDE_STORE = "overrideStore";
public static final String ORCHESTRATION_FLAG_TRIGGER_INTER_CLOUD = "triggerInterCloud";
public static final String ORCHESTRATION_FLAG_EXTERNAL_SERVICE_REQUEST = "externalServiceRequest";
public static final String ORCHESTRATION_FLAG_ENABLE_INTER_CLOUD = "enableInterCloud";
public static final String ORCHESTRATION_FLAG_ENABLE_QOS = "enableQoS";
public static final String ORCHESTRATION_FLAG_ONLY_IP_ADDRESS_RESPONSE = "onlyIPAddressResponse";
public static final String ORCHESTRATION_FLAG_ONLY_IPV4_ADDRESS_RESPONSE = "onlyIPv4AddressResponse";
public static final String ORCHESTRATION_FLAG_ONLY_IPV6_ADDRESS_RESPONSE = "onlyIPv6AddressResponse";
public static final String GATEKEEPER_URI = "/gatekeeper";
public static final String OP_GATEKEEPER_GSD_SERVICE = "/init_gsd";
public static final String OP_GATEKEEPER_MULTI_GSD_SERVICE = "/init_multi_gsd";
public static final String OP_GATEKEEPER_ICN_SERVICE = "/init_icn";
public static final String OP_GATEKEEPER_PULL_CLOUDS_SERVICE = "/pull_clouds";
public static final String OP_GATEKEEPER_COLLECT_SYSTEM_ADDRESSES_SERVICE = "/collect_system_addresses";
public static final String OP_GATEKEEPER_COLLECT_ACCESS_TYPES_SERVICE = "/collect_access_types";
public static final String OP_GATEKEEPER_RELAY_TEST_SERVICE = "/init_relay_test";
public static final String OP_GATEKEEPER_GET_CLOUD_SERVICE = "/cloud/";
public static final String OP_GATEKEEPER_GET_CLOUD_SERVICE_SUFFIX = "{operator}/{name}";
public static final String CONFIGURATION_URI = "/configuration";
public static final String OP_CONFIGURATION_CONF = "/config";
public static final String OP_CONFIGURATION_RAWCONF = "/config/raw";
public static final String OP_CONFIGURATION_MGMT_MANAGE = "/mgmt/config";
public static final String CHOREOGRAPHER_URI = "/choreographer";
public static final String CHOREOGRAPHER_SESSION_MGMT_URI = CoreCommonConstants.MGMT_URI + "/session";
public static final String CHOREOGRAPHER_SESSION_STEPS_MGMT_URI = CoreCommonConstants.MGMT_URI + "/session/steps";
public static final String CHOREOGRAPHER_WORKLOG_MGMT_URI = CoreCommonConstants.MGMT_URI + "/worklog";
public static final String CHOREOGRAPHER_EXECUTOR_MGMT_URI = CoreCommonConstants.MGMT_URI + "/executor";
public static final String CHOREOGRAPHER_EXECUTOR_MGMT_BY_ID_URI = CHOREOGRAPHER_EXECUTOR_MGMT_URI + "/{id}";
public static final String CHOREOGRAPHER_EXECUTOR_CLIENT_SERVICE_INFO_URI = "/service-info";
public static final String CHOREOGRAPHER_EXECUTOR_CLIENT_SERVICE_START_URI = "/start";
public static final String CHOREOGRAPHER_EXECUTOR_CLIENT_SERVICE_ABORT_URI = "/abort";
public static final String OP_CHOREOGRAPHER_EXECUTOR_REGISTER = "/executor/register";
public static final String OP_CHOREOGRAPHER_EXECUTOR_UNREGISTER = "/executor/unregister";
public static final String OP_CHOREOGRAPHER_NOTIFY_STEP_DONE = "/executor/notify-step-done";
public static final String OP_CHOREOGRAPHER_EXECUTOR_UNREGISTER_REQUEST_PARAM_NAME = "name";
public static final String GATEWAY_URI = "/gateway";
public static final String OP_GATEWAY_KEY_URI = "/publickey";
public static final String OP_GATEWAY_CONNECT_PROVIDER_URI = "/connect_provider";
public static final String OP_GATEWAY_CONNECT_CONSUMER_URI = "/connect_consumer";
public static final String OP_GATEWAY_CLOSE_SESSIONS = "/close_sessions";
public static final String EVENTHANDLER_URI = "/eventhandler";
public static final String OP_EVENTHANDLER_PUBLISH = "/publish";
public static final String OP_EVENTHANDLER_SUBSCRIBE = "/subscribe";
public static final String OP_EVENTHANDLER_UNSUBSCRIBE = "/unsubscribe";
public static final String OP_EVENTHANDLER_PUBLISH_AUTH_UPDATE = "/publish/authupdate";
public static final String QOSMONITOR_URI = "/qosmonitor";
public static final String OP_QOSMONITOR_INTRA_PING_MEASUREMENT = "/measurements/intracloud/ping";
public static final String OP_QOSMONITOR_INTRA_PING_MEASUREMENT_SUFFIX = "/{" + COMMON_FIELD_NAME_ID + "}";
public static final String OP_QOSMONITOR_INTRA_PING_MEDIAN_MEASUREMENT = "/measurements/intracloud/ping_median/{attribute}";
public static final String OP_QOSMONITOR_INTER_DIRECT_PING_MEASUREMENT = "/measurements/intercloud/ping";
public static final String OP_QOSMONITOR_INTER_RELAY_ECHO_MEASUREMENT = "/measurements/intercloud/relay_echo";
public static final String OP_QOSMONITOR_KEY_URI = "/publickey";
public static final String OP_QOSMONITOR_JOIN_RELAY_TEST_URI = "/join_relay_test";
public static final String OP_QOSMONITOR_INIT_RELAY_TEST_URI = "/init_relay_test";
public static final String DATAMANAGER_URI = "/datamanager";
public static final String OP_DATAMANAGER_PROXY = "/proxy";
public static final String OP_DATAMANAGER_HISTORIAN = "/historian";
public static final String TIMEMANAGER_URI = "/timemanager";
public static final String OP_TIMEMANAGER_TIME = "/time";
public static final String TRANSLATOR_URI = "/translator";
public static final String OP_TRANSLATOR_FIWARE_URI = "/v2";
public static final String OP_TRANSLATOR_PLUGIN_URI = "/plugin";
public static final String MSCV_URI = "/mscv";
public static final String OP_MSCV_EXECUTE_URI = "/execute";
public static final String OP_MSCV_EVENT_CALLBACK_URI = "/event_callback";
public static final String OP_MSCV_LOGIN_URI = "/login";
public static final String OP_MSCV_PUBLIC_KEY_URI = "/publickey";
public static final String OP_GAMS_SERVICE_URI = "";
public static final String OP_GAMS_SENSOR_SERVICE_URI = "/{gams_uid}/sensor";
public static final String SWAGGER_COMMON_PACKAGE = "eu.arrowhead.common.swagger";
public static final String SWAGGER_UI_URI = "/swagger-ui.html";
public static final String SWAGGER_HTTP_200_MESSAGE = "Core service is available";
public static final String SWAGGER_HTTP_400_MESSAGE = "Bad request";
public static final String SWAGGER_HTTP_401_MESSAGE = "You are not authorized";
public static final String SWAGGER_HTTP_409_MESSAGE = "Request caused a conflict";
public static final String SWAGGER_HTTP_500_MESSAGE = "Core service is not available";
public static final String REQUEST_PARAM_TOKEN = "token";
public static final String ECHO_URI = "/echo";
public static final List<CoreSystemService> PUBLIC_CORE_SYSTEM_SERVICES = List.of(CoreSystemService.ORCHESTRATION_SERVICE, CoreSystemService.AUTH_PUBLIC_KEY_SERVICE,
CoreSystemService.EVENT_PUBLISH_SERVICE, CoreSystemService.EVENT_SUBSCRIBE_SERVICE, CoreSystemService.EVENT_UNSUBSCRIBE_SERVICE,
CoreSystemService.PROXY_SERVICE, CoreSystemService.HISTORIAN_SERVICE, CoreSystemService.CHOREOGRAPHER_SERVICE, CoreSystemService.CHOREOGRAPHER_REGISTER_EXECUTOR_SERVICE,
CoreSystemService.CHOREOGRAPHER_UNREGISTER_EXECUTOR_SERVICE, CoreSystemService.TRANSLATOR_SERVICE,
CoreSystemService.CONFIGURATION_SERVICE, CoreSystemService.CONFIGURATION_RAW_SERVICE, CoreSystemService.TIME_SERVICE);
public static final String HTTP_CLIENT_CONNECTION_TIMEOUT = "http.client.connection.timeout";
public static final String $HTTP_CLIENT_CONNECTION_TIMEOUT_WD = "${" + HTTP_CLIENT_CONNECTION_TIMEOUT + ":" + Defaults.DEFAULT_CONNECTION_TIMEOUT + "}";
public static final String HTTP_CLIENT_SOCKET_TIMEOUT = "http.client.socket.timeout";
public static final String $HTTP_CLIENT_SOCKET_TIMEOUT_WD = "${" + HTTP_CLIENT_SOCKET_TIMEOUT + ":" + Defaults.DEFAULT_SOCKET_TIMEOUT + "}";
public static final String HTTP_CLIENT_CONNECTION_MANAGER_TIMEOUT = "http.client.connection.manager.timeout";
public static final String $HTTP_CLIENT_CONNECTION_MANAGER_TIMEOUT_WD = "${" + HTTP_CLIENT_CONNECTION_MANAGER_TIMEOUT + ":" + Defaults.DEFAULT_CONNECTION_MANAGER_TIMEOUT + "}";
public static final String COMMON_NAME_FIELD_NAME = "CN";
public static final String ATTR_JAVAX_SERVLET_REQUEST_X509_CERTIFICATE = "javax.servlet.request.X509Certificate";
public static final String SERVER_SSL_ENABLED = "server.ssl.enabled";
public static final String $SERVER_SSL_ENABLED_WD = "${" + SERVER_SSL_ENABLED + ":" + Defaults.DEFAULT_SSL_SERVER_ENABLED + "}";
public static final String WEBSOCKETS_ENABLED = "websockets.enabled";
public static final String $WEBSOCKETS_ENABLED_WD = "${" + WEBSOCKETS_ENABLED + ":" + Defaults.DEFAULT_WEBSOCKETS_ENABLED + "}";
public static final String KEYSTORE_TYPE = "server.ssl.key-store-type";
public static final String $KEYSTORE_TYPE_WD = "${" + KEYSTORE_TYPE + ":" + Defaults.DEFAULT_KEYSTORE_TYPE + "}";
public static final String KEYSTORE_PATH = "server.ssl.key-store";
public static final String $KEYSTORE_PATH_WD = "${" + KEYSTORE_PATH + ":" + Defaults.DEFAULT_KEYSTORE_PATH + "}";
public static final String KEYSTORE_PASSWORD = "server.ssl.key-store-password"; //NOSONAR it is not a password
public static final String $KEYSTORE_PASSWORD_WD = "${" + KEYSTORE_PASSWORD + ":" + Defaults.DEFAULT_KEYSTORE_PASSWORD + "}"; //NOSONAR it is not a password
public static final String KEY_PASSWORD = "server.ssl.key-password"; //NOSONAR it is not a password
public static final String $KEY_PASSWORD_WD = "${" + KEY_PASSWORD + ":" + Defaults.DEFAULT_KEY_PASSWORD + "}"; //NOSONAR it is not a password
public static final String TRUSTSTORE_PATH = "server.ssl.trust-store";
public static final String $TRUSTSTORE_PATH_WD = "${" + TRUSTSTORE_PATH + ":" + Defaults.DEFAULT_TRUSTSTORE_PATH + "}";
public static final String TRUSTSTORE_PASSWORD = "server.ssl.trust-store-password"; //NOSONAR it is not a password
public static final String $TRUSTSTORE_PASSWORD_WD = "${" + TRUSTSTORE_PASSWORD + ":" + Defaults.DEFAULT_TRUSTSTORE_PATH + "}"; //NOSONAR it is not a password
public static final String DISABLE_HOSTNAME_VERIFIER = "disable.hostname.verifier";
public static final String $DISABLE_HOSTNAME_VERIFIER_WD = "${" + DISABLE_HOSTNAME_VERIFIER + ":" + Defaults.DEFAULT_DISABLE_HOSTNAME_VERIFIER + "}";
public static final String CA_CERT_VALIDITY_NEG_OFFSET_MINUTES = "ca.validity.negative-offest-minutes";
public static final String $CA_CERT_VALIDITY_NEG_OFFSET_MINUTES = "${" + CA_CERT_VALIDITY_NEG_OFFSET_MINUTES + ":" + Defaults.DEFAULT_CA_CERT_VALIDITY_NEG_OFFSET_MINUTES + "}";
public static final String CA_CERT_VALIDITY_POS_OFFSET_MINUTES = "ca.validity.positive-offest-minutes";
public static final String $CA_CERT_VALIDITY_POS_OFFSET_MINUTES = "${" + CA_CERT_VALIDITY_POS_OFFSET_MINUTES + ":" + Defaults.DEFAULT_CA_CERT_VALIDITY_POS_OFFSET_MINUTES + "}";
public static final String CA_CERT_KEYSTORE_TYPE = "cloud.ssl.key-store-type";
public static final String $CA_CERT_KEYSTORE_TYPE = "${" + CA_CERT_KEYSTORE_TYPE + "}";
public static final String CA_CERT_KEYSTORE_PATH = "cloud.ssl.key-store";
public static final String $CA_CERT_KEYSTORE_PATH = "${" + CA_CERT_KEYSTORE_PATH + "}";
public static final String CA_CERT_KEYSTORE_PASSWORD = "cloud.ssl.key-store-password"; //NOSONAR it is not a password
public static final String $CA_CERT_KEYSTORE_PASSWORD = "${" + CA_CERT_KEYSTORE_PASSWORD + "}"; //NOSONAR it is not a password
public static final String CA_CERT_KEY_PASSWORD = "cloud.ssl.key-password"; //NOSONAR it is not a password
public static final String $CA_CERT_KEY_PASSWORD = "${" + CA_CERT_KEY_PASSWORD + "}"; //NOSONAR it is not a password
public static final String JWT_CLAIM_CONSUMER_ID = "cid";
public static final String JWT_CLAIM_SERVICE_ID = "sid";
public static final String JWT_CLAIM_INTERFACE_ID = "iid";
public static final String JWT_CLAIM_MESSAGE_TYPE = "mst";
public static final String JWT_CLAIM_SESSION_ID = "sid"; // can be the same as service id because we don't use service id and session id at the same time
public static final String JWT_CLAIM_PAYLOAD = "pld";
public static final String JWE_KEY_MANAGEMENT_ALG = KeyManagementAlgorithmIdentifiers.RSA_OAEP_256;
public static final String JWE_ENCRYPTION_ALG = ContentEncryptionAlgorithmIdentifiers.AES_256_CBC_HMAC_SHA_512;
public static final String JWS_SIGN_ALG = AlgorithmIdentifiers.RSA_USING_SHA512;
public static final int SYSTEM_PORT_RANGE_MIN = 0;
public static final int SYSTEM_PORT_RANGE_MAX = 65535;
public static final long CONVERSION_MILLISECOND_TO_SECOND = 1000;
public static final long CONVERSION_MILLISECOND_TO_MINUTE = 60000;
public static final long CONVERSION_SECOND_TO_MINUTE = 60;
public static final String SORT_ORDER_ASCENDING = "ASC";
public static final String SORT_ORDER_DESCENDING = "DESC";
public static final String SORT_FIELD_PRIORITY = "priority";
public static final String INTRA_CLOUD_PROVIDER_MATCHMAKER = "intraCloudProviderMatchmaker";
public static final String INTER_CLOUD_PROVIDER_MATCHMAKER = "interCloudProviderMatchmaker";
public static final String ICN_PROVIDER_MATCHMAKER = "icnProviderMatchmaker";
public static final String GATEKEEPER_MATCHMAKER = "gatekeeperMatchmaker";
public static final String GATEWAY_MATCHMAKER = "gatewayMatchmaker";
public static final String CLOUD_MATCHMAKER = "cloudMatchmaker";
public static final int TOP_PRIORITY = 1;
public static final String EVENT_METADATA_FILTER = "metadataFilter";
public static final String LOCALHOST = "localhost";
public static final int HTTP_PORT = 8080;
public static final String OP_EVENTHANDLER_UNSUBSCRIBE_REQUEST_PARAM_EVENT_TYPE = "event_type";
public static final String OP_EVENTHANDLER_UNSUBSCRIBE_REQUEST_PARAM_SUBSCRIBER_SYSTEM_NAME = "system_name";
public static final String OP_EVENTHANDLER_UNSUBSCRIBE_REQUEST_PARAM_SUBSCRIBER_ADDRESS = "address";
public static final String OP_EVENTHANDLER_UNSUBSCRIBE_REQUEST_PARAM_SUBSCRIBER_PORT = "port";
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private CommonConstants() {
throw new UnsupportedOperationException();
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/Defaults.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common;
public class Defaults {
//=================================================================================================
// members
public static final int DEFAULT_VERSION = 1;
public static final boolean DEFAULT_SSL_SERVER_ENABLED = true;
public static final boolean DEFAULT_WEBSOCKETS_ENABLED = false;
public static final String DEFAULT_KEYSTORE_TYPE = "PKCS12";
public static final String DEFAULT_KEYSTORE_PATH = "";
public static final String DEFAULT_KEYSTORE_PASSWORD = "";
public static final String DEFAULT_KEY_PASSWORD = "";
public static final String DEFAULT_TRUSTSTORE_PATH = "";
public static final String DEFAULT_TRUSTSTORE_PASSWORD ="";
public static final boolean DEFAULT_DISABLE_HOSTNAME_VERIFIER = false;
public static final boolean DEFAULT_LOG_ALL_REQUEST_AND_RESPONSE = false;
public static final int DEFAULT_URI_CRAWLER_INTERVAL = 30;
public static final int DEFAULT_AUTH_TOKEN_TTL_IN_MINUTES = -1; // never expires
public static final String DEFAULT_SERVICEREGISTRY_ADDRESS = CommonConstants.LOCALHOST;
public static final int DEFAULT_ONBOARDING_PORT = 8435;
public static final int DEFAULT_SYSTEMREGISTRY_PORT = 8437;
public static final int DEFAULT_DEVICEREGISTRY_PORT = 8439;
public static final int DEFAULT_ORCHESTRATOR_PORT = 8441;
public static final int DEFAULT_SERVICEREGISTRY_PORT = 8443;
public static final int DEFAULT_AUTHORIZATION_PORT = 8445;
public static final int DEFAULT_GATEKEEPER_PORT = 8449;
public static final int DEFAULT_QOSMONITOR_PORT = 8451;
public static final int DEFAULT_GATEWAY_PORT = 8453;
public static final int DEFAULT_EVENTHANDLER_PORT = 8455;
public static final int DEFAULT_DATAMANAGER_PORT = 8461;
public static final int DEFAULT_TIMEMANAGER_PORT = 8463;
public static final int DEFAULT_CHOREOGRAPHER_PORT = 8457;
public static final int DEFAULT_CERTIFICATEAUTHORITY_PORT = 8448;
public static final int DEFAULT_CONFIGURATION_PORT = 8459;
public static final int DEFAULT_CERTIFICATE_AUTHORITY_PORT = 8448;
public static final int DEFAULT_GENERIC_AUTONOMIC_MANAGEMENT_PORT = 8502;
public static final int DEFAULT_TRANSLATOR_PORT = 8462;
public static final int DEFAULT_MSCV_PORT = 8501;
public static final int DEFAULT_PLANT_DESCRIPTION_ENGINE_PORT = 8432;
public static final int DEFAULT_HAWKBIT_CONFIGURATION_MANAGER_PORT = 8447;
// HTTP client defaults
public static final int DEFAULT_CONNECTION_TIMEOUT = 30000;
public static final int DEFAULT_SOCKET_TIMEOUT = 30000;
public static final int DEFAULT_CONNECTION_MANAGER_TIMEOUT = 10000;
// CORS defaults
public static final long CORS_MAX_AGE = 600;
public static final String CORS_ALLOW_CREDENTIALS = "true";
// CA defaults
public static final long DEFAULT_CA_CERT_VALIDITY_NEG_OFFSET_MINUTES = 1;
public static final long DEFAULT_CA_CERT_VALIDITY_POS_OFFSET_MINUTES = 60 * 24 * 365;
//-------------------------------------------------------------------------------------------------
private Defaults() {
throw new UnsupportedOperationException();
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/SSLProperties.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import eu.arrowhead.common.exception.InvalidParameterException;
@Component
public class SSLProperties {
//=================================================================================================
// members
@Value(CommonConstants.$SERVER_SSL_ENABLED_WD)
private boolean sslEnabled;
@Value(CommonConstants.$KEYSTORE_TYPE_WD)
private String keyStoreType;
@Value(CommonConstants.$KEYSTORE_PATH_WD)
private String keyStorePath;
private Resource keyStore;
@Value(CommonConstants.$KEYSTORE_PASSWORD_WD)
private String keyStorePassword;
@Value(CommonConstants.$KEY_PASSWORD_WD)
private String keyPassword;
@Value(CommonConstants.$TRUSTSTORE_PATH_WD)
private String trustStorePath;
private Resource trustStore;
@Value(CommonConstants.$TRUSTSTORE_PASSWORD_WD)
private String trustStorePassword;
@Autowired
private ResourceLoader resourceLoader;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public boolean isSslEnabled() { return sslEnabled; }
public String getKeyStoreType() { return keyStoreType; }
public Resource getKeyStore() { return keyStore; }
public String getKeyStorePassword() { return keyStorePassword; }
public String getKeyPassword() { return keyPassword; }
public Resource getTrustStore() { return trustStore; }
public String getTrustStorePassword() { return trustStorePassword; }
//-------------------------------------------------------------------------------------------------
@PostConstruct
private void validate() {
if (sslEnabled) {
if (Utilities.isEmpty(keyStoreType)) {
throw new InvalidParameterException("keyStoreType is missing");
}
if (Utilities.isEmpty(keyStorePath)) {
throw new InvalidParameterException("keyStorePath is missing");
} else {
keyStore = resourceLoader.getResource(keyStorePath);
}
if (Utilities.isEmpty(keyStorePassword)) {
throw new InvalidParameterException("keyStorePassword is missing");
}
if (Utilities.isEmpty(keyPassword)) {
throw new InvalidParameterException("keyPassword is missing");
}
if (Utilities.isEmpty(trustStorePath)) {
throw new InvalidParameterException("trustStorePath is missing");
} else {
trustStore = resourceLoader.getResource(trustStorePath);
}
if (Utilities.isEmpty(trustStorePassword)) {
throw new InvalidParameterException("trustStorePassword is missing");
}
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/SecurityUtilities.java
|
/********************************************************************************
* Copyright (c) 2020 FHB
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* FHB - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Objects;
import java.util.ServiceConfigurationError;
import javax.servlet.http.HttpServletRequest;
import eu.arrowhead.common.dto.shared.CertificateCreationRequestDTO;
import eu.arrowhead.common.dto.shared.CertificateCreationResponseDTO;
import eu.arrowhead.common.dto.shared.CertificateType;
import eu.arrowhead.common.dto.shared.KeyPairDTO;
import eu.arrowhead.common.exception.ArrowheadException;
import eu.arrowhead.common.exception.AuthException;
import org.apache.http.HttpStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNamesBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.http.server.ServletServerHttpRequest;
@Component
public class SecurityUtilities {
//=================================================================================================
// members
private final static String SIGNATURE_ALGORITHM = "SHA256WithRSA";
private static final String X509_FORMAT = "X.509";
private static final String PKCS8_FORMAT = "PKCS#8";
private static final String PKCS1_FORMAT = "PKCS#1";
private final Logger logger = LogManager.getLogger(SecurityUtilities.class);
private final KeyFactory keyFactory;
private final KeyPairGenerator keyPairGenerator;
private final SSLProperties sslProperties;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
@Autowired
public SecurityUtilities(@Value("${security.key.algorithm:RSA}") final String keyFactoryAlgorithm,
@Value("${security.key.size:2048}") final Integer keySize,
final SSLProperties sslProperties) throws NoSuchAlgorithmException {
Assert.hasText(keyFactoryAlgorithm, "keyFactoryAlgorithm must not be null");
Assert.notNull(keySize, "keyFactoryAlgorithm keySize not be null");
Assert.notNull(sslProperties, "sslProperties must not be null");
this.sslProperties = sslProperties;
keyFactory = KeyFactory.getInstance(keyFactoryAlgorithm);
keyPairGenerator = KeyPairGenerator.getInstance(keyFactoryAlgorithm);
keyPairGenerator.initialize(keySize);
}
//-------------------------------------------------------------------------------------------------
public static String getCertificateCNFromRequest(final HttpServletRequest request) {
Assert.notNull(request, "request must not be null");
final X509Certificate[] certificates = (X509Certificate[]) request.getAttribute(CommonConstants.ATTR_JAVAX_SERVLET_REQUEST_X509_CERTIFICATE);
if (certificates != null && certificates.length != 0) {
for(final X509Certificate cert : certificates) {
final String fullCN = Utilities.getCertCNFromSubject(cert.getSubjectDN().getName());
if(Objects.isNull(fullCN)) { continue; }
final String[] strings = fullCN.split("\\.");
if(strings.length != 5) { continue; }
return fullCN;
}
}
return null;
}
//-------------------------------------------------------------------------------------------------
public static String getCertificateCNFromServerRequest(final ServletServerHttpRequest request) {
Assert.notNull(request, "request must not be null");
final HttpServletRequest servletRequest = request.getServletRequest();
return getCertificateCNFromRequest(servletRequest);
}
//-------------------------------------------------------------------------------------------------
private static String getCommonNameFromCloudCertificate(final Principal principal) {
Assert.notNull(principal, "Principal must not be null");
return Utilities.getCertCNFromSubject(principal.getName());
}
//-------------------------------------------------------------------------------------------------
private static String getOperatorNameFromCloudCertificate(final Principal principal) {
return extractCNPart(principal, 2);
}
//-------------------------------------------------------------------------------------------------
private static String getOrganizationFromCloudCertificate(final Principal principal) {
return extractCNPart(principal, 1);
}
//-------------------------------------------------------------------------------------------------
private static String getCountryFromCloudCertificate(final Principal principal) {
return extractCNPart(principal, 0);
}
//-------------------------------------------------------------------------------------------------
private static String extractCNPart(final Principal principal, final int tailIndex) {
Assert.notNull(principal, "Principal must not be null");
Assert.isTrue(tailIndex >= 0, "tailIndex must not be negative");
final String fullCN = principal.getName();
Assert.hasText(fullCN, "Empty common name is not allowed");
final String[] strings = fullCN.split("\\.");
if (tailIndex >= strings.length) {
throw new IllegalArgumentException("Internal error: Unable to extract information from cloud certificate");
}
return strings[strings.length - (tailIndex + 1)];
}
//-------------------------------------------------------------------------------------------------
public void authenticateCertificate(final HttpServletRequest httpServletRequest, final CertificateType minimumStrength) {
Assert.notNull(httpServletRequest, "httpServletRequest must not be null");
Assert.notNull(minimumStrength, "minimumStrength must not be null");
final X509Certificate[] certificates = (X509Certificate[]) httpServletRequest.getAttribute(CommonConstants.ATTR_JAVAX_SERVLET_REQUEST_X509_CERTIFICATE);
if (sslProperties.isSslEnabled()) {
if (Objects.nonNull(certificates) && certificates.length > 0) {
final String clientCN = getCertificateCNFromRequest(httpServletRequest);
final String requestTarget = Utilities.stripEndSlash(httpServletRequest.getRequestURL().toString());
authenticateCertificate(clientCN, requestTarget, minimumStrength);
} else {
logger.debug("No client certificate given!");
throw new AuthException("Client certificate in needed!");
}
}
}
//-------------------------------------------------------------------------------------------------
public void authenticateCertificate(final String clientCN, final String requestTarget, final CertificateType minimumStrength) {
Assert.notNull(clientCN, "clientCN must not be null");
Assert.notNull(requestTarget, "requestTarget must not be null");
Assert.notNull(minimumStrength, "minimumStrength must not be null");
if (sslProperties.isSslEnabled()) {
final CertificateType type = CertificateType.getTypeFromCN(clientCN);
if (!type.hasMinimumStrength(minimumStrength)) {
logger.debug("{} is not a valid common name, access denied!", clientCN);
throw new AuthException(clientCN + " is unauthorized to access " + requestTarget);
}
}
}
//-------------------------------------------------------------------------------------------------
public KeyStore getKeyStore() {
try {
final KeyStore keystore = KeyStore.getInstance(sslProperties.getKeyStoreType());
keystore.load(sslProperties.getKeyStore()
.getInputStream(),
sslProperties.getKeyStorePassword()
.toCharArray());
return keystore;
} catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) {
throw new ServiceConfigurationError("Cannot open keystore: " + e.getMessage());
}
}
//-------------------------------------------------------------------------------------------------
public String createCertificateSigningRequest(final String baseCommonName, final KeyPair keyPair, final CertificateType type,
final String host, final String address)
throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, OperatorCreationException {
Assert.hasText(baseCommonName, "baseCommonName must not be null or empty!");
Assert.notNull(keyPair, "keyPair must not be null");
Assert.notNull(sslProperties.getKeyStore(), "KeyStore property must not be null!");
Assert.hasText(sslProperties.getKeyStorePassword(), "KeyStore password property must not be null or empty!");
Assert.notNull(type, "type must not be null");
// host and address are optional
logger.debug("Preparing Certificate Signing Request ...");
// get cloud certificate for cloudName and operator
final X509Certificate cloudCertFromKeyStore = Utilities.getCloudCertFromKeyStore(getKeyStore());
// "CN=<commonName>.<type>.<cloudName>.<operator>.arrowhead.eu, OU=<operator>, O=arrowhead, C=eu"
final String cloudName = getCommonNameFromCloudCertificate(cloudCertFromKeyStore.getSubjectDN());
final String operator = getOperatorNameFromCloudCertificate(cloudCertFromKeyStore.getSubjectDN());
final String organization = getOrganizationFromCloudCertificate(cloudCertFromKeyStore.getSubjectDN());
final String country = getCountryFromCloudCertificate(cloudCertFromKeyStore.getSubjectDN());
final String commonName = String.format("CN=%s.%s, OU=%s, O=%s, C=%s", type.appendTypeToCN(baseCommonName), cloudName,
operator, organization, country);
final X500Name x500Name = new X500Name(commonName);
logger.debug("Building and Signing Certificate Signing Request for {}", x500Name);
// create certificate signing request
final JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name, keyPair.getPublic());
final GeneralNamesBuilder namesBuilder = new GeneralNamesBuilder();
namesBuilder.addName(new GeneralName(GeneralName.dNSName, "localhost"));
namesBuilder.addName(new GeneralName(GeneralName.dNSName, baseCommonName));
namesBuilder.addName(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
if (StringUtils.hasText(host)) {
namesBuilder.addName(new GeneralName(GeneralName.dNSName, host));
}
if (StringUtils.hasText(address)) {
namesBuilder.addName(new GeneralName(GeneralName.iPAddress, address));
}
final Extension extAlternativeNames = new Extension(Extension.subjectAlternativeName, false, new DEROctetString(namesBuilder.build()));
builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new Extensions(extAlternativeNames));
final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM);
final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());
final PKCS10CertificationRequest csr = builder.build(contentSigner);
return Base64.getEncoder().encodeToString(csr.getEncoded());
}
//-------------------------------------------------------------------------------------------------
public void extractAndSetPublicKey(final CertificateCreationResponseDTO creationResponseDTO) {
Assert.notNull(creationResponseDTO, "creationResponseDTO must not be null");
try {
final byte[] certificateBytes = Base64Utils.decodeFromString(creationResponseDTO.getCertificate());
final Certificate certificate;
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(certificateBytes)) {
final CertificateFactory certificateFactory = CertificateFactory.getInstance(creationResponseDTO.getCertificateFormat());
certificate = certificateFactory.generateCertificate(byteArrayInputStream);
} catch (final CertificateException e) {
logger.error("Unable to generate certificate from Base64: {}", creationResponseDTO.getCertificate());
throw new ArrowheadException("Unable to decode signed certificate", HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
final PublicKey publicKey = certificate.getPublicKey();
creationResponseDTO.setKeyPairDTO(encodePublicKey(publicKey));
} catch (final IOException e) {
logger.fatal("ByteArrayInputStream should never throw an IOException, but it just did : {}", e.getMessage());
throw new ArrowheadException(e.getMessage());
}
}
//-------------------------------------------------------------------------------------------------
public KeyPair extractOrGenerateKeyPair(final CertificateCreationRequestDTO creationRequestDTO) {
Assert.notNull(creationRequestDTO, "creationRequestDTO must not be null");
final String commonName = creationRequestDTO.getCommonName();
Assert.isTrue(Utilities.notEmpty(commonName), "CommonName is null or blank");
final KeyPairDTO keyPairDTO = creationRequestDTO.getKeyPairDTO();
KeyPair keyPair;
if (Objects.nonNull(keyPairDTO) &&
Objects.nonNull(keyPairDTO.getPublicKey()) &&
Objects.nonNull(keyPairDTO.getPrivateKey())) {
final String encodedPublicKey = keyPairDTO.getPublicKey();
final String encodedPrivateKey = keyPairDTO.getPrivateKey();
final String keyFormat = keyPairDTO.getKeyFormat();
if (Objects.nonNull(keyFormat)) {
keyPair = getKeyPairFromBase64EncodedStringsForFormat(encodedPublicKey, encodedPrivateKey, keyFormat);
} else {
try {
keyPair = getKeyPairFromBase64EncodedStringsForFormat(encodedPublicKey, encodedPrivateKey, PKCS8_FORMAT);
} catch (final AuthException e1) {
try {
keyPair = getKeyPairFromBase64EncodedStringsForFormat(encodedPublicKey, encodedPrivateKey, PKCS1_FORMAT);
} catch (final AuthException e2) {
keyPair = getKeyPairFromBase64EncodedStringsForFormat(encodedPublicKey, encodedPrivateKey, X509_FORMAT);
}
}
}
} else {
keyPair = generateKeyPair();
}
return keyPair;
}
//-------------------------------------------------------------------------------------------------
public KeyPairDTO encodePublicKey(final PublicKey publicKey) {
Assert.notNull(publicKey, "PublicKey must not be null");
final String encodedPublicKey = Base64.getEncoder().encodeToString(publicKey.getEncoded());
return new KeyPairDTO(publicKey.getAlgorithm(), publicKey.getFormat(), encodedPublicKey, null);
}
//-------------------------------------------------------------------------------------------------
public KeyPairDTO encodeKeyPair(final KeyPair keyPair) {
Assert.notNull(keyPair, "KeyPair must not be null");
final KeyPairDTO dto = encodePublicKey(keyPair.getPublic());
if (Objects.nonNull(keyPair.getPrivate())) { dto.setPrivateKey(Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); }
return dto;
}
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private KeyPair generateKeyPair() {
return keyPairGenerator.generateKeyPair();
}
//-------------------------------------------------------------------------------------------------
private KeyPair getKeyPairFromBase64EncodedStringsForFormat(final String encodedPublicKey,
final String encodedPrivateKey,
final String keyFormat) {
Assert.notNull(keyFormat, "KeyFormat must not be null");
final byte[] publicKeyBytes = Base64.getDecoder().decode(encodedPublicKey);
final byte[] privateKeyBytes = Base64.getDecoder().decode(encodedPrivateKey);
final EncodedKeySpec publicKeySpec;
final EncodedKeySpec privateKeySpec;
// public key must be x509
publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
if (keyFormat.equalsIgnoreCase(X509_FORMAT)) {
privateKeySpec = new X509EncodedKeySpec(privateKeyBytes);
} else if (keyFormat.equalsIgnoreCase(PKCS8_FORMAT)) {
privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
} else if (keyFormat.equalsIgnoreCase(PKCS1_FORMAT)) {
final byte[] pkcs8Bytes = convertPkcs1ToPkcs8(privateKeyBytes);
privateKeySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
} else {
logger.error("getKeyPairFromBase64EncodedStringsForFormat: Unknown or unsupported key format.");
throw new AuthException("Unknown or unsupported key format.");
}
return generateKeyPairFromSpec(privateKeySpec, publicKeySpec);
}
//-------------------------------------------------------------------------------------------------
private KeyPair generateKeyPairFromSpec(final EncodedKeySpec privateKeySpec, final EncodedKeySpec publicKeySpec) {
final PublicKey publicKey;
final PrivateKey privateKey;
try {
publicKey = keyFactory.generatePublic(publicKeySpec);
} catch (final InvalidKeySpecException ex) {
logger.warn("generateKeyPairFromSpec: Unable to generate public key from key spec format '{}'.",
publicKeySpec.getFormat());
throw new AuthException("Public key decoding failed due to wrong key format", ex);
}
try {
privateKey = keyFactory.generatePrivate(privateKeySpec);
} catch (final InvalidKeySpecException ex) {
logger.warn("generateKeyPairFromSpec: Unable to generate private key from key spec format '{}'.",
privateKeySpec.getFormat());
throw new AuthException("Private key decoding failed due to wrong key format", ex);
}
return new KeyPair(publicKey, privateKey);
}
//-------------------------------------------------------------------------------------------------
private byte[] convertPkcs1ToPkcs8(final byte[] pkcs1Bytes) {
// We can't use Java internal APIs to parse ASN.1 structures, so we build a PKCS#8 key Java can understand
final int pkcs1Length = pkcs1Bytes.length;
final int totalLength = pkcs1Length + 22;
final byte[] pkcs8Header = new byte[]{
0x30, (byte) 0x82, (byte) ((totalLength >> 8) & 0xff), (byte) (totalLength & 0xff), // Sequence + total length
0x2, 0x1, 0x0, // Integer (0)
0x30, 0xD, 0x6, 0x9, 0x2A, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0, // Sequence: 1.2.840.113549.1.1.1, NULL
0x4, (byte) 0x82, (byte) ((pkcs1Length >> 8) & 0xff), (byte) (pkcs1Length & 0xff) // Octet string + length
};
return join(pkcs8Header, pkcs1Bytes);
}
//-------------------------------------------------------------------------------------------------
private byte[] join(final byte[] byteArray1, final byte[] byteArray2) {
final byte[] bytes = new byte[byteArray1.length + byteArray2.length];
System.arraycopy(byteArray1, 0, bytes, 0, byteArray1.length);
System.arraycopy(byteArray2, 0, bytes, byteArray1.length, byteArray2.length);
return bytes;
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/Utilities.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.ServiceConfigurationError;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import eu.arrowhead.common.dto.internal.ChoreographerSessionStepStatus;
import eu.arrowhead.common.dto.internal.QoSMeasurementAttribute;
import eu.arrowhead.common.dto.internal.RelayType;
import eu.arrowhead.common.dto.shared.ChoreographerSessionStatus;
import eu.arrowhead.common.dto.shared.ErrorMessageDTO;
import eu.arrowhead.common.exception.ArrowheadException;
import eu.arrowhead.common.exception.AuthException;
import eu.arrowhead.common.exception.BadPayloadException;
import eu.arrowhead.common.exception.DataNotFoundException;
import eu.arrowhead.common.exception.InvalidParameterException;
import eu.arrowhead.common.exception.TimeoutException;
import eu.arrowhead.common.exception.UnavailableServerException;
public class Utilities {
//=================================================================================================
// members
private static final int SERVICE_CN_NAME_LENGTH = 5;
@SuppressWarnings("unused")
private static final int CLOUD_CN_NAME_LENGTH = 4;
@SuppressWarnings("unused")
private static final int AH_MASTER_CN_NAME_LENGTH = 2;
private static final String AH_MASTER_SUFFIX = "eu";
private static final String AH_MASTER_NAME = "arrowhead";
private static final String KEY_FACTORY_ALGORHITM_NAME = "RSA";
private static final KeyFactory keyFactory;
private static final Pattern PEM_PATTERN = Pattern.compile("(?m)(?s)^---*BEGIN.*---*$(.*)^---*END.*---*$.*");
private static final String MAC_ADDRESS_PATTERN_STRING = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
public static final Pattern MAC_ADDRESS_PATTERN = Pattern.compile(MAC_ADDRESS_PATTERN_STRING);
private static final Logger logger = LogManager.getLogger(Utilities.class);
private static final ObjectMapper mapper = new ObjectMapper();
static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_INSTANT;
static {
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
try {
keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORHITM_NAME);
} catch (final NoSuchAlgorithmException ex) {
logger.fatal("KeyFactory.getInstance(String) throws NoSuchAlgorithmException, code needs to be changed!");
throw new ServiceConfigurationError("KeyFactory.getInstance(String) throws NoSuchAlgorithmException, code needs to be changed!", ex);
}
}
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public static boolean isEmpty(final String str) {
return str == null || str.isBlank();
}
//-------------------------------------------------------------------------------------------------
public static boolean isEmpty(final Map<?,?> map) {
return map == null || map.isEmpty();
}
//-------------------------------------------------------------------------------------------------
public static boolean isEmpty(final Collection<?> collection) {
return collection == null || collection.isEmpty();
}
//-------------------------------------------------------------------------------------------------
public static boolean notEmpty(final String str) {
return StringUtils.hasText(str);
}
//-------------------------------------------------------------------------------------------------
@Nullable
public static String stripEndSlash(final String uri) {
if (uri != null && uri.endsWith("/")) {
return uri.substring(0, uri.length() - 1);
}
return uri;
}
//-------------------------------------------------------------------------------------------------
public static String convertZonedDateTimeToUTCString(final ZonedDateTime time) {
if (time == null) {
return null;
}
return dateTimeFormatter.format(time.toInstant());
}
//-------------------------------------------------------------------------------------------------
@SuppressWarnings("squid:RedundantThrowsDeclarationCheck")
public static ZonedDateTime parseUTCStringToLocalZonedDateTime(final String timeStr) throws DateTimeParseException {
if (isEmpty(timeStr)) {
return null;
}
final TemporalAccessor tempAcc = dateTimeFormatter.parse(timeStr);
return ZonedDateTime.ofInstant(Instant.from(tempAcc), ZoneId.systemDefault());
}
//-------------------------------------------------------------------------------------------------
@SuppressWarnings("squid:RedundantThrowsDeclarationCheck")
public static ZonedDateTime parseDBLocalStringToUTCZonedDateTime(final String timeStr) throws DateTimeParseException {
if (isEmpty(timeStr)) {
return null;
}
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final TemporalAccessor tempAcc = formatter.parse(timeStr);
final ZonedDateTime parsedDateTime = ZonedDateTime.of(tempAcc.get(ChronoField.YEAR),
tempAcc.get(ChronoField.MONTH_OF_YEAR),
tempAcc.get(ChronoField.DAY_OF_MONTH),
tempAcc.get(ChronoField.HOUR_OF_DAY),
tempAcc.get(ChronoField.MINUTE_OF_HOUR),
tempAcc.get(ChronoField.SECOND_OF_MINUTE),
0,
ZoneId.systemDefault());
return ZonedDateTime.ofInstant(parsedDateTime.toInstant(), ZoneOffset.UTC);
}
//-------------------------------------------------------------------------------------------------
@Nullable
public static String toPrettyJson(final String jsonString) {
try {
if (jsonString != null) {
final String jsonString_ = jsonString.trim();
if (jsonString_.startsWith("{")) {
final Object tempObj = mapper.readValue(jsonString_, Object.class);
return mapper.writeValueAsString(tempObj);
} else {
final Object[] tempObj = mapper.readValue(jsonString_, Object[].class);
return mapper.writeValueAsString(tempObj);
}
}
} catch (final IOException ex) {
// it seems it is not a JSON string, so we just return untouched
}
return jsonString;
}
//-------------------------------------------------------------------------------------------------
@Nullable
public static String toJson(final Object object) {
if (object == null) {
return null;
}
try {
return mapper.writeValueAsString(object);
} catch (final JsonProcessingException ex) {
throw new ArrowheadException("The specified object cannot be converted to text.", ex);
}
}
//-------------------------------------------------------------------------------------------------
@Nullable
public static <T> T fromJson(final String json, final Class<T> parsedClass) {
if (json == null || parsedClass == null) {
return null;
}
try {
return mapper.readValue(json, parsedClass);
} catch (final IOException ex) {
throw new ArrowheadException("The specified string cannot be converted to a(n) " + parsedClass.getSimpleName() + " object.", ex);
}
}
//-------------------------------------------------------------------------------------------------
@Nullable
public static Map<String,String> text2Map(final String text) {
if (text == null) {
return null;
}
final Map<String,String> result = new HashMap<>();
if (!isEmpty(text.trim())) {
final String[] parts = text.split(",");
for (final String part : parts) {
final String[] pair = part.split("=");
result.put(URLDecoder.decode(pair[0].trim(), StandardCharsets.UTF_8), pair.length == 1 ? "" : URLDecoder.decode(pair[1].trim(), StandardCharsets.UTF_8));
}
}
return result;
}
//-------------------------------------------------------------------------------------------------
@Nullable
public static String map2Text(final Map<String,String> map) {
if (map == null) {
return null;
}
final StringBuilder sb = new StringBuilder();
for (final Entry<String,String> entry : map.entrySet()) {
final String key = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8);
final String value = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8);
sb.append(key).append("=").append(value).append(", ");
}
return map.isEmpty() ? "" : sb.substring(0, sb.length() - 2);
}
//-------------------------------------------------------------------------------------------------
/**
* @param scheme default: http
* @param host default: 127.0.0.1
* @param port default: 80
* @param queryParams default: null
* @param path default: null
* @param pathSegments default: null
*/
public static UriComponents createURI(final String scheme, final String host, final int port, final MultiValueMap<String, String> queryParams, final String path, final String... pathSegments) {
final UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
builder.scheme(Utilities.isEmpty(scheme) ? CommonConstants.HTTP : scheme.trim())
.host(Utilities.isEmpty(host) ? CommonConstants.LOCALHOST : host.trim())
.port(port <= 0 ? CommonConstants.HTTP_PORT : port);
if (queryParams != null) {
builder.queryParams(queryParams);
}
if (pathSegments != null && pathSegments.length > 0) {
builder.pathSegment(pathSegments);
}
if (!Utilities.isEmpty(path)) {
builder.path(path);
}
return builder.build();
}
//-------------------------------------------------------------------------------------------------
public static UriComponents createURI(final String scheme, final String host, final int port, final String path) {
return createURI(scheme, host, port, null, path, (String[]) null);
}
//-------------------------------------------------------------------------------------------------
public static UriComponents createURI(final String scheme, final String host, final int port, final String path, final String... queryParams) {
if (queryParams == null || queryParams.length == 0) {
return createURI(scheme, host, port, path);
}
if (queryParams.length % 2 != 0) {
throw new InvalidParameterException("queryParams variable arguments conatins a key without value");
}
final LinkedMultiValueMap<String, String> query = new LinkedMultiValueMap<>();
int count = 1;
String key = "";
for (final String vararg : queryParams) {
if (count % 2 != 0) {
query.putIfAbsent(vararg, new ArrayList<>());
key = vararg;
} else {
query.get(key).add(vararg);
}
count++;
}
return createURI(scheme, host, port, query, path);
}
//-------------------------------------------------------------------------------------------------
public static HttpStatus calculateHttpStatusFromArrowheadException(final ArrowheadException ex) {
Assert.notNull(ex, "Exception is null.");
HttpStatus status = HttpStatus.resolve(ex.getErrorCode());
if (status == null) {
switch (ex.getExceptionType()) {
case AUTH:
status = HttpStatus.UNAUTHORIZED;
break;
case BAD_PAYLOAD:
case INVALID_PARAMETER:
status = HttpStatus.BAD_REQUEST;
break;
case DATA_NOT_FOUND:
status = HttpStatus.NOT_FOUND;
break;
case UNAVAILABLE:
case TIMEOUT:
status = HttpStatus.GATEWAY_TIMEOUT;
break;
default:
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
}
return status;
}
//-------------------------------------------------------------------------------------------------
public static RelayType convertStringToRelayType(final String str) {
if (isEmpty(str)) {
return RelayType.GENERAL_RELAY;
}
try {
return RelayType.valueOf(str.toUpperCase().trim());
} catch (final IllegalArgumentException ex) {
return null;
}
}
//-------------------------------------------------------------------------------------------------
public static QoSMeasurementAttribute convertStringToQoSMeasurementAttribute(final String str) {
if (isEmpty(str)) {
throw new InvalidParameterException("Attribute string is null or empty");
}
try {
return QoSMeasurementAttribute.valueOf(str.toUpperCase().trim());
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterException("Unkown attribute string: " + str);
}
}
//-------------------------------------------------------------------------------------------------
public static ChoreographerSessionStatus convertStringToChoreographerSessionStatus(final String str) {
if (isEmpty(str)) {
throw new InvalidParameterException("Status string is null or empty");
}
try {
return ChoreographerSessionStatus.valueOf(str.toUpperCase().trim());
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterException("Unkown status string: " + str);
}
}
//-------------------------------------------------------------------------------------------------
public static ChoreographerSessionStepStatus convertStringToChoreographerSessionStepStatus(final String str) {
if (isEmpty(str)) {
throw new InvalidParameterException("Status string is null or empty");
}
try {
return ChoreographerSessionStepStatus.valueOf(str.toUpperCase().trim());
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterException("Unkown status string: " + str);
}
}
//-------------------------------------------------------------------------------------------------
@Nullable
public static String getCertCNFromSubject(final String subjectName) {
if (subjectName == null) {
return null;
}
try {
// Subject is in LDAP format, we can use the LdapName object for parsing
final LdapName ldapname = new LdapName(subjectName);
for (final Rdn rdn : ldapname.getRdns()) {
// Find the data after the CN field
if (CommonConstants.COMMON_NAME_FIELD_NAME.equalsIgnoreCase(rdn.getType())) {
return (String) rdn.getValue();
}
}
} catch (final InvalidNameException ex) {
logger.warn("InvalidNameException in getCertCNFromSubject: {}", ex.getMessage());
logger.debug("Exception", ex);
}
return null;
}
//-------------------------------------------------------------------------------------------------
public static String getCloudCommonName(final String cloudOperator, final String cloudName) {
Assert.isTrue(!isEmpty(cloudOperator), "Cloud operator is null or blank.");
Assert.isTrue(!isEmpty(cloudName), "Cloud name is null or blank.");
return (cloudName.trim() + "." + cloudOperator.trim() + ".arrowhead.eu").toLowerCase();
}
//-------------------------------------------------------------------------------------------------
public static X509Certificate getSystemCertFromKeyStore(final KeyStore keystore) {
Assert.notNull(keystore, "Key store is not defined.");
try {
// the first certificate is not always the end certificate. java does not guarantee the order
final Enumeration<String> enumeration = keystore.aliases();
while (enumeration.hasMoreElements()) {
final Certificate[] chain = keystore.getCertificateChain(enumeration.nextElement());
if (Objects.nonNull(chain) && chain.length >= 3) {
return (X509Certificate) chain[0];
}
}
throw new ServiceConfigurationError("Getting the first cert from keystore failed...");
} catch (final KeyStoreException | NoSuchElementException ex) {
logger.error("Getting the first cert from key store failed...", ex);
throw new ServiceConfigurationError("Getting the first cert from keystore failed...", ex);
}
}
//-------------------------------------------------------------------------------------------------
public static X509Certificate getCloudCertFromKeyStore(final KeyStore keystore) {
Assert.notNull(keystore, "Key store is not defined.");
try {
// debian installation with new certificates have a different alias
// i.e. the format is {cloudname}.{cloudoperator}." + AH_MASTER_NAME + "." + AH_MASTER_SUFFIX
final Enumeration<String> enumeration = keystore.aliases();
while (enumeration.hasMoreElements()) {
final String alias = enumeration.nextElement();
final X509Certificate certificate = (X509Certificate) keystore.getCertificate(alias);
if (isCloudCertificate(certificate)) {
return certificate;
}
}
final String errorMsg = "Getting the cloud cert from keystore failed. " +
"Cannot find alias in the following format: {cloudname}.{cloudoperator}." + AH_MASTER_NAME + "." + AH_MASTER_SUFFIX;
logger.error(errorMsg);
throw new ServiceConfigurationError(errorMsg);
} catch (final KeyStoreException | NoSuchElementException ex) {
logger.error("Getting the cloud cert from keystore failed...", ex);
throw new ServiceConfigurationError("Getting the cloud cert from keystore failed...", ex);
}
}
//-------------------------------------------------------------------------------------------------
public static X509Certificate getRootCertFromKeyStore(final KeyStore keystore) {
Assert.notNull(keystore, "Key store is not defined.");
try {
// debian installation with new certificates have a different alias
final Enumeration<String> enumeration = keystore.aliases();
while (enumeration.hasMoreElements()) {
final String alias = enumeration.nextElement();
final X509Certificate certificate = (X509Certificate) keystore.getCertificate(alias);
final String commonName = getCertCNFromSubject(certificate.getSubjectDN().getName());
Assert.notNull(commonName, "Certificate without commonName is not allowed");
final String[] cnParts = commonName.split("\\.");
if (cnParts.length == 2 && cnParts[0].equals(AH_MASTER_NAME) && cnParts[1].equals(AH_MASTER_SUFFIX)) {
return (X509Certificate) keystore.getCertificate(alias);
}
}
final String errorMsg = "Getting the root cert from keystore failed. " +
"Cannot find CN in the following format: " + AH_MASTER_NAME + "." + AH_MASTER_SUFFIX;
logger.error(errorMsg);
throw new ServiceConfigurationError(errorMsg);
} catch (final KeyStoreException | NoSuchElementException ex) {
logger.error("Getting the root cert from keystore failed...", ex);
throw new ServiceConfigurationError("Getting the root cert from keystore failed...", ex);
}
}
//-------------------------------------------------------------------------------------------------
public static PrivateKey getPrivateKey(final KeyStore keystore, final String keyPass) {
Assert.notNull(keystore, "Key store is not defined.");
Assert.notNull(keyPass, "Password is not defined.");
PrivateKey privateKey = null;
String element;
try {
final Enumeration<String> enumeration = keystore.aliases();
while (enumeration.hasMoreElements()) {
element = enumeration.nextElement();
// the first certificate is not always the end certificate. java does not guarantee the order
final Certificate[] chain = keystore.getCertificateChain(element);
if(Objects.isNull(chain) || chain.length < 3) {
continue;
}
privateKey = (PrivateKey) keystore.getKey(element, keyPass.toCharArray());
if (privateKey != null) {
break;
}
}
} catch (final KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException ex) {
logger.error("Getting the private key from key store failed...", ex);
throw new ServiceConfigurationError("Getting the private key from key store failed...", ex);
}
if (privateKey == null) {
throw new ServiceConfigurationError("Getting the private key failed, key store aliases do not identify a key.");
}
return privateKey;
}
//-------------------------------------------------------------------------------------------------
public static PrivateKey getCloudPrivateKey(final KeyStore keystore, final String keyPass) {
Assert.notNull(keystore, "Key store is not defined.");
Assert.notNull(keyPass, "Password is not defined.");
try {
final Enumeration<String> storedAliases = keystore.aliases();
while (storedAliases.hasMoreElements()) {
final String alias = storedAliases.nextElement();
final X509Certificate certificate = (X509Certificate) keystore.getCertificate(alias);
if (isCloudCertificate(certificate)) {
final PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, keyPass.toCharArray());
if (privateKey != null) {
logger.debug("Found cloud private key with alias: " + alias);
return privateKey;
}
}
}
} catch (final KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException ex) {
logger.error("Getting the private key from key store failed...", ex);
throw new ServiceConfigurationError("Getting the private key from key store failed...", ex);
}
logger.error("Getting the private key failed, key store aliases do not identify a key.");
throw new ServiceConfigurationError("Getting the private key failed, key store aliases do not identify a key.");
}
//-------------------------------------------------------------------------------------------------
public static PrivateKey getCloudPrivateKey(final KeyStore keystore, final String cloudCommonName, final String keyPass) {
Assert.notNull(keystore, "Key store is not defined.");
Assert.notNull(cloudCommonName, "CloudCommonName is not defined.");
Assert.notNull(keyPass, "Password is not defined.");
try {
// Try to find private key with common name as the alias
PrivateKey privateKey = (PrivateKey) keystore.getKey(cloudCommonName, keyPass.toCharArray());
if (privateKey != null) {
return privateKey;
}
// The cloud common name is not the alias in debian installation with own certificates
final String[] cnParts = cloudCommonName.split("\\.");
if (cnParts.length == 4 && cnParts[2].equals(AH_MASTER_NAME) && cnParts[3].equals(AH_MASTER_SUFFIX)) {
final String cloudName = cnParts[0];
privateKey = (PrivateKey) keystore.getKey(cloudName, keyPass.toCharArray());
if (privateKey != null) {
return privateKey;
}
}
// Try to find the private key based on the common name
logger.warn("Cannot find cloud private key based on alias. Trying to find based on common name...");
return getCloudPrivateKey(keystore, keyPass);
} catch (final KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException ex) {
logger.error("Getting the cloud private key from key store failed...", ex);
throw new ServiceConfigurationError("Getting the cloud private key from key store failed...", ex);
}
}
//-------------------------------------------------------------------------------------------------
public static PublicKey getPublicKeyFromBase64EncodedString(final String encodedKey) {
Assert.isTrue(!isEmpty(encodedKey), "Encoded key is null or blank");
final byte[] keyBytes = Base64.getDecoder().decode(encodedKey);
return generatePublicKeyFromByteArray(keyBytes);
}
//-------------------------------------------------------------------------------------------------
public static PublicKey getPublicKeyFromPEMFile(final InputStream is) {
Assert.notNull(is, "Input stream is null");
try {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final byte[] buf = new byte[1024];
for (int read = 0; read != -1; read = is.read(buf)) {
baos.write(buf, 0, read);
}
final String pem = new String(baos.toByteArray(), StandardCharsets.ISO_8859_1);
baos.close();
final String encoded = PEM_PATTERN.matcher(pem).replaceFirst("$1");
final byte[] keyBytes = Base64.getMimeDecoder().decode(encoded);
return generatePublicKeyFromByteArray(keyBytes);
} catch (final IOException ex) {
throw new ArrowheadException("IOException occurred during PEM file loading from input stream.", ex);
}
}
//-------------------------------------------------------------------------------------------------
public static boolean isKeyStoreCNArrowheadValid(final String commonName) {
if (isEmpty(commonName)) {
return false;
}
final String[] cnFields = commonName.split("\\.", 0);
return cnFields.length == SERVICE_CN_NAME_LENGTH && cnFields[cnFields.length - 1].equals(AH_MASTER_SUFFIX) && cnFields[cnFields.length - 2].equals(AH_MASTER_NAME);
}
//-------------------------------------------------------------------------------------------------
public static boolean isKeyStoreCNArrowheadValid(final String clientCN, final String cloudCN) {
if (isEmpty(clientCN) || isEmpty(cloudCN)) {
return false;
}
final String[] clientFields = clientCN.split("\\.", 2); // valid clientFields contains clientServiceName, cloudName.operator.arrowhead.eu
return clientFields.length >= 2 && cloudCN.equalsIgnoreCase(clientFields[1]);
}
//-------------------------------------------------------------------------------------------------
private static boolean isCloudCommonName(final String commonName) {
Assert.notNull(commonName, "Empty commonName is not allowed");
final String[] cnParts = commonName.split("\\.");
return (cnParts.length == 4 && cnParts[2].equals(AH_MASTER_NAME) && cnParts[3].equals(AH_MASTER_SUFFIX));
}
//-------------------------------------------------------------------------------------------------
private static boolean isCloudCertificate(final X509Certificate certificate) {
final String commonName = getCertCNFromSubject(certificate.getSubjectDN().getName());
Assert.notNull(commonName, "Certificate without commonName is not allowed");
return isCloudCommonName(commonName);
}
//-------------------------------------------------------------------------------------------------
public static void createExceptionFromErrorMessageDTO(final ErrorMessageDTO dto) {
Assert.notNull(dto, "Error message object is null.");
Assert.notNull(dto.getExceptionType(), "Exception type is null.");
switch (dto.getExceptionType()) {
case ARROWHEAD:
throw new ArrowheadException(dto.getErrorMessage(), dto.getErrorCode(), dto.getOrigin());
case AUTH:
throw new AuthException(dto.getErrorMessage(), dto.getErrorCode(), dto.getOrigin());
case BAD_PAYLOAD:
throw new BadPayloadException(dto.getErrorMessage(), dto.getErrorCode(), dto.getOrigin());
case INVALID_PARAMETER:
throw new InvalidParameterException(dto.getErrorMessage(), dto.getErrorCode(), dto.getOrigin());
case DATA_NOT_FOUND:
throw new DataNotFoundException(dto.getErrorMessage(), dto.getErrorCode(), dto.getOrigin());
case GENERIC:
throw new ArrowheadException(dto.getErrorMessage(), dto.getErrorCode(), dto.getOrigin());
case TIMEOUT:
throw new TimeoutException(dto.getErrorMessage(), dto.getErrorCode(), dto.getOrigin());
case UNAVAILABLE:
throw new UnavailableServerException(dto.getErrorMessage(), dto.getErrorCode(), dto.getOrigin());
default:
logger.error("Unknown exception type: {}", dto.getExceptionType());
throw new ArrowheadException(dto.getErrorMessage(), dto.getErrorCode(), dto.getOrigin());
}
}
//-------------------------------------------------------------------------------------------------
public static boolean isValidMacAddress(final String macAddress) {
Assert.notNull(macAddress, "MAC address must not be null");
final Matcher matcher = MAC_ADDRESS_PATTERN.matcher(macAddress);
return matcher.matches();
}
//-------------------------------------------------------------------------------------------------
public static String lowerCaseTrim(final String text) {
if (isEmpty(text)) {
return text;
}
return text.toLowerCase().trim();
}
//-------------------------------------------------------------------------------------------------
public static String firstNotNullIfExists(final String first, final String second) {
return Utilities.notEmpty(first) ? first : second;
}
//-------------------------------------------------------------------------------------------------
@SuppressWarnings("unchecked")
public static <T> T firstNotNullIfExists(final T first, final T second) {
if (first instanceof String && second instanceof String) {
return (T) firstNotNullIfExists((String) first, (String) second);
}
return Objects.nonNull(first) ? first : second;
}
//-------------------------------------------------------------------------------------------------
public static String firstNotNullIfExists(final String... args) {
for (final String candidate : args) {
if (Utilities.notEmpty(candidate)) {
return candidate;
}
}
return null;
}
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private Utilities() {
throw new UnsupportedOperationException();
}
//-------------------------------------------------------------------------------------------------
private static PublicKey generatePublicKeyFromByteArray(final byte[] keyBytes) {
try {
return keyFactory.generatePublic(new X509EncodedKeySpec(keyBytes));
} catch (final InvalidKeySpecException ex) {
logger.error("getPublicKey: X509 keyspec could not be created from the decoded bytes.");
throw new AuthException("Public key decoding failed due wrong input key", ex);
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/core/CoreSystem.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.core;
import java.util.Collections;
import java.util.List;
import org.springframework.util.Assert;
import eu.arrowhead.common.CommonConstants;
import eu.arrowhead.common.Defaults;
public enum CoreSystem {
//=================================================================================================
// elements
// Please create enum values here without underscore, because these values has a direct connection with the certificate's CN which does not support underscores!
SERVICEREGISTRY(Defaults.DEFAULT_SERVICEREGISTRY_PORT, List.of(CoreSystemService.SERVICEREGISTRY_REGISTER_SERVICE,
CoreSystemService.SERVICEREGISTRY_UNREGISTER_SERVICE,
CoreSystemService.SERVICEREGISTRY_REGISTER_SYSTEM,
CoreSystemService.SERVICEREGISTRY_UNREGISTER_SYSTEM,
CoreSystemService.SERVICEREGISTRY_PULL_SYSTEMS)),
SYSTEMREGISTRY(Defaults.DEFAULT_SYSTEMREGISTRY_PORT, List.of(CoreSystemService.SYSTEMREGISTRY_REGISTER_SERVICE,
CoreSystemService.SYSTEMREGISTRY_UNREGISTER_SERVICE,
CoreSystemService.SYSTEMREGISTRY_ONBOARDING_WITH_NAME_SERVICE,
CoreSystemService.SYSTEMREGISTRY_ONBOARDING_WITH_CSR_SERVICE)),
DEVICEREGISTRY(Defaults.DEFAULT_DEVICEREGISTRY_PORT, List.of(CoreSystemService.DEVICEREGISTRY_REGISTER_SERVICE,
CoreSystemService.DEVICEREGISTRY_UNREGISTER_SERVICE,
CoreSystemService.DEVICEREGISTRY_ONBOARDING_WITH_NAME_SERVICE,
CoreSystemService.DEVICEREGISTRY_ONBOARDING_WITH_CSR_SERVICE)),
ONBOARDINGCONTROLLER(Defaults.DEFAULT_ONBOARDING_PORT, List.of(CoreSystemService.ONBOARDING_WITH_CERTIFICATE_AND_NAME_SERVICE,
CoreSystemService.ONBOARDING_WITH_SHARED_SECRET_AND_NAME_SERVICE,
CoreSystemService.ONBOARDING_WITH_CERTIFICATE_AND_CSR_SERVICE,
CoreSystemService.ONBOARDING_WITH_SHARED_SECRET_AND_CSR_SERVICE)),
AUTHORIZATION(Defaults.DEFAULT_AUTHORIZATION_PORT, List.of(CoreSystemService.AUTH_CONTROL_INTRA_SERVICE,
CoreSystemService.AUTH_CONTROL_INTER_SERVICE,
CoreSystemService.AUTH_TOKEN_GENERATION_SERVICE,
CoreSystemService.AUTH_PUBLIC_KEY_SERVICE,
CoreSystemService.AUTH_CONTROL_SUBSCRIPTION_SERVICE)),
ORCHESTRATOR(Defaults.DEFAULT_ORCHESTRATOR_PORT, List.of(CoreSystemService.ORCHESTRATION_SERVICE,
CoreSystemService.ORCHESTRATION_BY_PROXY_SERVICE,
CoreSystemService.ORCHESTRATION_CREATE_FLEXIBLE_STORE_RULES_SERVICE,
CoreSystemService.ORCHESTRATION_REMOVE_FLEXIBLE_STORE_RULE_SERVICE,
CoreSystemService.ORCHESTRATION_CLEAN_FLEXIBLE_STORE_SERVICE,
CoreSystemService.ORCHESTRATION_QOS_ENABLED_SERVICE,
CoreSystemService.ORCHESTRATION_QOS_RESERVATIONS_SERVICE,
CoreSystemService.ORCHESTRATION_QOS_TEMPORARY_LOCK_SERVICE,
CoreSystemService.ORCHESTRATION_QOS_CONFIRM_RESERVATION_SERVICE)),
GATEKEEPER(Defaults.DEFAULT_GATEKEEPER_PORT, List.of(CoreSystemService.GATEKEEPER_GLOBAL_SERVICE_DISCOVERY,
CoreSystemService.GATEKEEPER_MULTI_GLOBAL_SERVICE_DISCOVERY,
CoreSystemService.GATEKEEPER_INTER_CLOUD_NEGOTIATION,
CoreSystemService.GATEKEEPER_PULL_CLOUDS,
CoreSystemService.GATEKEEPER_COLLECT_SYSTEM_ADDRESSES,
CoreSystemService.GATEKEEPER_COLLECT_ACCESS_TYPES,
CoreSystemService.GATEKEEPER_RELAY_TEST_SERVICE,
CoreSystemService.GATEKEEPER_GET_CLOUD_SERVICE)),
EVENTHANDLER(Defaults.DEFAULT_EVENTHANDLER_PORT, List.of(CoreSystemService.EVENT_PUBLISH_SERVICE,
CoreSystemService.EVENT_SUBSCRIBE_SERVICE,
CoreSystemService.EVENT_UNSUBSCRIBE_SERVICE,
CoreSystemService.EVENT_PUBLISH_AUTH_UPDATE_SERVICE)),
DATAMANAGER(Defaults.DEFAULT_DATAMANAGER_PORT, List.of(CoreSystemService.PROXY_SERVICE, CoreSystemService.HISTORIAN_SERVICE)),
TIMEMANAGER(Defaults.DEFAULT_TIMEMANAGER_PORT, List.of(CoreSystemService.TIME_SERVICE)),
GATEWAY(Defaults.DEFAULT_GATEWAY_PORT, List.of(CoreSystemService.GATEWAY_PUBLIC_KEY_SERVICE,
CoreSystemService.GATEWAY_PROVIDER_SERVICE,
CoreSystemService.GATEWAY_CONSUMER_SERVICE,
CoreSystemService.GATEWAY_CLOSE_SESSIONS_SERVICE)),
CHOREOGRAPHER(Defaults.DEFAULT_CHOREOGRAPHER_PORT, List.of(CoreSystemService.CHOREOGRAPHER_SERVICE,
CoreSystemService.CHOREOGRAPHER_REGISTER_EXECUTOR_SERVICE,
CoreSystemService.CHOREOGRAPHER_UNREGISTER_EXECUTOR_SERVICE)),
CONFIGURATION(Defaults.DEFAULT_CONFIGURATION_PORT, List.of(CoreSystemService.CONFIGURATION_SERVICE,
CoreSystemService.CONFIGURATION_RAW_SERVICE)),
QOSMONITOR(Defaults.DEFAULT_QOSMONITOR_PORT, List.of(CoreSystemService.QOSMONITOR_INTRA_PING_MEASUREMENT_SERVICE,
CoreSystemService.QOSMONITOR_INTRA_PING_MEDIAN_MEASUREMENT_SERVICE,
CoreSystemService.QOSMONITOR_INTER_DIRECT_PING_MEASUREMENT_SERVICE,
CoreSystemService.QOSMONITOR_INTER_RELAY_ECHO_MEASUREMENT_SERVICE,
CoreSystemService.QOSMONITOR_PUBLIC_KEY_SERVICE,
CoreSystemService.QOSMONITOR_JOIN_RELAY_TEST_SERVICE,
CoreSystemService.QOSMONITOR_INIT_RELAY_TEST_SERVICE)),
CERTIFICATEAUTHORITY(Defaults.DEFAULT_CERTIFICATEAUTHORITY_PORT, List.of(CoreSystemService.CERTIFICATEAUTHORITY_SIGN_SERVICE,
CoreSystemService.CERTIFICATEAUTHORITY_LIST_CERTIFICATES_SERVICE,
CoreSystemService.CERTIFICATEAUTHORITY_CHECK_CERTIFICATE_SERVICE,
CoreSystemService.CERTIFICATEAUTHORITY_REVOKE_CERTIFICATE_SERVICE,
CoreSystemService.CERTIFICATEAUTHORITY_LIST_TRUSTED_KEYS_SERVICE,
CoreSystemService.CERTIFICATEAUTHORITY_CHECK_TRUSTED_KEY_SERVICE,
CoreSystemService.CERTIFICATEAUTHORITY_ADD_TRUSTED_KEY_SERVICE,
CoreSystemService.CERTIFICATEAUTHORITY_DELETE_TRUSTED_KEY_SERVICE)),
TRANSLATOR(Defaults.DEFAULT_TRANSLATOR_PORT, List.of(CoreSystemService.TRANSLATOR_SERVICE,
CoreSystemService.TRANSLATOR_FIWARE_SERVICE,
CoreSystemService.TRANSLATOR_PLUGIN_SERVICE)),
MSCV(Defaults.DEFAULT_MSCV_PORT, List.of(CoreSystemService.MSCV_VERIFICATION_SERVICE,
CoreSystemService.MSCV_PUBLIC_KEY_SERVICE,
CoreSystemService.MSCV_LOGIN_SERVICE)),
PLANTDESCRIPTIONENGINE(Defaults.DEFAULT_PLANT_DESCRIPTION_ENGINE_PORT, List.of()), //TODO add PDE services
GAMS(Defaults.DEFAULT_GENERIC_AUTONOMIC_MANAGEMENT_PORT, List.of(CoreSystemService.GAMS_SERVICE,
CoreSystemService.GAMS_SENSOR_SERVICE)),
HAWKBITCONFIGURATIONMANAGER(Defaults.DEFAULT_HAWKBIT_CONFIGURATION_MANAGER_PORT, List.of());
//=================================================================================================
// members
private final int defaultPort;
private final List<CoreSystemService> services;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public int getDefaultPort() { return defaultPort; }
public List<CoreSystemService> getServices() { return services; }
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private CoreSystem(final int defaultPort, final List<CoreSystemService> services) {
Assert.isTrue(defaultPort > CommonConstants.SYSTEM_PORT_RANGE_MIN && defaultPort < CommonConstants.SYSTEM_PORT_RANGE_MAX, "Default port is invalid.");
this.services = services != null ? Collections.unmodifiableList(services) : List.of();
this.defaultPort = defaultPort;
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/core/CoreSystemService.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.core;
import java.util.List;
import org.springframework.util.Assert;
import eu.arrowhead.common.CommonConstants;
import eu.arrowhead.common.Utilities;
public enum CoreSystemService {
//=================================================================================================
// elements
// Authorization services
AUTH_CONTROL_INTRA_SERVICE(CommonConstants.CORE_SERVICE_AUTH_CONTROL_INTRA, CommonConstants.AUTHORIZATION_URI + CommonConstants.OP_AUTH_INTRA_CHECK_URI),
AUTH_CONTROL_INTER_SERVICE(CommonConstants.CORE_SERVICE_AUTH_CONTROL_INTER, CommonConstants.AUTHORIZATION_URI + CommonConstants.OP_AUTH_INTER_CHECK_URI),
AUTH_TOKEN_GENERATION_SERVICE(CommonConstants.CORE_SERVICE_AUTH_TOKEN_GENERATION, CommonConstants.AUTHORIZATION_URI + CommonConstants.OP_AUTH_TOKEN_URI),
AUTH_TOKEN_GENERATION_MULTI_SERVICE(CommonConstants.CORE_SERVICE_AUTH_TOKEN_GENERATION_MULTI_SERVICE, CommonConstants.AUTHORIZATION_URI + CommonConstants.OP_AUTH_TOKEN_MULTI_SERVICE_URI),
AUTH_PUBLIC_KEY_SERVICE(CommonConstants.CORE_SERVICE_AUTH_PUBLIC_KEY, CommonConstants.AUTHORIZATION_URI + CommonConstants.OP_AUTH_KEY_URI),
AUTH_CONTROL_SUBSCRIPTION_SERVICE(CommonConstants.CORE_SERVICE_AUTH_CONTROL_SUBSCRIPTION, CommonConstants.AUTHORIZATION_URI + CommonConstants.OP_AUTH_SUBSCRIPTION_CHECK_URI),
// Orchestrator services
ORCHESTRATION_SERVICE(CommonConstants.CORE_SERVICE_ORCH_PROCESS, CommonConstants.ORCHESTRATOR_URI + CommonConstants.OP_ORCH_PROCESS_URI),
ORCHESTRATION_BY_PROXY_SERVICE(CommonConstants.CORE_SERVICE_ORCH_PROCESS_BY_PROXY, CommonConstants.ORCHESTRATOR_URI + CommonConstants.OP_ORCH_PROCESS_BY_PROXY_URI),
ORCHESTRATION_CREATE_FLEXIBLE_STORE_RULES_SERVICE(CommonConstants.CORE_SERVICE_ORCH_CREATE_FLEXIBLE_STORE_RULES, CommonConstants.ORCHESTRATOR_URI + CommonConstants.OP_ORCH_CREATE_FLEXIBLE_STORE_RULES_URI),
ORCHESTRATION_REMOVE_FLEXIBLE_STORE_RULE_SERVICE(CommonConstants.CORE_SERVICE_ORCH_REMOVE_FLEXIBLE_STORE_RULE, CommonConstants.ORCHESTRATOR_URI + CommonConstants.OP_ORCH_REMOVE_FLEXIBLE_STORE_RULE_URI),
ORCHESTRATION_CLEAN_FLEXIBLE_STORE_SERVICE(CommonConstants.CORE_SERVICE_ORCH_CLEAN_FLEXIBLE_STORE, CommonConstants.ORCHESTRATOR_URI + CommonConstants.OP_ORCH_CLEAN_FLEXIBLE_STORE_URI),
ORCHESTRATION_QOS_ENABLED_SERVICE(CommonConstants.CORE_SERVICE_ORCH_QOS_ENABLED, CommonConstants.ORCHESTRATOR_URI + CommonConstants.OP_ORCH_QOS_ENABLED_URI),
ORCHESTRATION_QOS_RESERVATIONS_SERVICE(CommonConstants.CORE_SERVICE_ORCH_QOS_RESERVATIONS, CommonConstants.ORCHESTRATOR_URI + CommonConstants.OP_ORCH_QOS_RESERVATIONS_URI),
ORCHESTRATION_QOS_TEMPORARY_LOCK_SERVICE(CommonConstants.CORE_SERVICE_ORCH_QOS_TEMPORARY_LOCK, CommonConstants.ORCHESTRATOR_URI + CommonConstants.OP_ORCH_QOS_TEMPORARY_LOCK_URI),
ORCHESTRATION_QOS_CONFIRM_RESERVATION_SERVICE(CommonConstants.CORE_SERVICE_ORCH_QOS_CONFIRM_RESERVATION, CommonConstants.ORCHESTRATOR_URI + CommonConstants.OP_ORCH_QOS_RESERVATIONS_URI),
// Gatekeeper services
GATEKEEPER_GLOBAL_SERVICE_DISCOVERY(CommonConstants.CORE_SERVICE_GATEKEEPER_GSD, CommonConstants.GATEKEEPER_URI + CommonConstants.OP_GATEKEEPER_GSD_SERVICE),
GATEKEEPER_MULTI_GLOBAL_SERVICE_DISCOVERY(CommonConstants.CORE_SERVICE_GATEKEEPER_MULTI_GSD, CommonConstants.GATEKEEPER_URI + CommonConstants.OP_GATEKEEPER_MULTI_GSD_SERVICE),
GATEKEEPER_INTER_CLOUD_NEGOTIATION(CommonConstants.CORE_SERVICE_GATEKEEPER_ICN, CommonConstants.GATEKEEPER_URI + CommonConstants.OP_GATEKEEPER_ICN_SERVICE),
GATEKEEPER_PULL_CLOUDS(CommonConstants.CORE_SERVICE_GATEKEEPER_PULL_CLOUDS, CommonConstants.GATEKEEPER_URI + CommonConstants.OP_GATEKEEPER_PULL_CLOUDS_SERVICE),
GATEKEEPER_COLLECT_SYSTEM_ADDRESSES(CommonConstants.CORE_SERVICE_GATEKEEPER_COLLECT_SYSTEM_ADDRESSES, CommonConstants.GATEKEEPER_URI + CommonConstants.OP_GATEKEEPER_COLLECT_SYSTEM_ADDRESSES_SERVICE),
GATEKEEPER_COLLECT_ACCESS_TYPES(CommonConstants.CORE_SERVICE_GATEKEEPER_COLLECT_ACCESS_TYPES, CommonConstants.GATEKEEPER_URI + CommonConstants.OP_GATEKEEPER_COLLECT_ACCESS_TYPES_SERVICE),
GATEKEEPER_RELAY_TEST_SERVICE(CommonConstants.CORE_SERVICE_GATEKEEPER_RELAY_TEST, CommonConstants.GATEKEEPER_URI + CommonConstants.OP_GATEKEEPER_RELAY_TEST_SERVICE),
GATEKEEPER_GET_CLOUD_SERVICE(CommonConstants.CORE_SERVICE_GATEKEEPER_GET_CLOUD, CommonConstants.GATEKEEPER_URI + CommonConstants.OP_GATEKEEPER_GET_CLOUD_SERVICE +
CommonConstants.OP_GATEKEEPER_GET_CLOUD_SERVICE_SUFFIX),
// Gateway services
GATEWAY_PUBLIC_KEY_SERVICE(CommonConstants.CORE_SERVICE_GATEWAY_PUBLIC_KEY, CommonConstants.GATEWAY_URI + CommonConstants.OP_GATEWAY_KEY_URI),
GATEWAY_PROVIDER_SERVICE(CommonConstants.CORE_SERVICE_GATEWAY_CONNECT_PROVIDER, CommonConstants.GATEWAY_URI + CommonConstants.OP_GATEWAY_CONNECT_PROVIDER_URI),
GATEWAY_CONSUMER_SERVICE(CommonConstants.CORE_SERVICE_GATEWAY_CONNECT_CONSUMER, CommonConstants.GATEWAY_URI + CommonConstants.OP_GATEWAY_CONNECT_CONSUMER_URI),
GATEWAY_CLOSE_SESSIONS_SERVICE(CommonConstants.CORE_SERVICE_GATEWAY_CLOSE_SESSIONS, CommonConstants.GATEWAY_URI + CommonConstants.OP_GATEWAY_CLOSE_SESSIONS),
// Eventhandler services
EVENT_PUBLISH_SERVICE(CommonConstants.CORE_SERVICE_EVENTHANDLER_PUBLISH, CommonConstants.EVENTHANDLER_URI + CommonConstants.OP_EVENTHANDLER_PUBLISH),
EVENT_SUBSCRIBE_SERVICE(CommonConstants.CORE_SERVICE_EVENTHANDLER_SUBSCRIBE, CommonConstants.EVENTHANDLER_URI + CommonConstants.OP_EVENTHANDLER_SUBSCRIBE),
EVENT_UNSUBSCRIBE_SERVICE(CommonConstants.CORE_SERVICE_EVENTHANDLER_UNSUBSCRIBE, CommonConstants.EVENTHANDLER_URI + CommonConstants.OP_EVENTHANDLER_UNSUBSCRIBE),
EVENT_PUBLISH_AUTH_UPDATE_SERVICE(CommonConstants.CORE_SERVICE_EVENTHANDLER_PUBLISH_AUTH_UPDATE, CommonConstants.EVENTHANDLER_URI + CommonConstants.OP_EVENTHANDLER_PUBLISH_AUTH_UPDATE),
// DataManager services
PROXY_SERVICE(CommonConstants.CORE_SERVICE_DATAMANAGER_PROXY, CommonConstants.DATAMANAGER_URI + CommonConstants.OP_DATAMANAGER_PROXY),
HISTORIAN_SERVICE(CommonConstants.CORE_SERVICE_DATAMANAGER_HISTORIAN, CommonConstants.DATAMANAGER_URI + CommonConstants.OP_DATAMANAGER_HISTORIAN),
// TimeManager services
TIME_SERVICE(CommonConstants.CORE_SERVICE_TIMEMANAGER_TIME, CommonConstants.TIMEMANAGER_URI + CommonConstants.OP_TIMEMANAGER_TIME),
// Translator services
TRANSLATOR_SERVICE(CommonConstants.CORE_SERVICE_TRANSLATOR, CommonConstants.TRANSLATOR_URI),
TRANSLATOR_FIWARE_SERVICE(CommonConstants.CORE_SERVICE_TRANSLATOR_FIWARE, CommonConstants.TRANSLATOR_URI + CommonConstants.OP_TRANSLATOR_FIWARE_URI),
TRANSLATOR_PLUGIN_SERVICE(CommonConstants.CORE_SERVICE_TRANSLATOR_PLUGIN, CommonConstants.TRANSLATOR_URI + CommonConstants.OP_TRANSLATOR_PLUGIN_URI),
// CA services
CERTIFICATEAUTHORITY_SIGN_SERVICE(CommonConstants.CORE_SERVICE_CERTIFICATEAUTHORITY_SIGN, CommonConstants.CERTIFICATEAUTHRORITY_URI + CommonConstants.OP_CA_SIGN_CERTIFICATE_URI),
CERTIFICATEAUTHORITY_LIST_CERTIFICATES_SERVICE(CommonConstants.CORE_SERVICE_CERTIFICATEAUTHORITY_LIST_CERTIFICATES, CommonConstants.CERTIFICATEAUTHRORITY_URI + CommonConstants.OP_CA_MGMT_CERTIFICATES_URI),
CERTIFICATEAUTHORITY_CHECK_CERTIFICATE_SERVICE(CommonConstants.CORE_SERVICE_CERTIFICATEAUTHORITY_CHECK_CERTIFICATE, CommonConstants.CERTIFICATEAUTHRORITY_URI + CommonConstants.OP_CA_CHECK_CERTIFICATE_URI),
CERTIFICATEAUTHORITY_REVOKE_CERTIFICATE_SERVICE(CommonConstants.CORE_SERVICE_CERTIFICATEAUTHORITY_REVOKE_CERTIFICATE, CommonConstants.CERTIFICATEAUTHRORITY_URI + CommonConstants.OP_CA_MGMT_CERTIFICATES_URI +
CommonConstants.OP_CA_MGMT_CERTIFICATES_URI_SUFFIX),
CERTIFICATEAUTHORITY_LIST_TRUSTED_KEYS_SERVICE(CommonConstants.CORE_SERVICE_CERTIFICATEAUTHORITY_LIST_TRUSTED_KEYS, CommonConstants.CERTIFICATEAUTHRORITY_URI + CommonConstants.OP_CA_MGMT_TRUSTED_KEYS_URI),
CERTIFICATEAUTHORITY_CHECK_TRUSTED_KEY_SERVICE(CommonConstants.CORE_SERVICE_CERTIFICATEAUTHORITY_CHECK_TRUSTED_KEY, CommonConstants.CERTIFICATEAUTHRORITY_URI + CommonConstants.OP_CA_CHECK_TRUSTED_KEY_URI),
CERTIFICATEAUTHORITY_ADD_TRUSTED_KEY_SERVICE(CommonConstants.CORE_SERVICE_CERTIFICATEAUTHORITY_ADD_TRUSTED_KEY, CommonConstants.CERTIFICATEAUTHRORITY_URI + CommonConstants.OP_CA_MGMT_TRUSTED_KEYS_URI),
CERTIFICATEAUTHORITY_DELETE_TRUSTED_KEY_SERVICE(CommonConstants.CORE_SERVICE_CERTIFICATEAUTHORITY_DELETE_TRUSTED_KEY, CommonConstants.CERTIFICATEAUTHRORITY_URI + CommonConstants.OP_CA_MGMT_TRUSTED_KEYS_URI +
CommonConstants.OP_CA_MGMT_TRUSTED_KEYS_URI_SUFFIX),
// Configuration services
CONFIGURATION_SERVICE(CommonConstants.CORE_SERVICE_CONFIGURATION_CONF, CommonConstants.CONFIGURATION_URI + CommonConstants.OP_CONFIGURATION_CONF),
CONFIGURATION_RAW_SERVICE(CommonConstants.CORE_SERVICE_CONFIGURATION_RAWCONF, CommonConstants.CONFIGURATION_URI + CommonConstants.OP_CONFIGURATION_RAWCONF, List.of(new InterfaceData(CommonConstants.HTTP, CommonConstants.BINARY))),
CONFIGURATION_MANAGE_SERVICE(CommonConstants.CORE_SERVICE_CONFIGURATION_CONF, CommonConstants.CONFIGURATION_URI + CommonConstants.OP_CONFIGURATION_MGMT_MANAGE),
// Choreographer services
CHOREOGRAPHER_SERVICE(CommonConstants.CORE_SERVICE_CHOREOGRAPHER_PROCESS, CommonConstants.CHOREOGRAPHER_URI + CommonConstants.OP_CHOREOGRAPHER_NOTIFY_STEP_DONE),
CHOREOGRAPHER_REGISTER_EXECUTOR_SERVICE(CommonConstants.CORE_SERVICE_CHOREOGRAPHER_REGISTER_EXECUTOR, CommonConstants.CHOREOGRAPHER_URI + CommonConstants.OP_CHOREOGRAPHER_EXECUTOR_REGISTER),
CHOREOGRAPHER_UNREGISTER_EXECUTOR_SERVICE(CommonConstants.CORE_SERVICE_CHOREOGRAPHER_UNREGISTER_EXECUTOR, CommonConstants.CHOREOGRAPHER_URI + CommonConstants.OP_CHOREOGRAPHER_EXECUTOR_UNREGISTER),
// QoS Monitor services
QOSMONITOR_INTRA_PING_MEASUREMENT_SERVICE(CommonConstants.CORE_SERVICE_QOSMONITOR_INTRA_PING_MEASUREMENT, CommonConstants.QOSMONITOR_URI + CommonConstants.OP_QOSMONITOR_INTRA_PING_MEASUREMENT +
CommonConstants.OP_QOSMONITOR_INTRA_PING_MEASUREMENT_SUFFIX),
QOSMONITOR_INTRA_PING_MEDIAN_MEASUREMENT_SERVICE(CommonConstants.CORE_SERVICE_QOSMONITOR_INTRA_PING_MEDIAN_MEASUREMENT, CommonConstants.QOSMONITOR_URI + CommonConstants.OP_QOSMONITOR_INTRA_PING_MEDIAN_MEASUREMENT),
QOSMONITOR_INTER_DIRECT_PING_MEASUREMENT_SERVICE(CommonConstants.CORE_SERVICE_QOSMONITOR_INTER_DIRECT_PING_MEASUREMENT, CommonConstants.QOSMONITOR_URI + CommonConstants.OP_QOSMONITOR_INTER_DIRECT_PING_MEASUREMENT),
QOSMONITOR_INTER_RELAY_ECHO_MEASUREMENT_SERVICE(CommonConstants.CORE_SERVICE_QOSMONITOR_INTER_RELAY_ECHO_MEASUREMENT, CommonConstants.QOSMONITOR_URI + CommonConstants.OP_QOSMONITOR_INTER_RELAY_ECHO_MEASUREMENT),
QOSMONITOR_PUBLIC_KEY_SERVICE(CommonConstants.CORE_SERVICE_QOSMONITOR_PUBLIC_KEY, CommonConstants.QOSMONITOR_URI + CommonConstants.OP_QOSMONITOR_KEY_URI),
QOSMONITOR_JOIN_RELAY_TEST_SERVICE(CommonConstants.CORE_SERVICE_QOSMONITOR_JOIN_RELAY_TEST, CommonConstants.QOSMONITOR_URI + CommonConstants.OP_QOSMONITOR_JOIN_RELAY_TEST_URI),
QOSMONITOR_INIT_RELAY_TEST_SERVICE(CommonConstants.CORE_SERVICE_QOSMONITOR_INIT_RELAY_TEST, CommonConstants.QOSMONITOR_URI + CommonConstants.OP_QOSMONITOR_INIT_RELAY_TEST_URI),
// Onboarding services
ONBOARDING_WITH_CERTIFICATE_AND_NAME_SERVICE(CommonConstants.CORE_SERVICE_ONBOARDING_WITH_CERTIFICATE_AND_NAME, CommonConstants.ONBOARDING_URI + CommonConstants.OP_ONBOARDING_WITH_CERTIFICATE_AND_NAME),
ONBOARDING_WITH_CERTIFICATE_AND_CSR_SERVICE(CommonConstants.CORE_SERVICE_ONBOARDING_WITH_CERTIFICATE_AND_CSR, CommonConstants.ONBOARDING_URI + CommonConstants.OP_ONBOARDING_WITH_CERTIFICATE_AND_CSR),
ONBOARDING_WITH_SHARED_SECRET_AND_NAME_SERVICE(CommonConstants.CORE_SERVICE_ONBOARDING_WITH_SHARED_SECRET_AND_NAME, CommonConstants.ONBOARDING_URI + CommonConstants.OP_ONBOARDING_WITH_SHARED_SECRET_AND_NAME),
ONBOARDING_WITH_SHARED_SECRET_AND_CSR_SERVICE(CommonConstants.CORE_SERVICE_ONBOARDING_WITH_SHARED_SECRET_AND_CSR, CommonConstants.ONBOARDING_URI + CommonConstants.OP_ONBOARDING_WITH_SHARED_SECRET_AND_CSR),
// Device Registry services
DEVICEREGISTRY_REGISTER_SERVICE(CommonConstants.CORE_SERVICE_DEVICEREGISTRY_REGISTER, CommonConstants.DEVICEREGISTRY_URI + CommonConstants.OP_DEVICEREGISTRY_REGISTER_URI),
DEVICEREGISTRY_UNREGISTER_SERVICE(CommonConstants.CORE_SERVICE_DEVICEREGISTRY_UNREGISTER, CommonConstants.DEVICEREGISTRY_URI + CommonConstants.OP_DEVICEREGISTRY_UNREGISTER_URI),
DEVICEREGISTRY_ONBOARDING_WITH_NAME_SERVICE(CommonConstants.CORE_SERVICE_DEVICEREGISTRY_ONBOARDING_WITH_NAME,
CommonConstants.DEVICEREGISTRY_URI + CommonConstants.ONBOARDING_URI + CommonConstants.OP_DEVICEREGISTRY_ONBOARDING_WITH_NAME_URI),
DEVICEREGISTRY_ONBOARDING_WITH_CSR_SERVICE(CommonConstants.CORE_SERVICE_DEVICEREGISTRY_ONBOARDING_WITH_CSR,
CommonConstants.DEVICEREGISTRY_URI + CommonConstants.ONBOARDING_URI + CommonConstants.OP_DEVICEREGISTRY_ONBOARDING_WITH_CSR_URI),
// System Registry services
SYSTEMREGISTRY_REGISTER_SERVICE(CommonConstants.CORE_SERVICE_SYSTEMREGISTRY_REGISTER, CommonConstants.SYSTEMREGISTRY_URI + CommonConstants.OP_SYSTEMREGISTRY_REGISTER_URI),
SYSTEMREGISTRY_UNREGISTER_SERVICE(CommonConstants.CORE_SERVICE_SYSTEMREGISTRY_UNREGISTER, CommonConstants.SYSTEMREGISTRY_URI + CommonConstants.OP_SYSTEMREGISTRY_UNREGISTER_URI),
SYSTEMREGISTRY_ONBOARDING_WITH_NAME_SERVICE(CommonConstants.CORE_SERVICE_SYSTEMREGISTRY_ONBOARDING_WITH_NAME,
CommonConstants.SYSTEMREGISTRY_URI + CommonConstants.ONBOARDING_URI + CommonConstants.OP_SYSTEMREGISTRY_ONBOARDING_WITH_NAME_URI),
SYSTEMREGISTRY_ONBOARDING_WITH_CSR_SERVICE(CommonConstants.CORE_SERVICE_SYSTEMREGISTRY_ONBOARDING_WITH_CSR,
CommonConstants.SYSTEMREGISTRY_URI + CommonConstants.ONBOARDING_URI + CommonConstants.OP_SYSTEMREGISTRY_ONBOARDING_WITH_CSR_URI),
// Service Registry services
SERVICEREGISTRY_REGISTER_SERVICE(CommonConstants.CORE_SERVICE_SERVICEREGISTRY_REGISTER, CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_REGISTER_URI),
SERVICEREGISTRY_UNREGISTER_SERVICE(CommonConstants.CORE_SERVICE_SERVICEREGISTRY_UNREGISTER, CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_URI),
SERVICEREGISTRY_REGISTER_SYSTEM(CommonConstants.CORE_SERVICE_SERVICEREGISTRY_REGISTER_SYSTEM, CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_REGISTER_SYSTEM_URI),
SERVICEREGISTRY_UNREGISTER_SYSTEM(CommonConstants.CORE_SERVICE_SERVICEREGISTRY_UNREGISTER_SYSTEM, CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_UNREGISTER_SYSTEM_URI),
SERVICEREGISTRY_PULL_SYSTEMS(CommonConstants.CORE_SERVICE_SERVICEREGISTRY_PULL_SYSTEMS,
CommonConstants.SERVICEREGISTRY_URI + CommonConstants.OP_SERVICEREGISTRY_PULL_SYSTEMS_URI),
// Monitoring and Standard Verification Services
MSCV_VERIFICATION_SERVICE(CommonConstants.CORE_SERVICE_MSCV_VERIFICATION, CommonConstants.MSCV_URI + CommonConstants.OP_MSCV_EXECUTE_URI),
MSCV_PUBLIC_KEY_SERVICE(CommonConstants.CORE_SERVICE_MSCV_PUBLIC_KEY, CommonConstants.MSCV_URI + CommonConstants.OP_MSCV_PUBLIC_KEY_URI),
MSCV_LOGIN_SERVICE(CommonConstants.CORE_SERVICE_MSCV_LOGIN, CommonConstants.MSCV_URI + CommonConstants.OP_MSCV_LOGIN_URI),
GAMS_SERVICE(CommonConstants.CORE_SERVICE_GAMS_SERVICE, CommonConstants.GAMS_URI + CommonConstants.OP_GAMS_SERVICE_URI),
GAMS_SENSOR_SERVICE(CommonConstants.CORE_SERVICE_GAMS_SENSOR_SERVICE, CommonConstants.GAMS_URI + CommonConstants.OP_GAMS_SENSOR_SERVICE_URI);
//TODO: additional services
//=================================================================================================
// members
private final String serviceDefinition;
private final String serviceUri;
private final List<InterfaceData> interfaces;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public String getServiceDefinition() { return serviceDefinition; }
public String getServiceUri() { return serviceUri; }
public List<InterfaceData> getInterfaces() { return interfaces; }
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private CoreSystemService(final String serviceDefinition, final String serviceUri) {
this(serviceDefinition, serviceUri, null);
}
//-------------------------------------------------------------------------------------------------
private CoreSystemService(final String serviceDefinition, final String serviceUri, final List<InterfaceData> interfaces) {
Assert.isTrue(!Utilities.isEmpty(serviceDefinition), "Service definition is null or blank");
Assert.isTrue(!Utilities.isEmpty(serviceUri), "Service URI is null or blank");
this.serviceDefinition = serviceDefinition;
this.serviceUri = serviceUri;
this.interfaces = interfaces == null || interfaces.isEmpty() ? null : interfaces;
}
//=================================================================================================
// nested classes
//-------------------------------------------------------------------------------------------------
public static class InterfaceData {
//=================================================================================================
// members
private final String protocol;
private final String format;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public InterfaceData(final String protocol, final String format) {
Assert.isTrue(!Utilities.isEmpty(protocol), "protocol is invalid");
Assert.isTrue(!Utilities.isEmpty(format), "format is invalid");
this.protocol = protocol.toUpperCase().trim();
this.format = format.toUpperCase().trim();
}
//-------------------------------------------------------------------------------------------------
public String getProtocol() { return protocol; }
public String getFormat() { return format; }
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ActiveSessionCloseErrorDTO.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ActiveSessionCloseErrorDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 1369339628228024167L;
private int port;
private String error;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ActiveSessionCloseErrorDTO() {}
//-------------------------------------------------------------------------------------------------
public ActiveSessionCloseErrorDTO(final int port, final String error) {
this.port = port;
this.error = error;
}
//-------------------------------------------------------------------------------------------------
public int getPort() { return port; }
public String getError() { return error; }
//-------------------------------------------------------------------------------------------------
public void setPort(final int port) { this.port = port; }
public void setError(final String error) { this.error = error; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/AddressType.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
public enum AddressType {
HOSTNAME, IPV4, IPV6;
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/CertificateCreationRequestDTO.java
|
/********************************************************************************
* Copyright (c) 2020 FHB
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* FHB - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CertificateCreationRequestDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 4798265080935778603L;
private String commonName;
private KeyPairDTO keyPairDTO;
//=================================================================================================
// constructors
//-------------------------------------------------------------------------------------------------
public CertificateCreationRequestDTO() {}
//-------------------------------------------------------------------------------------------------
public CertificateCreationRequestDTO(final String commonName) {
this.commonName = commonName;
}
//-------------------------------------------------------------------------------------------------
public CertificateCreationRequestDTO(final String commonName, final KeyPairDTO keyPairDTO) {
this.commonName = commonName;
this.keyPairDTO = keyPairDTO;
}
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public String getCommonName() { return commonName; }
public KeyPairDTO getKeyPairDTO() { return keyPairDTO; }
//-------------------------------------------------------------------------------------------------
public void setCommonName(final String commonName) { this.commonName = commonName; }
public void setKeyPairDTO(final KeyPairDTO keyPairDTO) { this.keyPairDTO = keyPairDTO; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/CertificateCreationResponseDTO.java
|
/********************************************************************************
* Copyright (c) 2020 FHB
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* FHB - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CertificateCreationResponseDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 6712338957176937559L;
private String certificate;
private CertificateType certificateType;
private KeyPairDTO keyPairDTO;
private String certificateFormat;
//=================================================================================================
// constructors
//-------------------------------------------------------------------------------------------------
public CertificateCreationResponseDTO() {}
//-------------------------------------------------------------------------------------------------
public CertificateCreationResponseDTO(final String certificate, final CertificateType certificateType, final String certificateFormat) {
this.certificate = certificate;
this.certificateType = certificateType;
this.certificateFormat = certificateFormat;
}
//-------------------------------------------------------------------------------------------------
public CertificateCreationResponseDTO(final String certificate,
final CertificateType certificateType,
final KeyPairDTO keyPairDTO,
final String certificateFormat) {
this.certificate = certificate;
this.certificateType = certificateType;
this.keyPairDTO = keyPairDTO;
this.certificateFormat = certificateFormat;
}
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public String getCertificate() { return certificate; }
public String getCertificateFormat() { return certificateFormat; }
public CertificateType getCertificateType() { return certificateType; }
public KeyPairDTO getKeyPairDTO() { return keyPairDTO; }
//-------------------------------------------------------------------------------------------------
public void setCertificate(final String certificate) { this.certificate = certificate; }
public void setCertificateFormat(final String certificateFormat) { this.certificateFormat = certificateFormat; }
public void setCertificateType(final CertificateType certificateType) { this.certificateType = certificateType; }
public void setKeyPairDTO(final KeyPairDTO keyPairDTO) { this.keyPairDTO = keyPairDTO; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/CertificateType.java
|
/********************************************************************************
* Copyright (c) 2020 FHB
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* FHB - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.util.Objects;
import eu.arrowhead.common.Utilities;
import org.springframework.util.Assert;
public enum CertificateType {
AH_ONBOARDING("onboarding", 0),
AH_DEVICE("device", 1),
AH_SYSTEM("", 2),
UNKNOWN("", 0);
//=================================================================================================
// members
private final String commonNamePart;
private final int strength;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
CertificateType(final String commonNamePart, final int strength) {
this.commonNamePart = commonNamePart;
this.strength = strength;
}
//-------------------------------------------------------------------------------------------------
public static CertificateType getTypeFromCN(final String commonName) {
if (Objects.isNull(commonName)) { return CertificateType.UNKNOWN; }
final String[] split = commonName.split("\\.");
if (Utilities.isKeyStoreCNArrowheadValid(commonName)) {
return AH_SYSTEM;
} else if (split.length >= 2) {
return CertificateType.getTypeFromCNPart(split[1]);
} else {
return CertificateType.getTypeFromCNPart(split[0]);
}
}
//-------------------------------------------------------------------------------------------------
public boolean hasMinimumStrength(final CertificateType minimumStrengthType) {
Assert.notNull(minimumStrengthType, "CertificateType must not be null");
return this.strength >= minimumStrengthType.strength;
}
//-------------------------------------------------------------------------------------------------
public String appendTypeToCN(final String commonName) {
/* if (Utilities.notEmpty(commonNamePart)) {
return commonName + '.' + commonNamePart;
} else { return commonName; } */
return commonName;
}
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private static CertificateType getTypeFromCNPart(final String commonNamePart) {
for (final CertificateType type : values()) {
if (type.commonNamePart.equalsIgnoreCase(commonNamePart)) {
return type;
}
}
return UNKNOWN;
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerAbortStepRequestDTO.java
|
/********************************************************************************
* Copyright (c) 2020 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerAbortStepRequestDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = -4367804324253105575L;
private long sessionId;
private long sessionStepId;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerAbortStepRequestDTO() {}
//-------------------------------------------------------------------------------------------------
public ChoreographerAbortStepRequestDTO(final long sessionId, final long sessionStepId) {
this.sessionId = sessionId;
this.sessionStepId = sessionStepId;
}
//-------------------------------------------------------------------------------------------------
public long getSessionId() { return sessionId; }
public long getSessionStepId() { return sessionStepId; }
//-------------------------------------------------------------------------------------------------
public void setSessionId(final long sessionId) { this.sessionId = sessionId; }
public void setSessionStepId(final long sessionStepId) { this.sessionStepId = sessionStepId; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerActionRequestDTO.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerActionRequestDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 305775285238451287L;
private String name;
private String nextActionName;
private List<String> firstStepNames;
private List<ChoreographerStepRequestDTO> steps;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerActionRequestDTO() {}
//-------------------------------------------------------------------------------------------------
public ChoreographerActionRequestDTO(final String name, final String nextActionName, final List<String> firstStepNames, final List<ChoreographerStepRequestDTO> steps) {
this.name = name;
this.nextActionName = nextActionName;
this.firstStepNames = firstStepNames;
this.steps = steps;
}
//-------------------------------------------------------------------------------------------------
public String getName() { return name; }
public String getNextActionName() { return nextActionName; }
public List<ChoreographerStepRequestDTO> getSteps() { return steps; }
public List<String> getFirstStepNames() { return firstStepNames; }
//-------------------------------------------------------------------------------------------------
public void setName(final String name) { this.name = name; }
public void setNextActionName(final String nextActionName) { this.nextActionName = nextActionName; }
public void setSteps(final List<ChoreographerStepRequestDTO> steps) { this.steps = steps; }
public void setFirstStepNames(final List<String> firstStepNames) { this.firstStepNames = firstStepNames; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerActionResponseDTO.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.Serializable;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ChoreographerActionResponseDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = -3263344826750594965L;
private long id;
private String name;
private boolean firstAction;
private String nextActionName;
private List<ChoreographerStepResponseDTO> steps;
private List<String> firstStepNames;
private String createdAt;
private String updatedAt;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerActionResponseDTO() {}
//-------------------------------------------------------------------------------------------------
public ChoreographerActionResponseDTO(final long id, final String name, final boolean firstAction, final String nextActionName, final List<ChoreographerStepResponseDTO> steps, final List<String> firstStepNames, final String createdAt,
final String updatedAt) {
this.id = id;
this.name = name;
this.firstAction = firstAction;
this.nextActionName = nextActionName;
this.steps = steps;
this.firstStepNames = firstStepNames;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
//-------------------------------------------------------------------------------------------------
public long getId() { return id; }
public String getName() { return name; }
public boolean isFirstAction() { return firstAction; }
public String getNextActionName() { return nextActionName; }
public List<ChoreographerStepResponseDTO> getSteps() { return steps; }
public List<String> getFirstStepNames() { return firstStepNames; }
public String getCreatedAt() { return createdAt; }
public String getUpdatedAt() { return updatedAt; }
//-------------------------------------------------------------------------------------------------
public void setId(final long id) { this.id = id; }
public void setName(final String name) { this.name = name; }
public void setNextActionName(final String nextActionName) { this.nextActionName = nextActionName; }
public void setSteps(final List<ChoreographerStepResponseDTO> steps) { this.steps = steps; }
public void setFirstStepNames(final List<String> firstStepNames) { this.firstStepNames = firstStepNames; }
public void setCreatedAt(final String createdAt) { this.createdAt = createdAt; }
public void setUpdatedAt(final String updatedAt) { this.updatedAt = updatedAt; }
public void setFirstAction(final boolean firstAction) { this.firstAction = firstAction; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerCheckPlanResponseDTO.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerCheckPlanResponseDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = -6599506456874073377L;
private long planId;
private List<String> errorMessages = new ArrayList<>();
private boolean needInterCloud;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerCheckPlanResponseDTO() {}
//-------------------------------------------------------------------------------------------------
public ChoreographerCheckPlanResponseDTO(final long planId, final List<String> errorMessages, final boolean needInterCloud) {
this.planId = planId;
this.needInterCloud = needInterCloud;
if (errorMessages != null) {
this.errorMessages.addAll(errorMessages);
}
}
//-------------------------------------------------------------------------------------------------
public long getPlanId() { return planId; }
public List<String> getErrorMessages() { return errorMessages; }
public boolean getNeedInterCloud() { return needInterCloud; }
//-------------------------------------------------------------------------------------------------
public void setPlanId(final long planId) { this.planId = planId; }
public void setErrorMessages(final List<String> errorMessages) { this.errorMessages = errorMessages; }
public void setNeedInterCloud(final boolean needInterCloud) { this.needInterCloud = needInterCloud; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerExecuteStepRequestDTO.java
|
/********************************************************************************
* Copyright (c) 2020 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerExecuteStepRequestDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 7693538826059396949L;
private long sessionId;
private long sessionStepId;
private List<OrchestrationResultDTO> preconditionOrchestrationResults;
private OrchestrationResultDTO mainOrchestrationResult;
private int quantity;
private Map<String,String> staticParameters;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerExecuteStepRequestDTO() {}
//-------------------------------------------------------------------------------------------------
public ChoreographerExecuteStepRequestDTO(final long sessionId, final long sessionStepId, final List<OrchestrationResultDTO> preconditionOrchestrationResults, final OrchestrationResultDTO mainOrchestrationResult, final int quantity,
final Map<String,String> staticParameters) {
this.sessionId = sessionId;
this.sessionStepId = sessionStepId;
this.preconditionOrchestrationResults = preconditionOrchestrationResults;
this.mainOrchestrationResult = mainOrchestrationResult;
this.quantity = quantity;
this.staticParameters = staticParameters;
}
//-------------------------------------------------------------------------------------------------
public long getSessionId() { return sessionId; }
public long getSessionStepId() { return sessionStepId; }
public List<OrchestrationResultDTO> getPreconditionOrchestrationResults() { return preconditionOrchestrationResults; }
public OrchestrationResultDTO getMainOrchestrationResult() { return mainOrchestrationResult; }
public int getQuantity() { return quantity; }
public Map<String,String> getStaticParameters() { return staticParameters; }
//-------------------------------------------------------------------------------------------------
public void setSessionId(final long sessionId) { this.sessionId = sessionId; }
public void setSessionStepId(final long sessionStepId) { this.sessionStepId = sessionStepId; }
public void setPreconditionOrchestrationResults(final List<OrchestrationResultDTO> preconditionOrchestrationResults) { this.preconditionOrchestrationResults = preconditionOrchestrationResults; }
public void setMainOrchestrationResult(final OrchestrationResultDTO mainOrchestrationResult) { this.mainOrchestrationResult = mainOrchestrationResult; }
public void setQuantity(final int quantity) { this.quantity = quantity; }
public void setStaticParameters(final Map<String,String> staticParameters) { this.staticParameters = staticParameters; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerExecutedStepResultDTO.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerExecutedStepResultDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = -8977335371238750835L;
private Long sessionId;
private Long sessionStepId;
private ChoreographerExecutedStepStatus status;
private String message;
private String exception;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public Long getSessionId() { return sessionId; }
public Long getSessionStepId() { return sessionStepId; }
public ChoreographerExecutedStepStatus getStatus() { return status; }
public String getMessage() { return message; }
public String getException() { return exception; }
//-------------------------------------------------------------------------------------------------
public void setSessionId(final Long sessionId) { this.sessionId = sessionId; }
public void setSessionStepId(final Long sessionStepId) { this.sessionStepId = sessionStepId; }
public void setStatus(final ChoreographerExecutedStepStatus status) { this.status = status; }
public void setMessage(final String message) { this.message = message; }
public void setException(final String exception) { this.exception = exception; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerExecutedStepStatus.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
public enum ChoreographerExecutedStepStatus {
SUCCESS, ERROR, FATAL_ERROR, ABORTED;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public boolean isError() {
return this == ERROR || this == FATAL_ERROR;
}
//-------------------------------------------------------------------------------------------------
public boolean isFatal() {
return this == FATAL_ERROR;
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerExecutorRequestDTO.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerExecutorRequestDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 519659101385691422L;
private SystemRequestDTO system;
private String baseUri;
private String serviceDefinitionName;
private Integer minVersion;
private Integer maxVersion;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public SystemRequestDTO getSystem() { return system; }
public String getBaseUri() { return baseUri; }
public String getServiceDefinitionName() { return serviceDefinitionName; }
public Integer getMinVersion() { return minVersion; }
public Integer getMaxVersion() { return maxVersion; }
//-------------------------------------------------------------------------------------------------
public void setSystem(final SystemRequestDTO system) { this.system = system; }
public void setBaseUri(final String baseUri) { this.baseUri = baseUri; }
public void setServiceDefinitionName(final String serviceDefinitionName) { this.serviceDefinitionName = serviceDefinitionName; }
public void setMinVersion(final Integer minVersion) { this.minVersion = minVersion; }
public void setMaxVersion(final Integer maxVersion) { this.maxVersion = maxVersion; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerExecutorResponseDTO.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerExecutorResponseDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = -8660896921520588874L;
private long id;
private String name;
private String address;
private int port;
private String baseUri;
private List<ChoreographerExecutorServiceDefinitionResponseDTO> serviceDefinitions;
private String createdAt;
private String updatedAt;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerExecutorResponseDTO() {}
//-------------------------------------------------------------------------------------------------
public ChoreographerExecutorResponseDTO(final long id, final String name, final String address, final int port, final String baseUri,
final List<ChoreographerExecutorServiceDefinitionResponseDTO> serviceDefinitions,
final String createdAt, final String updatedAt) {
this.id = id;
this.name = name;
this.address = address;
this.port = port;
this.baseUri = baseUri;
this.serviceDefinitions = serviceDefinitions;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
//-------------------------------------------------------------------------------------------------
public long getId() { return id; }
public String getName() { return name; }
public String getAddress() { return address; }
public int getPort() { return port; }
public String getBaseUri() { return baseUri; }
public List<ChoreographerExecutorServiceDefinitionResponseDTO> getServiceDefinitions() { return serviceDefinitions; }
public String getCreatedAt() { return createdAt; }
public String getUpdatedAt() { return updatedAt; }
//-------------------------------------------------------------------------------------------------
public void setId(final long id) { this.id = id; }
public void setName(final String name) { this.name = name; }
public void setAddress(final String address) { this.address = address; }
public void setPort(final int port) { this.port = port; }
public void setBaseUri(final String baseUri) { this.baseUri = baseUri; }
public void setServiceDefinitions(final List<ChoreographerExecutorServiceDefinitionResponseDTO> serviceDefinitions) { this.serviceDefinitions = serviceDefinitions; }
public void setCreatedAt(final String createdAt) { this.createdAt = createdAt; }
public void setUpdatedAt(final String updatedAt) { this.updatedAt = updatedAt; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerExecutorServiceDefinitionResponseDTO.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerExecutorServiceDefinitionResponseDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 739704041157654370L;
private long id;
private long executorId;
private String serviceDefinitionName;
private int minVersion;
private int maxVersion;
private String createdAt;
private String updatedAt;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerExecutorServiceDefinitionResponseDTO() { }
//-------------------------------------------------------------------------------------------------
public ChoreographerExecutorServiceDefinitionResponseDTO(final long id, final long executorId, final String serviceDefinitionName, final int minVersion, final int maxVersion,
final String createdAt, final String updatedAt) {
this.id = id;
this.executorId = executorId;
this.serviceDefinitionName = serviceDefinitionName;
this.minVersion = minVersion;
this.maxVersion = maxVersion;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
//-------------------------------------------------------------------------------------------------
public long getId() { return id; }
public long getExecutorId() { return executorId; }
public String getServiceDefinitionName() { return serviceDefinitionName; }
public int getMinVersion() { return minVersion; }
public int getMaxVersion() { return maxVersion; }
public String getCreatedAt() { return createdAt; }
public String getUpdatedAt() { return updatedAt; }
//-------------------------------------------------------------------------------------------------
public void setId(final long id) { this.id = id; }
public void setExecutorId(final long executorId) { this.executorId = executorId; }
public void setServiceDefinitionName(final String serviceDefinitionName) { this.serviceDefinitionName = serviceDefinitionName; }
public void setMinVersion(final int minVersion) { this.minVersion = minVersion; }
public void setMaxVersion(final int maxVersion) { this.maxVersion = maxVersion; }
public void setCreatedAt(final String createdAt) { this.createdAt = createdAt; }
public void setUpdatedAt(final String updatedAt) { this.updatedAt = updatedAt; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerExecutorServiceInfoRequestDTO.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerExecutorServiceInfoRequestDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 8360159447969430679L;
private String serviceDefinition;
private Integer minVersion;
private Integer maxVersion;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerExecutorServiceInfoRequestDTO() {}
//-------------------------------------------------------------------------------------------------
public ChoreographerExecutorServiceInfoRequestDTO(final String serviceDefinition, final Integer minVersion, final Integer maxVersion) {
this.serviceDefinition = serviceDefinition;
this.minVersion = minVersion;
this.maxVersion = maxVersion;
}
//-------------------------------------------------------------------------------------------------
public String getServiceDefinition() { return serviceDefinition; }
public Integer getMinVersion() { return minVersion; }
public Integer getMaxVersion() { return maxVersion; }
//-------------------------------------------------------------------------------------------------
public void setServiceDefinition(final String serviceDefinition) { this.serviceDefinition = serviceDefinition; }
public void setMinVersion(final Integer minVersion) { this.minVersion = minVersion; }
public void setMaxVersion(final Integer maxVersion) { this.maxVersion = maxVersion; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerExecutorServiceInfoResponseDTO.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerExecutorServiceInfoResponseDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 5217709257980451694L;
private String serviceDefinition;
private int minVersion;
private int maxVersion;
private List<ChoreographerServiceQueryFormDTO> dependencies;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerExecutorServiceInfoResponseDTO() {}
//-------------------------------------------------------------------------------------------------
public ChoreographerExecutorServiceInfoResponseDTO(final String serviceDefinition, final int minVersion, final int maxVersion, final List<ChoreographerServiceQueryFormDTO> dependencies) {
this.serviceDefinition = serviceDefinition;
this.minVersion = minVersion;
this.maxVersion = maxVersion;
this.dependencies = dependencies;
}
//-------------------------------------------------------------------------------------------------
public String getServiceDefinition() { return serviceDefinition; }
public int getMinVersion() { return minVersion; }
public int getMaxVersion() { return maxVersion; }
public List<ChoreographerServiceQueryFormDTO> getDependencies() { return dependencies; }
//-------------------------------------------------------------------------------------------------
public void setServiceDefinition(final String serviceDefinition) { this.serviceDefinition = serviceDefinition; }
public void setMinVersion(final int minVersion) { this.minVersion = minVersion; }
public void setMaxVersion(final int maxVersion) { this.maxVersion = maxVersion; }
public void setDependencies(final List<ChoreographerServiceQueryFormDTO> dependencies) { this.dependencies = dependencies; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/dto/shared/ChoreographerNotificationDTO.java
|
/********************************************************************************
* Copyright (c) 2021 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.dto.shared;
import java.io.Serializable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ChoreographerNotificationDTO implements Serializable {
//=================================================================================================
// members
private static final long serialVersionUID = 222508477814610141L;
private long sessionId;
private long planId;
private String planName;
private String timestamp;
private ChoreographerSessionStatus status;
private String message;
private String details;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public ChoreographerNotificationDTO() {}
//-------------------------------------------------------------------------------------------------
public ChoreographerNotificationDTO(final long sessionId, final long planId, final String planName, final String timestamp, final ChoreographerSessionStatus status, final String message, final String details) {
super();
this.sessionId = sessionId;
this.planId = planId;
this.planName = planName;
this.timestamp = timestamp;
this.status = status;
this.message = message;
this.details = details;
}
//-------------------------------------------------------------------------------------------------
public long getSessionId() { return sessionId; }
public long getPlanId() { return planId; }
public String getPlanName() { return planName; }
public String getTimestamp() { return timestamp; }
public ChoreographerSessionStatus getStatus() { return status; }
public String getMessage() { return message; }
public String getDetails() { return details; }
//-------------------------------------------------------------------------------------------------
public void setSessionId(final long sessionId) { this.sessionId = sessionId; }
public void setPlanId(final long planId) { this.planId = planId; }
public void setPlanName(final String planName) { this.planName = planName; }
public void setTimestamp(final String timestamp) { this.timestamp = timestamp; }
public void setStatus(final ChoreographerSessionStatus status) { this.status = status; }
public void setMessage(final String message) { this.message = message; }
public void setDetails(final String details) { this.details = details; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final JsonProcessingException ex) {
return "toString failure";
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.