Also format all Java files to be consistent.
Change-Id: Id0db0ebfff0745270de9c6d833bc24177a136594
Signed-off-by: Serban Jora <sj2381@att.com>
import com.fasterxml.jackson.databind.ObjectMapper;
-
/**
*
*
*/
-@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
+@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
+ DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
@SpringBootApplication
public class Application implements ApplicationContextAware {
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpStatusCodeException;
-
@Component("peergateway")
-//@Scope("singleton")
-@ConfigurationProperties(prefix="federation")
+// @Scope("singleton")
+@ConfigurationProperties(prefix = "federation")
@Conditional(GatewayCondition.class)
public class PeerGateway {
private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerGateway.class);
- private TaskExecutor taskExecutor;
+ private TaskExecutor taskExecutor;
@Autowired
private Environment env;
@Autowired
private Clients clients;
-
@PostConstruct
public void initGateway() {
logger.debug(EELFLoggerDelegate.debugLogger, "initPeerGateway");
/* make sure an operator was specified and that it is a declared user */
if (null == this.env.getProperty("federation.operator")) {
throw new BeanInitializationException("Missing 'federation.operator' configuration");
- }
- else {
+ } else {
try {
if (null == this.clients.getClient().getUser(this.env.getProperty("federation.operator"))) {
- logger.warn(EELFLoggerDelegate.errorLogger, "'federation.operator' does not point to an existing user");
+ logger.warn(EELFLoggerDelegate.errorLogger,
+ "'federation.operator' does not point to an existing user");
}
- }
- catch (/*HttpStatusCode*/Exception dx) {
+ } catch (/* HttpStatusCode */Exception dx) {
logger.warn(EELFLoggerDelegate.errorLogger, "failed to verify 'federation.operator' value", dx);
}
}
this.taskExecutor = new ThreadPoolTaskExecutor();
- ((ThreadPoolTaskExecutor)this.taskExecutor).setCorePoolSize(1);
- ((ThreadPoolTaskExecutor)this.taskExecutor).setMaxPoolSize(1);
- ((ThreadPoolTaskExecutor)this.taskExecutor).setQueueCapacity(25);
- ((ThreadPoolTaskExecutor)this.taskExecutor).initialize();
+ ((ThreadPoolTaskExecutor) this.taskExecutor).setCorePoolSize(1);
+ ((ThreadPoolTaskExecutor) this.taskExecutor).setMaxPoolSize(1);
+ ((ThreadPoolTaskExecutor) this.taskExecutor).setQueueCapacity(25);
+ ((ThreadPoolTaskExecutor) this.taskExecutor).initialize();
// Done
logger.debug(EELFLoggerDelegate.debugLogger, "PeerGateway available");
logger.debug(EELFLoggerDelegate.debugLogger, "PeerGateway destroyed");
}
- protected String getOwnerId(MLPPeerSubscription theSubscription/*,
- MLPSolution theSolution*/) {
- String ownerId = theSubscription.getOwnerId();
- return ownerId != null ? ownerId : this.env.getProperty("federation.operator");
+ protected String getOwnerId(MLPPeerSubscription theSubscription/*
+ * , MLPSolution theSolution
+ */) {
+ String ownerId = theSubscription.getOwnerId();
+ return ownerId != null ? ownerId : this.env.getProperty("federation.operator");
}
@EventListener
public void handlePeerSubscriptionUpdate(PeerSubscriptionEvent theEvent) {
logger.info(EELFLoggerDelegate.debugLogger, "received peer subscription update event " + theEvent);
taskExecutor.execute(
- new PeerGatewayUpdateTask(theEvent.getPeer(),
- theEvent.getSubscription(),
- theEvent.getSolutions()));
+ new PeerGatewayUpdateTask(theEvent.getPeer(), theEvent.getSubscription(), theEvent.getSolutions()));
}
-
/**
- * The list of solutions processed here represents the solutions (with
- * respect to the subscription filter definition) that were
- * reported by the peer as being updated since the last check.
+ * The list of solutions processed here represents the solutions (with respect
+ * to the subscription filter definition) that were reported by the peer as
+ * being updated since the last check.
*/
public class PeerGatewayUpdateTask implements Runnable {
- private MLPPeer peer;
+ private MLPPeer peer;
private MLPPeerSubscription sub;
- private List<MLPSolution> solutions;
-
+ private List<MLPSolution> solutions;
- public PeerGatewayUpdateTask(MLPPeer thePeer,
- MLPPeerSubscription theSub,
- List<MLPSolution> theSolutions) {
+ public PeerGatewayUpdateTask(MLPPeer thePeer, MLPPeerSubscription theSub, List<MLPSolution> theSolutions) {
this.peer = thePeer;
this.sub = theSub;
this.solutions = theSolutions;
logger.info(EELFLoggerDelegate.debugLogger, "Received peer " + this.peer + " solutions: " + this.solutions);
ICommonDataServiceRestClient cdsClient = PeerGateway.this.clients.getClient();
- for (MLPSolution peerSolution: this.solutions) {
- //Check if the Model already exists in the Local Acumos
- MLPSolution localSolution = null;
+ for (MLPSolution peerSolution : this.solutions) {
+ // Check if the Model already exists in the Local Acumos
+ MLPSolution localSolution = null;
try {
localSolution = cdsClient.getSolution(peerSolution.getSolutionId());
- }
- catch (HttpStatusCodeException x) {
+ } catch (HttpStatusCodeException x) {
if (!Errors.isCDSNotFound(x)) {
- logger.warn(EELFLoggerDelegate.errorLogger, "Failed to check if solution with id " + peerSolution.getSolutionId() + " exists locally, skipping for now", x);
+ logger.warn(EELFLoggerDelegate.errorLogger, "Failed to check if solution with id "
+ + peerSolution.getSolutionId() + " exists locally, skipping for now", x);
continue;
}
}
try {
- if (localSolution == null) {
- logger.info(EELFLoggerDelegate.debugLogger, "Solution Id : " + peerSolution.getSolutionId() + " does not exists locally, adding it to local catalog ");
+ if (localSolution == null) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Solution Id : " + peerSolution.getSolutionId()
+ + " does not exists locally, adding it to local catalog ");
localSolution = createMLPSolution(peerSolution, cdsClient);
- }
- else {
+ } else {
localSolution = updateMLPSolution(peerSolution, localSolution, cdsClient);
}
mapSolution(localSolution, cdsClient);
- }
- catch (Exception x) {
+ } catch (Exception x) {
x.printStackTrace();
- logger.warn(EELFLoggerDelegate.debugLogger, "Mapping of acumos solution failed for: " + peerSolution, x);
+ logger.warn(EELFLoggerDelegate.debugLogger,
+ "Mapping of acumos solution failed for: " + peerSolution, x);
}
}
}
-
- private MLPSolution createMLPSolution(
- MLPSolution peerMLPSolution,
- ICommonDataServiceRestClient cdsClient) {
- logger.info(EELFLoggerDelegate.debugLogger, "Creating Local MLP Solution for peer solution " + peerMLPSolution);
+
+ private MLPSolution createMLPSolution(MLPSolution peerMLPSolution, ICommonDataServiceRestClient cdsClient) {
+ logger.info(EELFLoggerDelegate.debugLogger,
+ "Creating Local MLP Solution for peer solution " + peerMLPSolution);
MLPSolution localSolution = new MLPSolution();
localSolution.setSolutionId(peerMLPSolution.getSolutionId());
localSolution.setName(peerMLPSolution.getName());
try {
cdsClient.createSolution(localSolution);
return localSolution;
- }
- catch (HttpStatusCodeException restx) {
- logger.error(EELFLoggerDelegate.debugLogger, "createSolution CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
+ } catch (HttpStatusCodeException restx) {
+ logger.error(EELFLoggerDelegate.debugLogger,
+ "createSolution CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
return null;
- }
- catch (Exception x) {
- logger.error(EELFLoggerDelegate.debugLogger, "createMLPSolution unexpected failure", x);
+ } catch (Exception x) {
+ logger.error(EELFLoggerDelegate.debugLogger, "createMLPSolution unexpected failure", x);
return null;
}
}
-
- private MLPSolutionRevision createMLPSolutionRevision(
- MLPSolutionRevision mlpSolutionRevision,
- ICommonDataServiceRestClient cdsClient) {
+
+ private MLPSolutionRevision createMLPSolutionRevision(MLPSolutionRevision mlpSolutionRevision,
+ ICommonDataServiceRestClient cdsClient) {
MLPSolutionRevision solutionRevision = new MLPSolutionRevision();
solutionRevision.setSolutionId(mlpSolutionRevision.getSolutionId());
solutionRevision.setRevisionId(mlpSolutionRevision.getRevisionId());
try {
cdsClient.createSolutionRevision(solutionRevision);
return solutionRevision;
- }
- catch (HttpStatusCodeException restx) {
- logger.error(EELFLoggerDelegate.debugLogger, "createSolutionRevision CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
+ } catch (HttpStatusCodeException restx) {
+ logger.error(EELFLoggerDelegate.debugLogger,
+ "createSolutionRevision CDS call failed. CDS message is " + restx.getResponseBodyAsString(),
+ restx);
return null;
- }
- catch (Exception x) {
- logger.error(EELFLoggerDelegate.debugLogger, "createSolutionRevision unexpected failure", x);
+ } catch (Exception x) {
+ logger.error(EELFLoggerDelegate.debugLogger, "createSolutionRevision unexpected failure", x);
return null;
}
}
-
- private MLPArtifact createMLPArtifact(
- String theSolutionId,
- String theRevisionId,
- MLPArtifact mlpArtifact,
+
+ private MLPArtifact createMLPArtifact(String theSolutionId, String theRevisionId, MLPArtifact mlpArtifact,
ICommonDataServiceRestClient cdsClient) {
MLPArtifact artifact = new MLPArtifact();
artifact.setArtifactId(mlpArtifact.getArtifactId());
artifact.setModified(mlpArtifact.getModified());
artifact.setName(mlpArtifact.getName());
artifact.setOwnerId(getOwnerId(this.sub));
- artifact.setSize(mlpArtifact.getSize());;
+ artifact.setSize(mlpArtifact.getSize());
+ ;
artifact.setUri(mlpArtifact.getUri());
artifact.setVersion(mlpArtifact.getVersion());
try {
cdsClient.createArtifact(artifact);
cdsClient.addSolutionRevisionArtifact(theSolutionId, theRevisionId, mlpArtifact.getArtifactId());
return artifact;
- }
- catch (HttpStatusCodeException restx) {
- logger.error(EELFLoggerDelegate.debugLogger, "createArtifact CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
+ } catch (HttpStatusCodeException restx) {
+ logger.error(EELFLoggerDelegate.debugLogger,
+ "createArtifact CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
return null;
- }
- catch (Exception x) {
+ } catch (Exception x) {
logger.error(EELFLoggerDelegate.debugLogger, "createArtifact unexpected failure", x);
return null;
}
}
-
+
private MLPArtifact copyMLPArtifact(MLPArtifact peerMLPArtifact, MLPArtifact localMLPArtifact) {
-
+
localMLPArtifact.setArtifactId(peerMLPArtifact.getArtifactId());
localMLPArtifact.setArtifactTypeCode(peerMLPArtifact.getArtifactTypeCode());
localMLPArtifact.setCreated(peerMLPArtifact.getCreated());
localMLPArtifact.setVersion(peerMLPArtifact.getVersion());
return localMLPArtifact;
}
-
- private MLPSolution updateMLPSolution(MLPSolution peerMLPSolution, MLPSolution localMLPSolution, ICommonDataServiceRestClient cdsClient) {
- logger.info(EELFLoggerDelegate.debugLogger, "Updating Local MLP Solution for peer solution " + peerMLPSolution);
- if (!peerMLPSolution.getSolutionId().equals(
- localMLPSolution.getSolutionId()))
+ private MLPSolution updateMLPSolution(MLPSolution peerMLPSolution, MLPSolution localMLPSolution,
+ ICommonDataServiceRestClient cdsClient) {
+ logger.info(EELFLoggerDelegate.debugLogger,
+ "Updating Local MLP Solution for peer solution " + peerMLPSolution);
+
+ if (!peerMLPSolution.getSolutionId().equals(localMLPSolution.getSolutionId()))
throw new IllegalArgumentException("Local and Peer identifier mismatch");
localMLPSolution.setSolutionId(peerMLPSolution.getSolutionId());
localMLPSolution.setProvider(peerMLPSolution.getProvider());
localMLPSolution.setActive(peerMLPSolution.isActive());
localMLPSolution.setToolkitTypeCode(peerMLPSolution.getToolkitTypeCode());
- //an update needs to be re-validated
+ // an update needs to be re-validated
localMLPSolution.setValidationStatusCode(ValidationStatusCode.NV.toString());
{
String newOwnerId = getOwnerId(this.sub);
if (!newOwnerId.equals(localMLPSolution.getOwnerId())) {
- //is this solution being updated as part of different/new subscription?
- logger.warn(EELFLoggerDelegate.errorLogger, "updating solution " + localMLPSolution.getSolutionId() + " as part of subscription " + this.sub.getSubId() + " triggers an ownership change");
+ // is this solution being updated as part of different/new subscription?
+ logger.warn(EELFLoggerDelegate.errorLogger, "updating solution " + localMLPSolution.getSolutionId()
+ + " as part of subscription " + this.sub.getSubId() + " triggers an ownership change");
}
localMLPSolution.setOwnerId(newOwnerId);
}
{
String newSourceId = this.peer.getPeerId();
if (!newSourceId.equals(localMLPSolution.getSourceId())) {
- //we will see this if a solution is available in more than one peer
- logger.warn(EELFLoggerDelegate.errorLogger, "updating solution " + localMLPSolution.getSolutionId() + " as part of subscription " + this.sub.getSubId() + " triggers a source change");
+ // we will see this if a solution is available in more than one peer
+ logger.warn(EELFLoggerDelegate.errorLogger, "updating solution " + localMLPSolution.getSolutionId()
+ + " as part of subscription " + this.sub.getSubId() + " triggers a source change");
}
localMLPSolution.setSourceId(newSourceId);
}
try {
cdsClient.updateSolution(localMLPSolution);
return localMLPSolution;
- }
- catch (HttpStatusCodeException restx) {
- logger.error(EELFLoggerDelegate.debugLogger, "updateSolution CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
+ } catch (HttpStatusCodeException restx) {
+ logger.error(EELFLoggerDelegate.debugLogger,
+ "updateSolution CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
return null;
- }
- catch (Exception x) {
- logger.error(EELFLoggerDelegate.debugLogger, "updateSolution unexpected failure", x);
+ } catch (Exception x) {
+ logger.error(EELFLoggerDelegate.debugLogger, "updateSolution unexpected failure", x);
return null;
}
}
-
+
/**
* Here comes the core process of updating a local solution's related
* information with what is available from a peer.
- */
+ *
+ * @param theSolution
+ * the local solution who's related information (revisions and
+ * artifacts) we are trying to sync
+ * @param cdsClient
+ * CDS client to use in the process
+ * @throws Exception
+ * any error related to CDS and peer interaction
+ */
protected void mapSolution(MLPSolution theSolution, ICommonDataServiceRestClient cdsClient) throws Exception {
- FederationClient fedClient =
- clients.getFederationClient(this.peer.getApiUrl());
+ FederationClient fedClient = clients.getFederationClient(this.peer.getApiUrl());
- //get revisions
+ // get revisions
List<MLPSolutionRevision> peerRevisions = null;
try {
- peerRevisions = (List<MLPSolutionRevision>)
- fedClient.getSolutionRevisions(theSolution.getSolutionId()).getResponseBody();
- }
- catch (Exception x) {
- logger.warn(EELFLoggerDelegate.errorLogger, "Failed to retrieve acumos revisions for solution " + theSolution.getSolutionId() + " from peer " + this.peer, x);
+ peerRevisions = (List<MLPSolutionRevision>) fedClient.getSolutionRevisions(theSolution.getSolutionId())
+ .getResponseBody();
+ } catch (Exception x) {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Failed to retrieve acumos revisions for solution "
+ + theSolution.getSolutionId() + " from peer " + this.peer, x);
throw x;
}
- //this should not happen as any solution should have at least one
- //revision (but that's an assumption on how on-boarding works)
+ // this should not happen as any solution should have at least one
+ // revision (but that's an assumption on how on-boarding works)
if (peerRevisions == null || peerRevisions.size() == 0) {
logger.warn(EELFLoggerDelegate.debugLogger, "No revisions were retrieved");
return;
- }
+ }
- //check if we have locally the latest revision available on the peer
- //TODO: this is just one possible policy regarding the handling of
- //such a mismatch
+ // check if we have locally the latest revision available on the peer
+ // TODO: this is just one possible policy regarding the handling of
+ // such a mismatch
List<MLPSolutionRevision> cdsRevisions = Collections.EMPTY_LIST;
try {
- cdsRevisions =
- cdsClient.getSolutionRevisions(theSolution.getSolutionId());
- }
- catch (HttpStatusCodeException restx) {
+ cdsRevisions = cdsClient.getSolutionRevisions(theSolution.getSolutionId());
+ } catch (HttpStatusCodeException restx) {
if (!Errors.isCDSNotFound(restx)) {
- logger.error(EELFLoggerDelegate.debugLogger, "getSolutionRevisions CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
+ logger.error(EELFLoggerDelegate.debugLogger,
+ "getSolutionRevisions CDS call failed. CDS message is " + restx.getResponseBodyAsString(),
+ restx);
throw restx;
}
}
final List<MLPSolutionRevision> localRevisions = cdsRevisions;
- //map peer revisions to local ones; new peer revisions have a null mapping
+ // map peer revisions to local ones; new peer revisions have a null mapping
Map<MLPSolutionRevision, MLPSolutionRevision> peerToLocalRevisions =
- /*
- Elegant but toMap uses map merging which does not allow null values
- peerRevisions
- .stream()
- .collect(
- Collectors.toMap(...)
- */
- new HashMap<MLPSolutionRevision, MLPSolutionRevision>();
- peerRevisions.forEach(
- peerRevision -> peerToLocalRevisions.put(
- peerRevision, localRevisions
- .stream()
- .filter(localRevision ->
- localRevision.getRevisionId().equals(
- peerRevision.getRevisionId()))
- .findFirst()
- .orElse(null)));
-
-
-
- for (Map.Entry<MLPSolutionRevision, MLPSolutionRevision> revisionEntry:
- peerToLocalRevisions.entrySet()) {
- MLPSolutionRevision peerRevision = revisionEntry.getKey(),
- localRevision = revisionEntry.getValue();
- //get peer artifacts
+ /*
+ * Elegant but toMap uses map merging which does not allow null values
+ * peerRevisions .stream() .collect( Collectors.toMap(...)
+ */
+ new HashMap<MLPSolutionRevision, MLPSolutionRevision>();
+ peerRevisions.forEach(peerRevision -> peerToLocalRevisions.put(peerRevision,
+ localRevisions.stream()
+ .filter(localRevision -> localRevision.getRevisionId().equals(peerRevision.getRevisionId()))
+ .findFirst().orElse(null)));
+
+ for (Map.Entry<MLPSolutionRevision, MLPSolutionRevision> revisionEntry : peerToLocalRevisions.entrySet()) {
+ MLPSolutionRevision peerRevision = revisionEntry.getKey(), localRevision = revisionEntry.getValue();
+ // get peer artifacts
List<MLPArtifact> peerArtifacts = null;
try {
- peerArtifacts = (List<MLPArtifact>)
- fedClient.getArtifacts(theSolution.getSolutionId(), peerRevision.getRevisionId())
- .getResponseBody();
- }
- catch (Exception x) {
+ peerArtifacts = (List<MLPArtifact>) fedClient
+ .getArtifacts(theSolution.getSolutionId(), peerRevision.getRevisionId()).getResponseBody();
+ } catch (Exception x) {
logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve peer acumos artifacts", x);
throw x;
- }
+ }
- List<MLPArtifact> cdsArtifacts = Collections.EMPTY_LIST;
+ List<MLPArtifact> cdsArtifacts = Collections.EMPTY_LIST;
if (localRevision == null) {
- localRevision = createMLPSolutionRevision(peerRevision, cdsClient);
- }
- else {
+ localRevision = createMLPSolutionRevision(peerRevision, cdsClient);
+ } else {
try {
- cdsArtifacts = cdsClient.getSolutionRevisionArtifacts(theSolution.getSolutionId(), localRevision.getRevisionId());
- }
- catch (HttpStatusCodeException restx) {
+ cdsArtifacts = cdsClient.getSolutionRevisionArtifacts(theSolution.getSolutionId(),
+ localRevision.getRevisionId());
+ } catch (HttpStatusCodeException restx) {
if (!Errors.isCDSNotFound(restx)) {
- logger.error(EELFLoggerDelegate.debugLogger, "getArtifact CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
+ logger.error(EELFLoggerDelegate.debugLogger,
+ "getArtifact CDS call failed. CDS message is " + restx.getResponseBodyAsString(),
+ restx);
throw restx;
}
}
}
- final List<MLPArtifact> localArtifacts = cdsArtifacts;
- //map the artifacts
- //TODO: track deleted artifacts
- Map<MLPArtifact, MLPArtifact> peerToLocalArtifacts =
- new HashMap<MLPArtifact, MLPArtifact>();
- peerArtifacts.forEach(
- peerArtifact -> peerToLocalArtifacts.put(
- peerArtifact, localArtifacts
- .stream()
- .filter(localArtifact ->
- localArtifact.getArtifactId().equals(
- peerArtifact.getArtifactId()))
- .findFirst()
- .orElse(null)));
-
- for (Map.Entry<MLPArtifact, MLPArtifact> artifactEntry:
- peerToLocalArtifacts.entrySet()) {
- MLPArtifact peerArtifact = artifactEntry.getKey(),
- localArtifact = artifactEntry.getValue();
+ final List<MLPArtifact> localArtifacts = cdsArtifacts;
+ // map the artifacts
+ // TODO: track deleted artifacts
+ Map<MLPArtifact, MLPArtifact> peerToLocalArtifacts = new HashMap<MLPArtifact, MLPArtifact>();
+ peerArtifacts.forEach(peerArtifact -> peerToLocalArtifacts.put(peerArtifact, localArtifacts.stream()
+ .filter(localArtifact -> localArtifact.getArtifactId().equals(peerArtifact.getArtifactId()))
+ .findFirst().orElse(null)));
+
+ for (Map.Entry<MLPArtifact, MLPArtifact> artifactEntry : peerToLocalArtifacts.entrySet()) {
+ MLPArtifact peerArtifact = artifactEntry.getKey(), localArtifact = artifactEntry.getValue();
boolean doUpdate = false;
if (localArtifact == null) {
- localArtifact = createMLPArtifact(
- theSolution.getSolutionId(),
- localRevision.getRevisionId(),
- peerArtifact,
- cdsClient);
- }
- else {
+ localArtifact = createMLPArtifact(theSolution.getSolutionId(), localRevision.getRevisionId(),
+ peerArtifact, cdsClient);
+ } else {
if (!peerArtifact.getVersion().equals(localArtifact.getVersion())) {
- //update local artifact
+ // update local artifact
copyMLPArtifact(peerArtifact, localArtifact);
doUpdate = true;
- }
+ }
}
- //TODO: with CDS 1.13 check the subscription scope to decide if
- //content is to be downloaded
+ // TODO: with CDS 1.13 check the subscription scope to decide if
+ // content is to be downloaded
boolean doContent = true;
if (doContent) {
- //TODO: we are trying to access the artifact by its identifier which
- //is fine in the common case but the uri specified in the artifact
- //data is a more flexible approach.
+ // TODO: we are trying to access the artifact by its identifier which
+ // is fine in the common case but the uri specified in the artifact
+ // data is a more flexible approach.
Resource artifactContent = null;
try {
artifactContent = fedClient.downloadArtifact(peerArtifact.getArtifactId());
- }
- catch (Exception x) {
- logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos artifact content", x);
+ } catch (Exception x) {
+ logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos artifact content",
+ x);
}
UploadArtifactInfo uploadInfo = null;
if (artifactContent != null) {
try {
- uploadInfo =
- PeerGateway.this.clients.getNexusClient()
- .uploadArtifact(
- PeerGateway.this.env.getProperty("nexus.groupId"),
- localArtifact.getName(), /* probably wrong */
- localArtifact.getVersion(),
- "", /* should receive this from peer */
- artifactContent.contentLength(),
- artifactContent.getInputStream());
- }
- catch (Exception x) {
- logger.warn(EELFLoggerDelegate.debugLogger, "Failed to push artifact content to local Nexus repo", x);
+ uploadInfo = PeerGateway.this.clients.getNexusClient()
+ .uploadArtifact(PeerGateway.this.env.getProperty("nexus.groupId"),
+ localArtifact.getName(), /* probably wrong */
+ localArtifact.getVersion(), "", /* should receive this from peer */
+ artifactContent.contentLength(), artifactContent.getInputStream());
+ } catch (Exception x) {
+ logger.warn(EELFLoggerDelegate.debugLogger,
+ "Failed to push artifact content to local Nexus repo", x);
}
}
if (uploadInfo != null) {
- //update artifact with local repo reference
+ // update artifact with local repo reference
localArtifact.setUri(uploadInfo.getArtifactMvnPath());
- //the artifact info will need to be updated with local content uri
+ // the artifact info will need to be updated with local content uri
doUpdate = true;
}
}
if (doUpdate) {
try {
cdsClient.updateArtifact(localArtifact);
- }
- catch (HttpStatusCodeException restx) {
- logger.error(EELFLoggerDelegate.debugLogger, "updateArtifact CDS call failed. CDS message is " + restx.getResponseBodyAsString(), restx);
+ } catch (HttpStatusCodeException restx) {
+ logger.error(EELFLoggerDelegate.debugLogger,
+ "updateArtifact CDS call failed. CDS message is " + restx.getResponseBodyAsString(),
+ restx);
}
}
}
}
- } //mapSolution
+ } // mapSolution
}
}
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
-
@Component("onap")
-//@Scope("singleton")
-@ConfigurationProperties(prefix="onap")
+// @Scope("singleton")
+@ConfigurationProperties(prefix = "onap")
@Conditional(ONAPAdapterCondition.class)
public class ONAP {
private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ONAP.class);
- private ASDC asdc = new ASDC();
- private String asdcOperator;
- private TaskExecutor taskExecutor;
- @Autowired
- private Clients clients;
+ private ASDC asdc = new ASDC();
+ private String asdcOperator;
+ private TaskExecutor taskExecutor;
+ @Autowired
+ private Clients clients;
-
public void setSdcUri(URI theUri) {
this.asdc.setUri(theUri);
}
public void setSdcRootPath(String thePath) {
this.asdc.setRootPath(thePath);
}
-
+
public void setSdcOperator(String theUid) {
this.asdcOperator = theUid;
}
throw new BeanInitializationException("Forgot to configure the SDC user ('onap.sdcOperator) ??");
this.taskExecutor = new ThreadPoolTaskExecutor();
- ((ThreadPoolTaskExecutor)this.taskExecutor).setCorePoolSize(1);
- ((ThreadPoolTaskExecutor)this.taskExecutor).setMaxPoolSize(1);
- ((ThreadPoolTaskExecutor)this.taskExecutor).setQueueCapacity(25);
- ((ThreadPoolTaskExecutor)this.taskExecutor).initialize();
+ ((ThreadPoolTaskExecutor) this.taskExecutor).setCorePoolSize(1);
+ ((ThreadPoolTaskExecutor) this.taskExecutor).setMaxPoolSize(1);
+ ((ThreadPoolTaskExecutor) this.taskExecutor).setQueueCapacity(25);
+ ((ThreadPoolTaskExecutor) this.taskExecutor).initialize();
- //temporary
+ // temporary
cleanup();
// Done
taskExecutor.execute(new ONAPPushTask(theEvent.getPeer(), theEvent.getSolutions()));
}
-
public class ONAPPushTask implements Runnable {
- private MLPPeer peer;
+ private MLPPeer peer;
private List<MLPSolution> solutions;
public ONAPPushTask(MLPPeer thePeer, List<MLPSolution> theSolutions) {
public void run() {
- //list with category and subcategory currently used for onap
- //more dynamic mapping to come: based on solution information it will provide sdc assettype, categoty and subcategoty
-
+ // list with category and subcategory currently used for onap
+ // more dynamic mapping to come: based on solution information it will provide
+ // sdc assettype, categoty and subcategoty
+
JSONArray sdcAssets = null;
try {
- sdcAssets = asdc.getAssets(AssetType.resource, JSONArray.class, "Generic", "Abstract")
- .waitForResult();
- }
- catch (Throwable x) {
+ sdcAssets = asdc.getAssets(AssetType.resource, JSONArray.class, "Generic", "Abstract").waitForResult();
+ } catch (Throwable x) {
logger.warn(EELFLoggerDelegate.debugLogger, "Failed to list ONAP SDC assets: " + x.getCause(), x);
- //if this is a 404 NotFound, continue, otherwise, fail
- if (x instanceof ASDCException &&
- x.getCause() instanceof HttpClientErrorException &&
- ((HttpClientErrorException)x.getCause()).getStatusCode() == HttpStatus.NOT_FOUND) {
+ // if this is a 404 NotFound, continue, otherwise, fail
+ if (x instanceof ASDCException && x.getCause() instanceof HttpClientErrorException
+ && ((HttpClientErrorException) x.getCause()).getStatusCode() == HttpStatus.NOT_FOUND) {
sdcAssets = new JSONArray();
- }
- else
+ } else
return;
}
- //logger.info(EELFLoggerDelegate.debugLogger, "Retrieved ONAP SDC assets: " + sdcAssets);
- //logger.info(EELFLoggerDelegate.debugLogger, "Received Acumos solutions: " + this.solutions);
+ // logger.info(EELFLoggerDelegate.debugLogger, "Retrieved ONAP SDC assets: " +
+ // sdcAssets);
+ // logger.info(EELFLoggerDelegate.debugLogger, "Received Acumos solutions: " +
+ // this.solutions);
- for (MLPSolution acumosSolution: this.solutions) {
+ for (MLPSolution acumosSolution : this.solutions) {
try {
- //does it already exist in sdc
+ // does it already exist in sdc
JSONObject sdcAsset = lookupSdcAsset(acumosSolution, sdcAssets);
if (sdcAsset == null) {
- //new solution
+ // new solution
sdcAsset = createSdcAsset(acumosSolution);
- }
- else {
- //ONAP.this.asdc.checkoutResource(UUID.fromString(sdcAsset.getString("artifactUUID")), ONAP.this.asdcOperator, "updated solution import");
+ } else {
+ // ONAP.this.asdc.checkoutResource(UUID.fromString(sdcAsset.getString("artifactUUID")),
+ // ONAP.this.asdcOperator, "updated solution import");
sdcAsset = updateSdcAsset(sdcAsset, acumosSolution);
}
updateAssetArtifacts(sdcAsset, acumosSolution);
- //ONAP.this.asdc.checkinResource(UUID.fromString(sdcAsset.getString("artifactUUID")), ONAP.this.asdcOperator, "solution imported " + " the acumos revision number ");
- }
- catch (Exception x) {
- logger.warn(EELFLoggerDelegate.debugLogger, "Mapping of acumos solution failed for: " + acumosSolution + ": " + x);
+ // ONAP.this.asdc.checkinResource(UUID.fromString(sdcAsset.getString("artifactUUID")),
+ // ONAP.this.asdcOperator, "solution imported " + " the acumos revision number
+ // ");
+ } catch (Exception x) {
+ logger.warn(EELFLoggerDelegate.debugLogger,
+ "Mapping of acumos solution failed for: " + acumosSolution + ": " + x);
}
}
}
return null;
for (int i = 0; i < theAssets.length(); i++) {
JSONObject asset = theAssets.optJSONObject(i);
- if (same(theSolution, asset))
+ if (same(theSolution, asset))
return asset;
}
return null;
public JSONObject createSdcAsset(MLPSolution theSolution) throws Exception {
logger.info(EELFLoggerDelegate.debugLogger, "Creating ONAP SDC VF for solution " + theSolution);
- String description = null;//theSolution.getDescription();
+ String description = null;// theSolution.getDescription();
if (description == null)
description = theSolution.getSolutionId();// + "@acumos";
try {
- return
- ONAP.this.asdc.createVF()
- .withCategory("Generic")
- .withSubCategory("Abstract")
- .withName(theSolution.getName() + "-" + theSolution.getSolutionId()) //sdc names are unique, acumos ones not so
- .withDescription(description)
- .withVendorName("AcumosInc")
- .withVendorRelease("1.0") //cannot update so .. but might want to fetch the last Acumos revision version
- .withTags("acumos", theSolution.getSolutionId()) //can I fit an UUID as tag ??
- .withOperator(ONAP.this.asdcOperator/*theSolution.getOwnerId()*/) //probably won't work, SDC expects an att uuid
- .execute()
- .waitForResult();
- }
- catch(Exception x) {
+ return ONAP.this.asdc.createVF().withCategory("Generic").withSubCategory("Abstract")
+ .withName(theSolution.getName() + "-" + theSolution.getSolutionId()) // sdc names are unique,
+ // acumos ones not so
+ .withDescription(description).withVendorName("AcumosInc").withVendorRelease("1.0") // cannot
+ // update so
+ // .. but
+ // might
+ // want to
+ // fetch the
+ // last
+ // Acumos
+ // revision
+ // version
+ .withTags("acumos", theSolution.getSolutionId()) // can I fit an UUID as tag ??
+ .withOperator(ONAP.this.asdcOperator/* theSolution.getOwnerId() */) // probably won't work, SDC
+ // expects an att uuid
+ .execute().waitForResult();
+ } catch (Exception x) {
logger.warn(EELFLoggerDelegate.debugLogger, "Failed to create ONAP SDC VF", x);
throw x;
}
}
-
+
/**
* There is no such thing as updating an asset in the ASDC REST API, we can only
* update the artifacts ..
*
* @param theAssetInfo
- * Asset info
+ * Asset info
* @param theSolution
- * solution
+ * solution
* @return SDC Asset info
*/
- public JSONObject updateSdcAsset(JSONObject theAssetInfo, MLPSolution theSolution) {
- logger.info(EELFLoggerDelegate.debugLogger, "Updating ONAP SDC VF " + theAssetInfo.optString("uuid") + " for Acumosb solution " + theSolution);
+ public JSONObject updateSdcAsset(JSONObject theAssetInfo, MLPSolution theSolution) {
+ logger.info(EELFLoggerDelegate.debugLogger,
+ "Updating ONAP SDC VF " + theAssetInfo.optString("uuid") + " for Acumosb solution " + theSolution);
return theAssetInfo;
}
public void updateAssetArtifacts(JSONObject theAssetInfo, MLPSolution theSolution) throws Exception {
- //fetch the solution artifacts: for now we'll do this for the latest acumos revision
- FederationClient fedClient =
- clients.getFederationClient(this.peer.getApiUrl());
+ // fetch the solution artifacts: for now we'll do this for the latest acumos
+ // revision
+ FederationClient fedClient = clients.getFederationClient(this.peer.getApiUrl());
List<MLPSolutionRevision> acumosRevisions = null;
try {
- acumosRevisions = (List<MLPSolutionRevision>)
- fedClient.getSolutionRevisions(theSolution.getSolutionId()).getResponseBody();
- }
- catch (Exception x) {
+ acumosRevisions = (List<MLPSolutionRevision>) fedClient
+ .getSolutionRevisions(theSolution.getSolutionId()).getResponseBody();
+ } catch (Exception x) {
logger.warn(EELFLoggerDelegate.errorLogger, "Failed to retrieve acumos revisions: " + x);
throw x;
}
List<MLPArtifact> acumosArtifacts = null;
try {
- acumosArtifacts = (List<MLPArtifact>)
- fedClient.getArtifacts(theSolution.getSolutionId(), acumosRevisions.get(acumosRevisions.size()-1).getRevisionId())
- .getResponseBody();
- }
- catch (Exception x) {
+ acumosArtifacts = (List<MLPArtifact>) fedClient.getArtifacts(theSolution.getSolutionId(),
+ acumosRevisions.get(acumosRevisions.size() - 1).getRevisionId()).getResponseBody();
+ } catch (Exception x) {
logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos artifacts" + x);
throw x;
}
try {
- theAssetInfo = ONAP.this.asdc.getAsset(AssetType.resource, UUID.fromString(theAssetInfo.getString("uuid")), JSONObject.class)
- .waitForResult();
- }
- catch (Exception x) {
- logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve ONAP SDC asset metadata for " + theAssetInfo.getString("uuid") + " : " + x);
+ theAssetInfo = ONAP.this.asdc
+ .getAsset(AssetType.resource, UUID.fromString(theAssetInfo.getString("uuid")), JSONObject.class)
+ .waitForResult();
+ } catch (Exception x) {
+ logger.warn(EELFLoggerDelegate.debugLogger,
+ "Failed to retrieve ONAP SDC asset metadata for " + theAssetInfo.getString("uuid") + " : " + x);
throw x;
}
- JSONArray sdcArtifacts = theAssetInfo.optJSONArray("artifacts");
+ JSONArray sdcArtifacts = theAssetInfo.optJSONArray("artifacts");
if (sdcArtifacts == null)
sdcArtifacts = new JSONArray();
- //all this could be better writen but the 2 sets are expected to be small so we favor readability
+ // all this could be better writen but the 2 sets are expected to be small so we
+ // favor readability
- //acumos artifacts that do not exist locally need to be added
- List<MLPArtifact> newArtifacts = new LinkedList<MLPArtifact>();
- Map<MLPArtifact, JSONObject> updatedArtifacts = new HashMap<MLPArtifact, JSONObject>();
- //List<JSONObject> oldArtifacts = new LinkedList<JSONObject>();
+ // acumos artifacts that do not exist locally need to be added
+ List<MLPArtifact> newArtifacts = new LinkedList<MLPArtifact>();
+ Map<MLPArtifact, JSONObject> updatedArtifacts = new HashMap<MLPArtifact, JSONObject>();
+ // List<JSONObject> oldArtifacts = new LinkedList<JSONObject>();
logger.info(EELFLoggerDelegate.debugLogger, "Acumos artifacts: " + acumosArtifacts);
logger.info(EELFLoggerDelegate.debugLogger, "ONAP SDC artifacts: " + sdcArtifacts);
-
- for (MLPArtifact acumosArtifact: acumosArtifacts) {
+
+ for (MLPArtifact acumosArtifact : acumosArtifacts) {
boolean found = false;
for (int i = 0; !found && i < sdcArtifacts.length(); i++) {
JSONObject sdcArtifact = sdcArtifacts.getJSONObject(i);
String sdcArtifactDescription = sdcArtifact.optString("artifactDescription");
- if (sdcArtifactDescription != null) {
+ if (sdcArtifactDescription != null) {
String[] parts = sdcArtifactDescription.split("@");
if (parts.length == 2) {
if (parts[0].equals(acumosArtifact.getArtifactId())) {
found = true;
- //compare the versions so that we find the
+ // compare the versions so that we find the
if (!parts[1].equals(acumosArtifact.getVersion()))
updatedArtifacts.put(acumosArtifact, sdcArtifact);
}
- }
+ }
}
}
if (!found)
}
logger.warn(EELFLoggerDelegate.debugLogger, "New SDC artifacts: " + newArtifacts);
- for (MLPArtifact acumosArtifact: newArtifacts) {
+ for (MLPArtifact acumosArtifact : newArtifacts) {
try {
byte[] content = IOUtils.toByteArray(new URI(acumosArtifact.getUri()));
if (content == null)
throw new Exception("Unable to fetch artifact content from " + acumosArtifact.getUri());
if (content.length == 0)
- logger.warn(EELFLoggerDelegate.debugLogger, "Acumos artifact has empty content, not acceptable in ONAP SDC");
- //more sophisticated mapping needed here
+ logger.warn(EELFLoggerDelegate.debugLogger,
+ "Acumos artifact has empty content, not acceptable in ONAP SDC");
+ // more sophisticated mapping needed here
asdc.createAssetArtifact(AssetType.resource, UUID.fromString(theAssetInfo.getString("uuid")))
- .withOperator(ONAP.this.asdcOperator)
- .withContent(content)
- .withLabel(acumosArtifact.getArtifactTypeCode())
- .withName(acumosArtifact.getName())
- .withDisplayName(acumosArtifact.getMetadata())
- .withType(ArtifactType.OTHER)
+ .withOperator(ONAP.this.asdcOperator).withContent(content)
+ .withLabel(acumosArtifact.getArtifactTypeCode()).withName(acumosArtifact.getName())
+ .withDisplayName(acumosArtifact.getMetadata()).withType(ArtifactType.OTHER)
.withGroupType(ArtifactGroupType.DEPLOYMENT)
- .withDescription(acumosArtifact.getArtifactId() + "@" + acumosArtifact.getVersion()/*acumosArtifact.getDescription()*/)
- .execute()
- .waitForResult();
- }
- catch(Exception x) {
+ .withDescription(acumosArtifact.getArtifactId() + "@"
+ + acumosArtifact.getVersion()/* acumosArtifact.getDescription() */)
+ .execute().waitForResult();
+ } catch (Exception x) {
logger.warn(EELFLoggerDelegate.debugLogger, "Failed to create ONAP SDC VF Artifact", x);
}
}
-
+
logger.warn(EELFLoggerDelegate.debugLogger, "Updated SDC artifacts: " + updatedArtifacts.keySet());
- for (Map.Entry<MLPArtifact,JSONObject> updateEntry: updatedArtifacts.entrySet()) {
+ for (Map.Entry<MLPArtifact, JSONObject> updateEntry : updatedArtifacts.entrySet()) {
MLPArtifact acumosArtifact = updateEntry.getKey();
try {
byte[] content = IOUtils.toByteArray(new URI(acumosArtifact.getUri()));
if (content == null)
throw new Exception("Unable to fetch artifact content from " + acumosArtifact.getUri());
- //more sophisticated mapping needed here
- asdc.updateAssetArtifact(
- AssetType.resource, UUID.fromString(theAssetInfo.getString("uuid")), updateEntry.getValue())
- .withOperator(ONAP.this.asdcOperator)
- .withContent(content)
- //.withName(acumosArtifact.getName())
- .withDescription(acumosArtifact.getArtifactId() + "@" + acumosArtifact.getVersion()/*acumosArtifact.getDescription()*/)
- .execute()
- .waitForResult();
- }
- catch(Exception x) {
+ // more sophisticated mapping needed here
+ asdc.updateAssetArtifact(AssetType.resource, UUID.fromString(theAssetInfo.getString("uuid")),
+ updateEntry.getValue()).withOperator(ONAP.this.asdcOperator).withContent(content)
+ // .withName(acumosArtifact.getName())
+ .withDescription(acumosArtifact.getArtifactId() + "@"
+ + acumosArtifact.getVersion()/* acumosArtifact.getDescription() */)
+ .execute().waitForResult();
+ } catch (Exception x) {
logger.warn(EELFLoggerDelegate.debugLogger, "Failed to update ONAP SDC VF Artifact", x);
}
}
-
- //sdc artifacts that do not have a acumos counterpart should be deleted (if they are labeled as having
- //originated in acumos).
+
+ // sdc artifacts that do not have a acumos counterpart should be deleted (if
+ // they are labeled as having
+ // originated in acumos).
List<JSONObject> deletedArtifacts = new LinkedList<JSONObject>();
for (int i = 0; i < sdcArtifacts.length(); i++) {
JSONObject sdcArtifact = sdcArtifacts.getJSONObject(i);
boolean found = false;
- for (MLPArtifact acumosArtifact: acumosArtifacts) {
+ for (MLPArtifact acumosArtifact : acumosArtifacts) {
if (same(acumosArtifact, sdcArtifact)) {
found = true;
break;
}
}
logger.warn(EELFLoggerDelegate.debugLogger, "Deleted SDC artifacts: " + deletedArtifacts);
- for (JSONObject sdcArtifact: deletedArtifacts) {
+ for (JSONObject sdcArtifact : deletedArtifacts) {
try {
- asdc.deleteAssetArtifact(
- AssetType.resource,
- UUID.fromString(theAssetInfo.getString("uuid")),
- UUID.fromString(sdcArtifact.getString("artifactUUID")))
- .withOperator(ONAP.this.asdcOperator)
- .execute()
- .waitForResult();
- }
- catch(Exception x) {
+ asdc.deleteAssetArtifact(AssetType.resource, UUID.fromString(theAssetInfo.getString("uuid")),
+ UUID.fromString(sdcArtifact.getString("artifactUUID"))).withOperator(ONAP.this.asdcOperator)
+ .execute().waitForResult();
+ } catch (Exception x) {
logger.warn(EELFLoggerDelegate.debugLogger, "Failed to delete ONAP SDC VF Artifact", x);
}
}
}
-
+
private boolean same(MLPSolution theAcumosSolution, JSONObject theSDCAsset) {
- return theSDCAsset.optString("name", "").equals(
- theAcumosSolution.getName() + "-" + theAcumosSolution.getSolutionId());
+ return theSDCAsset.optString("name", "")
+ .equals(theAcumosSolution.getName() + "-" + theAcumosSolution.getSolutionId());
}
private boolean same(MLPArtifact theAcumosArtifact, JSONObject theSDCArtifact) {
-
+
String sdcArtifactDescription = theSDCArtifact.optString("artifactDescription");
- if (sdcArtifactDescription != null) {
+ if (sdcArtifactDescription != null) {
String[] parts = sdcArtifactDescription.split("@");
if (parts.length == 2) {
if (parts[0].equals(theAcumosArtifact.getArtifactId())) {
return false;
}
- //only safe to call if 'same' returned true
+ // only safe to call if 'same' returned true
/*
- private boolean sameVersion(MLPArtifact theAcumosArtifact, JSONObject theSDCArtifact) {
- return theSDCArtifact.optString("artifactDescription","@").split("@")[1].equals(theAcumosArtifact.getVersion());
- }
- */
+ * private boolean sameVersion(MLPArtifact theAcumosArtifact, JSONObject
+ * theSDCArtifact) { return
+ * theSDCArtifact.optString("artifactDescription","@").split("@")[1].equals(
+ * theAcumosArtifact.getVersion()); }
+ */
private boolean isAcumosOriginated(JSONObject theSDCArtifact) {
- boolean isAcumos = theSDCArtifact.optString("artifactType").equals(ArtifactType.OTHER.toString()) &&
- theSDCArtifact.optString("artifactGroupType").equals(ArtifactGroupType.DEPLOYMENT.toString());
- String[] parts = theSDCArtifact.optString("artifactDescription","@").split("@");
- isAcumos &= (parts.length == 2); //and the first part can be parsed as an UUID
+ boolean isAcumos = theSDCArtifact.optString("artifactType").equals(ArtifactType.OTHER.toString())
+ && theSDCArtifact.optString("artifactGroupType").equals(ArtifactGroupType.DEPLOYMENT.toString());
+ String[] parts = theSDCArtifact.optString("artifactDescription", "@").split("@");
+ isAcumos &= (parts.length == 2); // and the first part can be parsed as an UUID
return isAcumos;
}
}
* Removes all (non-commited) Acumos solutions imported into ONAP SDC
*/
protected void cleanup() {
-
+
JSONArray sdcAssets = null;
try {
- sdcAssets = asdc.getAssets(AssetType.resource, JSONArray.class, "Generic", "Abstract")
- .waitForResult();
- }
- catch (Throwable x) {
+ sdcAssets = asdc.getAssets(AssetType.resource, JSONArray.class, "Generic", "Abstract").waitForResult();
+ } catch (Throwable x) {
logger.info(EELFLoggerDelegate.debugLogger, "Cleanup failed to list ONAP SDC assets: " + x.getCause(), x);
}
String state = sdcAsset.optString("lifecycleState");
if (state != null && "NOT_CERTIFIED_CHECKEOUT".equals(state)) {
try {
- asdc.cycleAsset(AssetType.resource, UUID.fromString(sdcAsset.getString("uuid")), LifecycleState.undocheckout, ONAP.this.asdcOperator, null)
- .waitForResult();
- }
- catch (Exception x) {
- logger.info(EELFLoggerDelegate.debugLogger, "Cleanup ONAP SDC asset: " + sdcAsset.optString("uuid"), x);
+ asdc.cycleAsset(AssetType.resource, UUID.fromString(sdcAsset.getString("uuid")),
+ LifecycleState.undocheckout, ONAP.this.asdcOperator, null).waitForResult();
+ } catch (Exception x) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Cleanup ONAP SDC asset: " + sdcAsset.optString("uuid"),
+ x);
}
}
}
public class ONAPAdapterCondition extends AdapterCondition {
@Override
- public boolean matches(ConditionContext theContext,
- AnnotatedTypeMetadata theMetadata) {
+ public boolean matches(ConditionContext theContext, AnnotatedTypeMetadata theMetadata) {
Environment env = theContext.getEnvironment();
- return super.matches(theContext, theMetadata) &&
- null != env &&
- "ONAP".equals(env.getProperty("federation.instance.name"));
- }
+ return super.matches(theContext, theMetadata) && null != env
+ && "ONAP".equals(env.getProperty("federation.instance.name"));
+ }
}
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
-
-
@Component("asdc")
@Scope("singleton")
-@ConfigurationProperties(prefix="asdc")
+@ConfigurationProperties(prefix = "asdc")
public class ASDC {
-
+
public static enum AssetType {
- resource,
- service,
- product
+ resource, service, product
}
public static enum ArtifactType {
- DCAE_TOSCA,
- DCAE_JSON,
- DCAE_POLICY,
- DCAE_DOC,
- DCAE_EVENT,
- DCAE_INVENTORY_TOSCA,
- DCAE_INVENTORY_JSON,
- DCAE_INVENTORY_POLICY,
- DCAE_INVENTORY_DOC,
- DCAE_INVENTORY_BLUEPRINT,
- DCAE_INVENTORY_EVENT,
- HEAT,
- HEAT_VOL,
- HEAT_NET,
- HEAT_NESTED,
- HEAT_ARTIFACT,
- HEAT_ENV,
- OTHER
+ DCAE_TOSCA, DCAE_JSON, DCAE_POLICY, DCAE_DOC, DCAE_EVENT, DCAE_INVENTORY_TOSCA, DCAE_INVENTORY_JSON, DCAE_INVENTORY_POLICY, DCAE_INVENTORY_DOC, DCAE_INVENTORY_BLUEPRINT, DCAE_INVENTORY_EVENT, HEAT, HEAT_VOL, HEAT_NET, HEAT_NESTED, HEAT_ARTIFACT, HEAT_ENV, OTHER
}
public static enum ArtifactGroupType {
- DEPLOYMENT,
- INFORMATIONAL
+ DEPLOYMENT, INFORMATIONAL
}
public static enum LifecycleState {
- Checkin,
- Checkout,
- Certify,
- undocheckout
+ Checkin, Checkout, Certify, undocheckout
}
-
-// @Retention(RetentionPolicy.RUNTIME)
-// @Target(ElementType.METHOD)
-// public @interface Mandatory {
-// }
+ // @Retention(RetentionPolicy.RUNTIME)
+ // @Target(ElementType.METHOD)
+ // public @interface Mandatory {
+ // }
private Logger log = Logger.getLogger(ASDC.class.getName());
- private URI rootUri;
- private String rootPath = "/asdc/"; //"/sdc1/feproxy/"; //"/sdc/v1/catalog/";
- private String user,
- passwd;
- private String instanceId;
+ private URI rootUri;
+ private String rootPath = "/asdc/"; // "/sdc1/feproxy/"; //"/sdc/v1/catalog/";
+ private String user, passwd;
+ private String instanceId;
public void setUri(URI theUri) {
String userInfo = theUri.getUserInfo();
}
String fragment = theUri.getFragment();
if (fragment == null)
- throw new IllegalArgumentException("The URI must contain a fragment specification, to be used as ASDC instance id");
+ throw new IllegalArgumentException(
+ "The URI must contain a fragment specification, to be used as ASDC instance id");
setInstanceId(fragment);
try {
- this.rootUri = new URI(theUri.getScheme(), null, theUri.getHost(), theUri.getPort(), theUri.getPath(), theUri.getQuery(), null);
- }
- catch (URISyntaxException urix) {
+ this.rootUri = new URI(theUri.getScheme(), null, theUri.getHost(), theUri.getPort(), theUri.getPath(),
+ theUri.getQuery(), null);
+ } catch (URISyntaxException urix) {
throw new IllegalArgumentException("Invalid uri", urix);
}
- }
+ }
public URI getUri() {
- return this.rootUri;
+ return this.rootUri;
}
public void setUser(String theUser) {
public String getInstanceId() {
return this.instanceId;
}
-
+
public void setRootPath(String thePath) {
this.rootPath = thePath;
}
return this.rootPath;
}
- @Scheduled(fixedRateString = "${beans.context.scripts.updateCheckFrequency?:60000}")
- public void checkForUpdates() {
+ @Scheduled(fixedRateString = "${beans.context.scripts.updateCheckFrequency?:60000}")
+ public void checkForUpdates() {
}
@PostConstruct
public <T> Future<T> getResources(Class<T> theType) {
return getAssets(AssetType.resource, theType);
}
-
+
public Future<JSONArray> getResources() {
return getAssets(AssetType.resource, JSONArray.class);
}
-
+
public <T> Future<T> getResources(Class<T> theType, String theCategory, String theSubCategory) {
return getAssets(AssetType.resource, theType, theCategory, theSubCategory);
}
-
+
public Future<JSONArray> getResources(String theCategory, String theSubCategory) {
return getAssets(AssetType.resource, JSONArray.class, theCategory, theSubCategory);
}
public <T> Future<T> getServices(Class<T> theType) {
return getAssets(AssetType.service, theType);
}
-
+
public Future<JSONArray> getServices() {
return getAssets(AssetType.service, JSONArray.class);
}
-
+
public <T> Future<T> getServices(Class<T> theType, String theCategory, String theSubCategory) {
return getAssets(AssetType.service, theType, theCategory, theSubCategory);
}
-
+
public Future<JSONArray> getServices(String theCategory, String theSubCategory) {
return getAssets(AssetType.service, JSONArray.class, theCategory, theSubCategory);
}
public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType) {
return fetch(refAssets(theAssetType), theType);
}
-
+
public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType) {
return (() -> fetch(refAssets(theAssetType), theType));
}
-
- public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType,
- String theCategory, String theSubCategory) {
+
+ public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType, String theCategory,
+ String theSubCategory) {
return getAssets(theAssetType, theType, theCategory, theSubCategory, null);
}
- public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType,
- String theCategory, String theSubCategory, String theResourceType) {
+ public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType, String theCategory, String theSubCategory,
+ String theResourceType) {
return fetch(refAssets(theAssetType) + filter(theCategory, theSubCategory, theResourceType), theType);
}
-
- public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType,
- String theCategory, String theSubCategory, String theResourceType) {
+
+ public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType, String theCategory,
+ String theSubCategory, String theResourceType) {
return (() -> fetch(refAssets(theAssetType) + filter(theCategory, theSubCategory, theResourceType), theType));
}
-
+
protected String refAssets(AssetType theAssetType) {
return this.rootPath + theAssetType + "s/";
}
StringBuilder filter = null;
if (theCategory != null) {
filter = new StringBuilder();
- filter.append("?category=")
- .append(theCategory);
+ filter.append("?category=").append(theCategory);
if (theSubCategory != null) {
- filter.append("&subCategory=")
- .append(theSubCategory);
+ filter.append("&subCategory=").append(theSubCategory);
if (theResourceType != null) {
- filter.append("&resourceType=")
- .append(theResourceType);
+ filter.append("&resourceType=").append(theResourceType);
}
}
}
protected String refAsset(AssetType theAssetType, UUID theId) {
return this.rootPath + theAssetType + "s/" + theId;
}
-
+
public <T> Future<T> getResource(UUID theId, Class<T> theType) {
return getAsset(AssetType.resource, theId, theType);
}
-
+
public Future<JSONObject> getResource(UUID theId) {
return getAsset(AssetType.resource, theId, JSONObject.class);
}
public <T> Future<T> getService(UUID theId, Class<T> theType) {
return getAsset(AssetType.service, theId, theType);
}
-
+
public Future<JSONObject> getService(UUID theId) {
return getAsset(AssetType.service, theId, JSONObject.class);
}
public <T> Future<T> getAsset(AssetType theAssetType, UUID theId, Class<T> theType) {
return fetch(refAsset(theAssetType, theId) + "/metadata", theType);
}
-
+
public <T> Action<T> getAssetAction(AssetType theAssetType, UUID theId, Class<T> theType) {
return (() -> fetch(refAsset(theAssetType, theId) + "/metadata", theType));
}
public Future<JSONObject> checkoutService(UUID theId, String theUser, String theMessage) {
return cycleAsset(AssetType.service, theId, LifecycleState.Checkout, theUser, theMessage);
}
-
+
public Future<JSONObject> certifyResource(UUID theId, String theUser, String theMessage) {
return cycleAsset(AssetType.resource, theId, LifecycleState.Certify, theUser, theMessage);
}
return cycleAsset(AssetType.service, theId, LifecycleState.Certify, theUser, theMessage);
}
- /* Normally theMessage is mandatory (and we'd use put instead of putOpt) but .. not so for undocheckout ..
+ /*
+ * Normally theMessage is mandatory (and we'd use put instead of putOpt) but ..
+ * not so for undocheckout ..
*/
- public Future<JSONObject> cycleAsset(AssetType theAssetType, UUID theId, LifecycleState theState,
- String theUser, String theMessage) {
- return post(refAsset(theAssetType, theId) + "/lifecycleState/" + theState,
- (headers) -> prepareHeaders(headers)
- .header("USER_ID", theUser),
- new JSONObject().putOpt("userRemarks", theMessage));
+ public Future<JSONObject> cycleAsset(AssetType theAssetType, UUID theId, LifecycleState theState, String theUser,
+ String theMessage) {
+ return post(refAsset(theAssetType, theId) + "/lifecycleState/" + theState,
+ (headers) -> prepareHeaders(headers).header("USER_ID", theUser),
+ new JSONObject().putOpt("userRemarks", theMessage));
}
- protected String refAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theAssetInstance, UUID theArtifactId) {
- return refAsset(theAssetType, theAssetId) + "/resourceInstances/" + theAssetInstance + "/artifacts" + (theArtifactId == null ? "" : ("/" + theArtifactId));
+ protected String refAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theAssetInstance,
+ UUID theArtifactId) {
+ return refAsset(theAssetType, theAssetId) + "/resourceInstances/" + theAssetInstance + "/artifacts"
+ + (theArtifactId == null ? "" : ("/" + theArtifactId));
}
protected String refAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId) {
return refAsset(theAssetType, theAssetId) + "/artifacts" + (theArtifactId == null ? "" : ("/" + theArtifactId));
}
-
+
public <T> Future<T> getResourceArtifact(UUID theAssetId, UUID theArtifactId, Class<T> theType) {
return getAssetArtifact(AssetType.resource, theAssetId, theArtifactId, theType);
}
-
+
public <T> Future<T> getServiceArtifact(UUID theAssetId, UUID theArtifactId, Class<T> theType) {
return getAssetArtifact(AssetType.service, theAssetId, theArtifactId, theType);
}
-
- public <T> Future<T> getResourceInstanceArtifact(UUID theAssetId, UUID theArtifactId, String theInstance, Class<T> theType) {
+
+ public <T> Future<T> getResourceInstanceArtifact(UUID theAssetId, UUID theArtifactId, String theInstance,
+ Class<T> theType) {
return getAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance, theArtifactId, theType);
}
-
- public <T> Future<T> getServiceInstanceArtifact(UUID theAssetId, UUID theArtifactId, String theInstance, Class<T> theType) {
+
+ public <T> Future<T> getServiceInstanceArtifact(UUID theAssetId, UUID theArtifactId, String theInstance,
+ Class<T> theType) {
return getAssetInstanceArtifact(AssetType.service, theAssetId, theInstance, theArtifactId, theType);
}
- public <T> Future<T> getAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId, Class<T> theType) {
+ public <T> Future<T> getAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId,
+ Class<T> theType) {
return fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType);
}
-
- public <T> Action<T> getAssetArtifactAction(AssetType theAssetType, UUID theAssetId, UUID theArtifactId, Class<T> theType) {
+
+ public <T> Action<T> getAssetArtifactAction(AssetType theAssetType, UUID theAssetId, UUID theArtifactId,
+ Class<T> theType) {
return (() -> fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType));
}
-
- public <T> Future<T> getAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) {
+
+ public <T> Future<T> getAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance,
+ UUID theArtifactId, Class<T> theType) {
return fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType);
}
-
- public <T> Action<T> getAssetInstanceArtifactAction(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) {
+
+ public <T> Action<T> getAssetInstanceArtifactAction(AssetType theAssetType, UUID theAssetId, String theInstance,
+ UUID theArtifactId, Class<T> theType) {
return (() -> fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType));
}
-
+
public ArtifactUploadAction createResourceArtifact(UUID theAssetId) {
return createAssetArtifact(AssetType.resource, theAssetId);
}
-
+
public ArtifactUploadAction createServiceArtifact(UUID theAssetId) {
return createAssetArtifact(AssetType.service, theAssetId);
}
-
+
public ArtifactUploadAction createResourceInstanceArtifact(UUID theAssetId, String theInstance) {
return createAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance);
}
-
+
public ArtifactUploadAction createServiceInstanceArtifact(UUID theAssetId, String theInstance) {
return createAssetInstanceArtifact(AssetType.service, theAssetId, theInstance);
}
public ArtifactUploadAction createAssetArtifact(AssetType theAssetType, UUID theAssetId) {
- return new ArtifactUploadAction()
- .ofAsset(theAssetType, theAssetId);
+ return new ArtifactUploadAction().ofAsset(theAssetType, theAssetId);
}
-
- public ArtifactUploadAction createAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance) {
- return new ArtifactUploadAction()
- .ofAssetInstance(theAssetType, theAssetId, theInstance);
+
+ public ArtifactUploadAction createAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId,
+ String theInstance) {
+ return new ArtifactUploadAction().ofAssetInstance(theAssetType, theAssetId, theInstance);
}
public ArtifactUpdateAction updateResourceArtifact(UUID theAssetId, JSONObject theArtifactInfo) {
return updateAssetArtifact(AssetType.resource, theAssetId, theArtifactInfo);
}
-
- public ArtifactUpdateAction updateResourceInstanceArtifact(UUID theAssetId, String theInstance, JSONObject theArtifactInfo) {
+
+ public ArtifactUpdateAction updateResourceInstanceArtifact(UUID theAssetId, String theInstance,
+ JSONObject theArtifactInfo) {
return updateAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance, theArtifactInfo);
}
-
+
public ArtifactUpdateAction updateServiceArtifact(UUID theAssetId, JSONObject theArtifactInfo) {
return updateAssetArtifact(AssetType.service, theAssetId, theArtifactInfo);
}
-
- public ArtifactUpdateAction updateServiceInstanceArtifact(UUID theAssetId, String theInstance, JSONObject theArtifactInfo) {
+
+ public ArtifactUpdateAction updateServiceInstanceArtifact(UUID theAssetId, String theInstance,
+ JSONObject theArtifactInfo) {
return updateAssetInstanceArtifact(AssetType.service, theAssetId, theInstance, theArtifactInfo);
}
- public ArtifactUpdateAction updateAssetArtifact(AssetType theAssetType, UUID theAssetId, JSONObject theArtifactInfo) {
- return new ArtifactUpdateAction(theArtifactInfo)
- .ofAsset(theAssetType, theAssetId);
+ public ArtifactUpdateAction updateAssetArtifact(AssetType theAssetType, UUID theAssetId,
+ JSONObject theArtifactInfo) {
+ return new ArtifactUpdateAction(theArtifactInfo).ofAsset(theAssetType, theAssetId);
}
-
- public ArtifactUpdateAction updateAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, JSONObject theArtifactInfo) {
- return new ArtifactUpdateAction(theArtifactInfo)
- .ofAssetInstance(theAssetType, theAssetId, theInstance);
+
+ public ArtifactUpdateAction updateAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance,
+ JSONObject theArtifactInfo) {
+ return new ArtifactUpdateAction(theArtifactInfo).ofAssetInstance(theAssetType, theAssetId, theInstance);
}
public ArtifactDeleteAction deleteResourceArtifact(UUID theAssetId, UUID theArtifactId) {
return deleteAssetArtifact(AssetType.resource, theAssetId, theArtifactId);
}
-
- public ArtifactDeleteAction deleteResourceInstanceArtifact(UUID theAssetId, String theInstance, UUID theArtifactId) {
+
+ public ArtifactDeleteAction deleteResourceInstanceArtifact(UUID theAssetId, String theInstance,
+ UUID theArtifactId) {
return deleteAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance, theArtifactId);
}
-
+
public ArtifactDeleteAction deleteServiceArtifact(UUID theAssetId, UUID theArtifactId) {
return deleteAssetArtifact(AssetType.service, theAssetId, theArtifactId);
}
-
+
public ArtifactDeleteAction deleteServiceInstanceArtifact(UUID theAssetId, String theInstance, UUID theArtifactId) {
return deleteAssetInstanceArtifact(AssetType.service, theAssetId, theInstance, theArtifactId);
}
public ArtifactDeleteAction deleteAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId) {
- return new ArtifactDeleteAction(theArtifactId)
- .ofAsset(theAssetType, theAssetId);
+ return new ArtifactDeleteAction(theArtifactId).ofAsset(theAssetType, theAssetId);
}
-
- public ArtifactDeleteAction deleteAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId) {
- return new ArtifactDeleteAction(theArtifactId)
- .ofAssetInstance(theAssetType, theAssetId, theInstance);
+
+ public ArtifactDeleteAction deleteAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance,
+ UUID theArtifactId) {
+ return new ArtifactDeleteAction(theArtifactId).ofAssetInstance(theAssetType, theAssetId, theInstance);
}
-
- public abstract class ASDCAction<A extends ASDCAction<A, T>, T> implements Action<T> {
+ public abstract class ASDCAction<A extends ASDCAction<A, T>, T> implements Action<T> {
- protected JSONObject info; //info passed to asdc as request body
- protected String operatorId; //uid of the user performing the action: only required in the updatr
+ protected JSONObject info; // info passed to asdc as request body
+ protected String operatorId; // uid of the user performing the action: only required in the updatr
protected ASDCAction(JSONObject theInfo) {
this.info = theInfo;
}
-
- protected abstract A self();
+
+ protected abstract A self();
protected ASDC asdc() {
return ASDC.this;
}
-
+
protected A withInfo(JSONObject theInfo) {
merge(this.info, theInfo);
return self();
}
-
+
public A with(String theProperty, Object theValue) {
info.put(theProperty, theValue);
return self();
public A withOperator(String theOperator) {
this.operatorId = theOperator;
- return self();
+ return self();
}
-
+
protected abstract String[] mandatoryInfoEntries();
-
+
protected void checkOperatorId() {
if (this.operatorId == null) {
throw new IllegalStateException("No operator id was provided");
}
protected void checkMandatoryInfo() {
- for (String field: mandatoryInfoEntries()) {
- if (!info.has(field))
+ for (String field : mandatoryInfoEntries()) {
+ if (!info.has(field))
throw new IllegalStateException("No '" + field + "' was provided");
}
}
-
+
protected void checkMandatory() {
checkOperatorId();
checkMandatoryInfo();
protected static final String[] artifactMandatoryEntries = new String[] {};
/**
- * We use teh same API to operate on artifacts attached to assets or to their instances
+ * We use teh same API to operate on artifacts attached to assets or to their
+ * instances
*/
public abstract class ASDCArtifactAction<A extends ASDCArtifactAction<A>> extends ASDCAction<A, JSONObject> {
- protected AssetType assetType;
- protected UUID assetId;
- protected String assetInstance;
+ protected AssetType assetType;
+ protected UUID assetId;
+ protected String assetInstance;
protected ASDCArtifactAction(JSONObject theInfo) {
super(theInfo);
}
-
+
protected A ofAsset(AssetType theAssetType, UUID theAssetId) {
this.assetType = theAssetType;
this.assetId = theAssetId;
- return self();
+ return self();
}
-
+
protected A ofAssetInstance(AssetType theAssetType, UUID theAssetId, String theInstance) {
this.assetType = theAssetType;
this.assetId = theAssetId;
this.assetInstance = theInstance;
- return self();
+ return self();
}
-
+
protected String normalizeInstanceName(String theName) {
return StringUtils.removePattern(theName, "[ \\.\\-]+").toLowerCase();
}
-
+
protected String[] mandatoryInfoEntries() {
return ASDC.this.artifactMandatoryEntries;
}
protected String ref(UUID theArtifactId) {
- return (this.assetInstance == null) ?
- refAssetArtifact(this.assetType, this.assetId, theArtifactId) :
- refAssetInstanceArtifact(this.assetType, this.assetId, normalizeInstanceName(this.assetInstance), theArtifactId);
+ return (this.assetInstance == null) ? refAssetArtifact(this.assetType, this.assetId, theArtifactId)
+ : refAssetInstanceArtifact(this.assetType, this.assetId, normalizeInstanceName(this.assetInstance),
+ theArtifactId);
}
- }
+ }
- protected static final String[] uploadMandatoryEntries = new String[] { "artifactName",
- "artifactType",
- "artifactGroupType",
- "artifactLabel",
- "description",
- "payloadData" };
+ protected static final String[] uploadMandatoryEntries = new String[] { "artifactName", "artifactType",
+ "artifactGroupType", "artifactLabel", "description", "payloadData" };
public class ArtifactUploadAction extends ASDCArtifactAction<ArtifactUploadAction> {
-
+
protected ArtifactUploadAction() {
super(new JSONObject());
}
protected ArtifactUploadAction self() {
return this;
}
-
+
public ArtifactUploadAction withContent(byte[] theContent) {
return with("payloadData", Base64Utils.encodeToString(theContent));
}
public ArtifactUploadAction withLabel(String theLabel) {
return with("artifactLabel", theLabel);
}
-
+
public ArtifactUploadAction withName(String theName) {
return with("artifactName", theName);
}
-
+
public ArtifactUploadAction withDisplayName(String theName) {
return with("artifactDisplayName", theName);
}
public ArtifactUploadAction withDescription(String theDescription) {
return with("description", theDescription);
}
-
+
protected String[] mandatoryInfoEntries() {
return ASDC.this.uploadMandatoryEntries;
}
public Future<JSONObject> execute() {
checkMandatory();
- return ASDC.this.post(ref(null),
- (headers) -> prepareHeaders(headers)
- .header("USER_ID", this.operatorId),
- this.info);
+ return ASDC.this.post(ref(null), (headers) -> prepareHeaders(headers).header("USER_ID", this.operatorId),
+ this.info);
}
}
- protected static final String[] updateMandatoryEntries = new String[] { "artifactName",
- "artifactType",
- "artifactGroupType",
- "artifactLabel",
- "description",
- "payloadData" };
+ protected static final String[] updateMandatoryEntries = new String[] { "artifactName", "artifactType",
+ "artifactGroupType", "artifactLabel", "description", "payloadData" };
/**
- * In its current form the update relies on a previous artifact retrieval. One cannot build an update from scratch.
- * The label, tye and group type must be submitted but cannot be updated
+ * In its current form the update relies on a previous artifact retrieval. One
+ * cannot build an update from scratch. The label, tye and group type must be
+ * submitted but cannot be updated
*/
public class ArtifactUpdateAction extends ASDCArtifactAction<ArtifactUpdateAction> {
-
protected ArtifactUpdateAction(JSONObject theInfo) {
super(theInfo);
}
-
+
protected ArtifactUpdateAction self() {
return this;
}
-
+
public ArtifactUpdateAction withContent(byte[] theContent) {
return with("payloadData", Base64Utils.encodeToString(theContent));
}
public ArtifactUpdateAction withDescription(String theDescription) {
return with("description", theDescription);
}
-
+
public ArtifactUpdateAction withName(String theName) {
return with("artifactName", theName);
}
-
+
protected String[] mandatoryInfoEntries() {
return ASDC.this.updateMandatoryEntries;
}
- /* The json object originates (normally) from a get so it will have entries we need to cleanup */
+ /*
+ * The json object originates (normally) from a get so it will have entries we
+ * need to cleanup
+ */
protected void cleanupInfoEntries() {
this.info.remove("artifactChecksum");
this.info.remove("artifactUUID");
this.info.remove("artifactURL");
this.info.remove("artifactDescription");
}
-
+
public Future<JSONObject> execute() {
UUID artifactUUID = UUID.fromString(this.info.getString("artifactUUID"));
checkMandatory();
cleanupInfoEntries();
return ASDC.this.post(ref(artifactUUID),
- (headers) -> prepareHeaders(headers)
- .header("USER_ID", this.operatorId),
- this.info);
+ (headers) -> prepareHeaders(headers).header("USER_ID", this.operatorId), this.info);
}
}
public class ArtifactDeleteAction extends ASDCArtifactAction<ArtifactDeleteAction> {
- private UUID artifactId;
-
+ private UUID artifactId;
+
protected ArtifactDeleteAction(UUID theArtifactId) {
super(null);
this.artifactId = theArtifactId;
}
-
+
protected ArtifactDeleteAction self() {
return this;
}
-
+
public Future<JSONObject> execute() {
checkMandatory();
return ASDC.this.delete(ref(this.artifactId),
- (headers) -> prepareHeaders(headers)
- .header("USER_ID", this.operatorId));
+ (headers) -> prepareHeaders(headers).header("USER_ID", this.operatorId));
}
}
-
-
-
public VFCMTCreateAction createVFCMT() {
return new VFCMTCreateAction();
}
-
- protected static final String[] vfcmtMandatoryEntries = new String[] { "name",
- "vendorName",
- "vendorRelease",
- "contactId" };
+ protected static final String[] vfcmtMandatoryEntries = new String[] { "name", "vendorName", "vendorRelease",
+ "contactId" };
public class VFCMTCreateAction extends ASDCAction<VFCMTCreateAction, JSONObject> {
protected VFCMTCreateAction() {
super(new JSONObject());
- this
- .with("resourceType", "VFCMT")
- .with("category", "Template")
- .with("subcategory", "Monitoring Template")
- .with("icon", "defaulticon");
+ this.with("resourceType", "VFCMT").with("category", "Template").with("subcategory", "Monitoring Template")
+ .with("icon", "defaulticon");
}
-
+
protected VFCMTCreateAction self() {
return this;
}
public VFCMTCreateAction withDescription(String theDescription) {
return with("description", theDescription);
}
-
+
public VFCMTCreateAction withVendorName(String theVendorName) {
return with("vendorName", theVendorName);
}
-
+
public VFCMTCreateAction withVendorRelease(String theVendorRelease) {
return with("vendorRelease", theVendorRelease);
}
-
+
public VFCMTCreateAction withTags(String... theTags) {
- for (String tag: theTags)
+ for (String tag : theTags)
this.info.append("tags", tag);
- return this;
+ return this;
}
-
+
public VFCMTCreateAction withIcon(String theIcon) {
return with("icon", theIcon);
}
-
+
protected String[] mandatoryInfoEntries() {
return ASDC.this.vfcmtMandatoryEntries;
}
-
+
public VFCMTCreateAction withContact(String theContact) {
return with("contactId", theContact);
}
-
+
public Future<JSONObject> execute() {
-
- this.info.putOnce("contactId", this.operatorId);
+
+ this.info.putOnce("contactId", this.operatorId);
this.info.append("tags", info.optString("name"));
checkMandatory();
return ASDC.this.post(refAssets(AssetType.resource),
- (headers) -> prepareHeaders(headers)
- .header("USER_ID", this.operatorId),
- this.info);
+ (headers) -> prepareHeaders(headers).header("USER_ID", this.operatorId), this.info);
}
}
-
public VFCreateAction createVF() {
return new VFCreateAction();
}
-
- protected static final String[] vfMandatoryEntries = new String[] {"category",
- "subcategory",
- "name",
- "vendorName",
- "vendorRelease",
- "contactId" };
-
+ protected static final String[] vfMandatoryEntries = new String[] { "category", "subcategory", "name", "vendorName",
+ "vendorRelease", "contactId" };
public class VFCreateAction extends ASDCAction<VFCreateAction, JSONObject> {
protected VFCreateAction() {
super(new JSONObject());
- this
- .with("resourceType", "VF")
- .with("icon", "defaulticon");
+ this.with("resourceType", "VF").with("icon", "defaulticon");
}
-
+
protected VFCreateAction self() {
return this;
}
public VFCreateAction withDescription(String theDescription) {
return with("description", theDescription);
}
-
+
public VFCreateAction withVendorName(String theVendorName) {
return with("vendorName", theVendorName);
}
-
+
public VFCreateAction withVendorRelease(String theVendorRelease) {
return with("vendorRelease", theVendorRelease);
}
-
+
public VFCreateAction withTags(String... theTags) {
- for (String tag: theTags)
+ for (String tag : theTags)
this.info.append("tags", tag);
- return this;
+ return this;
}
-
+
public VFCreateAction withIcon(String theIcon) {
return with("icon", theIcon);
}
-
+
protected String[] mandatoryInfoEntries() {
return ASDC.this.vfMandatoryEntries;
}
-
+
public VFCreateAction withContact(String theContact) {
return with("contactId", theContact);
}
-
+
public Future<JSONObject> execute() {
-
- this.info.putOnce("contactId", this.operatorId);
+
+ this.info.putOnce("contactId", this.operatorId);
this.info.append("tags", info.optString("name"));
checkMandatory();
return ASDC.this.post(refAssets(AssetType.resource),
- (headers) -> prepareHeaders(headers)
- .header("USER_ID", this.operatorId),
- this.info);
+ (headers) -> prepareHeaders(headers).header("USER_ID", this.operatorId), this.info);
}
}
-
public static JSONObject merge(JSONObject theOriginal, JSONObject thePatch) {
- for (String key: thePatch.keySet()) {
+ for (String key : thePatch.keySet()) {
if (!theOriginal.has(key))
theOriginal.put(key, thePatch.get(key));
}
protected URI refUri(String theRef) {
try {
return new URI(this.rootUri + theRef);
- }
- catch(URISyntaxException urisx) {
+ } catch (URISyntaxException urisx) {
throw new UncheckedIOException(new IOException(urisx));
}
}
private HttpHeaders prepareHeaders() {
HttpHeaders headers = new HttpHeaders();
- headers.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((this.user + ":" + this.passwd).getBytes()));
+ headers.add(HttpHeaders.AUTHORIZATION,
+ "Basic " + Base64Utils.encodeToString((this.user + ":" + this.passwd).getBytes()));
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE);
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
private RequestEntity.HeadersBuilder prepareHeaders(RequestEntity.HeadersBuilder theBuilder) {
return theBuilder
- .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((this.user + ":" + this.passwd).getBytes()))
- .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
- .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE)
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
- .header("X-ECOMP-InstanceID", this.instanceId);
+ .header(HttpHeaders.AUTHORIZATION,
+ "Basic " + Base64Utils.encodeToString((this.user + ":" + this.passwd).getBytes()))
+ .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
+ .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE)
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
+ .header("X-ECOMP-InstanceID", this.instanceId);
}
public <T> Future<T> fetch(String theRef, Class<T> theContentType) {
}
public Future<JSONObject> post(String theRef, JSONObject thePost) {
- return exchange(theRef, HttpMethod.POST, new HttpEntity<JSONObject>(thePost, prepareHeaders()), JSONObject.class);
+ return exchange(theRef, HttpMethod.POST, new HttpEntity<JSONObject>(thePost, prepareHeaders()),
+ JSONObject.class);
}
-
- public Future<JSONObject> post(String theRef, UnaryOperator<RequestEntity.HeadersBuilder> theHeadersBuilder, JSONObject thePost) {
+
+ public Future<JSONObject> post(String theRef, UnaryOperator<RequestEntity.HeadersBuilder> theHeadersBuilder,
+ JSONObject thePost) {
RequestEntity.BodyBuilder builder = RequestEntity.post(refUri(theRef));
theHeadersBuilder.apply(builder);
return exchange(theRef, HttpMethod.POST, builder.body(thePost), JSONObject.class);
}
-
+
public Future<JSONObject> delete(String theRef, UnaryOperator<RequestEntity.HeadersBuilder> theHeadersBuilder) {
RequestEntity.HeadersBuilder builder = RequestEntity.delete(refUri(theRef));
return exchange(theRef, HttpMethod.DELETE, builder.build(), JSONObject.class);
}
-
- public <T> Future<T> exchange(String theRef, HttpMethod theMethod, HttpEntity theRequest, Class<T> theResponseType) {
-
+
+ public <T> Future<T> exchange(String theRef, HttpMethod theMethod, HttpEntity theRequest,
+ Class<T> theResponseType) {
+
AsyncRestTemplate restTemplate = new AsyncRestTemplate();
List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
restTemplate.setMessageConverters(converters);
restTemplate.setInterceptors(Collections.singletonList(new ContentMD5Interceptor()));
-/*
- restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
- public boolean hasError(ClientHttpResponse theResponse) throws IOException {
- if (404 == theResponse.getRawStatusCode()) {
- System.out.println("Found a 404 !");
- return false;
- }
- return super.hasError(theResponse);
- }
-
- protected byte[] getResponseBody(ClientHttpResponse theResponse) {
- if (404 == theResponse.getRawStatusCode()) {
- return "[]".getBytes();
- }
- return super.getResponseBody(theResponse);
- }
- });
-*/
- //ResponseEntity<T> response = null;
+ /*
+ * restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { public
+ * boolean hasError(ClientHttpResponse theResponse) throws IOException { if (404
+ * == theResponse.getRawStatusCode()) { System.out.println("Found a 404 !");
+ * return false; } return super.hasError(theResponse); }
+ *
+ * protected byte[] getResponseBody(ClientHttpResponse theResponse) { if (404 ==
+ * theResponse.getRawStatusCode()) { return "[]".getBytes(); } return
+ * super.getResponseBody(theResponse); } });
+ */
+ // ResponseEntity<T> response = null;
ASDCFuture<T> result = new ASDCFuture<T>();
String uri = this.rootUri + theRef;
try {
- restTemplate
- .exchange(uri, theMethod, theRequest, theResponseType)
- .addCallback(result.callback);
- }
- catch (RestClientException rcx) {
+ restTemplate.exchange(uri, theMethod, theRequest, theResponseType).addCallback(result.callback);
+ } catch (RestClientException rcx) {
log.log(Level.WARNING, "Failed to fetch " + uri, rcx);
return Futures.failedFuture(rcx);
- }
- catch (Exception x) {
+ } catch (Exception x) {
log.log(Level.WARNING, "Failed to fetch " + uri, x);
return Futures.failedFuture(x);
}
-
+
return result;
}
-
-
- public class ASDCFuture<T>
- extends Futures.BasicFuture<T> {
+ public class ASDCFuture<T> extends Futures.BasicFuture<T> {
private boolean http404toEmpty = false;
ListenableFutureCallback<ResponseEntity<T>> callback = new ListenableFutureCallback<ResponseEntity<T>>() {
- public void onSuccess(ResponseEntity<T> theResult) {
+ public void onSuccess(ResponseEntity<T> theResult) {
ASDCFuture.this.result(theResult.getBody());
}
- public void onFailure(Throwable theError) {
+ public void onFailure(Throwable theError) {
if (theError instanceof HttpClientErrorException) {
- // if (theError.getRawStatusCode() == 404 && this.http404toEmpty)
- // ASDCFuture.this.result(); //th eresult is of type T ...
- // else
- ASDCFuture.this.cause(new ASDCException((HttpClientErrorException)theError));
- }
- else {
+ // if (theError.getRawStatusCode() == 404 && this.http404toEmpty)
+ // ASDCFuture.this.result(); //th eresult is of type T ...
+ // else
+ ASDCFuture.this.cause(new ASDCException((HttpClientErrorException) theError));
+ } else {
ASDCFuture.this.cause(theError);
}
}
public class ContentMD5Interceptor implements AsyncClientHttpRequestInterceptor {
- @Override
- public ListenableFuture<ClientHttpResponse> intercept(
- HttpRequest theRequest, byte[] theBody, AsyncClientHttpRequestExecution theExecution)
- throws IOException {
- if (HttpMethod.POST == theRequest.getMethod()) {
- HttpHeaders headers = theRequest.getHeaders();
- headers.add("Content-MD5", Base64Utils.encodeToString(
- //DigestUtils.md5Digest(theBody)));
- DigestUtils.md5Hex(theBody).getBytes()));
-
- }
- return theExecution.executeAsync(theRequest, theBody);
- }
+ @Override
+ public ListenableFuture<ClientHttpResponse> intercept(HttpRequest theRequest, byte[] theBody,
+ AsyncClientHttpRequestExecution theExecution) throws IOException {
+ if (HttpMethod.POST == theRequest.getMethod()) {
+ HttpHeaders headers = theRequest.getHeaders();
+ headers.add("Content-MD5", Base64Utils.encodeToString(
+ // DigestUtils.md5Digest(theBody)));
+ DigestUtils.md5Hex(theBody).getBytes()));
+
+ }
+ return theExecution.executeAsync(theRequest, theBody);
+ }
}
-}
+}
String body = theError.getResponseBodyAsString();
if (body != null) {
- JSONObject error = new JSONObject(body)
- .getJSONObject("requestError");
+ JSONObject error = new JSONObject(body).getJSONObject("requestError");
if (error != null) {
- this.content = Arrays.stream(ERROR_CLASSES)
- .map(c -> error.optJSONObject(c))
- .filter(x -> x != null)
- .findFirst()
- .orElse(null);
+ this.content = Arrays.stream(ERROR_CLASSES).map(c -> error.optJSONObject(c)).filter(x -> x != null)
+ .findFirst().orElse(null);
}
}
}
JSONArray vars = content.optJSONArray("variables");
if (vars != null) {
for (int i = 0; i < vars.length(); i++) {
- msg = msg.replaceAll("%"+(i+1), vars.optString(i));
+ msg = msg.replaceAll("%" + (i + 1), vars.optString(i));
}
}
return msg;
- }
- else
+ } else
return "";
}
public class AdapterCondition implements Condition {
@Override
- public boolean matches(ConditionContext theContext,
- AnnotatedTypeMetadata theMetadata) {
+ public boolean matches(ConditionContext theContext, AnnotatedTypeMetadata theMetadata) {
Environment env = theContext.getEnvironment();
- return null != env &&
- "adapter".equals(env.getProperty("federation.instance"));
- }
+ return null != env && "adapter".equals(env.getProperty("federation.instance"));
+ }
}
import org.acumos.federation.gateway.config.EELFLoggerDelegate;
@Configuration
-//@PropertySource("classpath:configprops.properties")
+// @PropertySource("classpath:configprops.properties")
@ConfigurationProperties(prefix = "client")
public class FederationClientConfiguration extends HttpClientConfiguration {
-
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public HttpClient federationClient() {
return buildClient();
}
}
-
public class GatewayCondition implements Condition {
@Override
- public boolean matches(ConditionContext theContext,
- AnnotatedTypeMetadata theMetadata) {
+ public boolean matches(ConditionContext theContext, AnnotatedTypeMetadata theMetadata) {
Environment env = theContext.getEnvironment();
- return null != env && "gateway".equals(env.getProperty("federation.instance"));
- }
+ return null != env && "gateway".equals(env.getProperty("federation.instance"));
+ }
}
package org.acumos.federation.gateway.common;
-
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
-@EnableConfigurationProperties({FederationClientConfiguration.class})
+@EnableConfigurationProperties({ FederationClientConfiguration.class })
public class GatewayConfiguration {
}
-
package org.acumos.federation.gateway.common;
-
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.env.Environment;
public class GhostAdapterCondition extends AdapterCondition {
@Override
- public boolean matches(ConditionContext theContext,
- AnnotatedTypeMetadata theMetadata) {
+ public boolean matches(ConditionContext theContext, AnnotatedTypeMetadata theMetadata) {
Environment env = theContext.getEnvironment();
- return super.matches(theContext, theMetadata) &&
- null != env &&
- "ghost".equals(env.getProperty("federation.instance.name"));
- }
+ return super.matches(theContext, theMetadata) && null != env
+ && "ghost".equals(env.getProperty("federation.instance.name"));
+ }
}
-
package org.acumos.federation.gateway.common;
-
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
//import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLContextBuilder;
-
+
import org.acumos.federation.gateway.config.EELFLoggerDelegate;
@Configuration
-//@PropertySource("classpath:configprops.properties")
+// @PropertySource("classpath:configprops.properties")
@ConfigurationProperties(prefix = "client")
public class HttpClientConfiguration {
@Autowired
private ResourceLoader resourceLoader;
-
- protected final EELFLoggerDelegate log =
- EELFLoggerDelegate.getLogger(getClass().getName());
+
+ protected final EELFLoggerDelegate log = EELFLoggerDelegate.getLogger(getClass().getName());
private String username;
private String passwd;
- private int poolSize = 10;
- private SSL ssl;
-
- public String getUsername() { return this.username; }
- public void setUsername(String theUsername)
- { this.username = theUsername; }
-
- public String getPassword() { return this.username; }
- public void setPassword(String thePassword)
- { this.passwd = thePassword; }
-
- public int getPoolSize() { return this.poolSize; }
- public void setPoolSize(int thePoolSize)
- { this.poolSize = thePoolSize; }
-
- public SSL getSSL() { return this.ssl; }
- public void setSSL(SSL theSSL)
- { this.ssl = theSSL; }
+ private int poolSize = 10;
+ private SSL ssl;
+
+ public String getUsername() {
+ return this.username;
+ }
+
+ public void setUsername(String theUsername) {
+ this.username = theUsername;
+ }
+
+ public String getPassword() {
+ return this.username;
+ }
+
+ public void setPassword(String thePassword) {
+ this.passwd = thePassword;
+ }
+
+ public int getPoolSize() {
+ return this.poolSize;
+ }
+
+ public void setPoolSize(int thePoolSize) {
+ this.poolSize = thePoolSize;
+ }
+
+ public SSL getSSL() {
+ return this.ssl;
+ }
+
+ public void setSSL(SSL theSSL) {
+ this.ssl = theSSL;
+ }
public static class SSL {
- private String keyStore;
- private String keyStoreType = "JKS";
- private String keyStorePasswd;
- private String keyAlias;
- private String trustStore;
- private String trustStoreType = "JKS";
- private String trustStorePasswd;
-
- public String getKeyStore() { return this.keyStore; }
- public void setKeyStore(String theKeyStore)
- { this.keyStore = theKeyStore; }
-
- public String getKeyStoreType() { return this.keyStoreType; }
- public void setKeyStoreType(String theKeyStoreType)
- { this.keyStoreType = theKeyStoreType; }
-
- public String getKeyStorePassword() { return this.keyStorePasswd; }
- public void setKeyStorePassword(String theKeyStorePassword)
- { this.keyStorePasswd = theKeyStorePassword; }
-
- public String getKeyAlias() { return this.keyAlias; }
- public void setKeyAlias(String theKeyAlias)
- { this.keyAlias = theKeyAlias; }
-
- public String getTrustStore() { return this.trustStore; }
- public void setTrustStore(String theTrustStore)
- { this.trustStore = theTrustStore; }
-
- public String getTrustStoreType() { return this.trustStoreType; }
- public void setTrustStoreType(String theTrustStoreType)
- { this.trustStoreType = theTrustStoreType; }
-
- public String getTrustStorePassword() { return this.trustStorePasswd; }
- public void setTrustStorePassword(String theTrustStorePassword)
- { this.trustStorePasswd = theTrustStorePassword; }
+ private String keyStore;
+ private String keyStoreType = "JKS";
+ private String keyStorePasswd;
+ private String keyAlias;
+ private String trustStore;
+ private String trustStoreType = "JKS";
+ private String trustStorePasswd;
+
+ public String getKeyStore() {
+ return this.keyStore;
+ }
+
+ public void setKeyStore(String theKeyStore) {
+ this.keyStore = theKeyStore;
+ }
+
+ public String getKeyStoreType() {
+ return this.keyStoreType;
+ }
+
+ public void setKeyStoreType(String theKeyStoreType) {
+ this.keyStoreType = theKeyStoreType;
+ }
+
+ public String getKeyStorePassword() {
+ return this.keyStorePasswd;
+ }
+
+ public void setKeyStorePassword(String theKeyStorePassword) {
+ this.keyStorePasswd = theKeyStorePassword;
+ }
+
+ public String getKeyAlias() {
+ return this.keyAlias;
+ }
+
+ public void setKeyAlias(String theKeyAlias) {
+ this.keyAlias = theKeyAlias;
+ }
+
+ public String getTrustStore() {
+ return this.trustStore;
+ }
+
+ public void setTrustStore(String theTrustStore) {
+ this.trustStore = theTrustStore;
+ }
+
+ public String getTrustStoreType() {
+ return this.trustStoreType;
+ }
+
+ public void setTrustStoreType(String theTrustStoreType) {
+ this.trustStoreType = theTrustStoreType;
+ }
+
+ public String getTrustStorePassword() {
+ return this.trustStorePasswd;
+ }
+
+ public void setTrustStorePassword(String theTrustStorePassword) {
+ this.trustStorePasswd = theTrustStorePassword;
+ }
protected boolean hasKeyStoreInfo() {
- return this.keyStore != null &&
- this.keyStoreType != null &&
- this.keyStorePasswd != null;
+ return this.keyStore != null && this.keyStoreType != null && this.keyStorePasswd != null;
}
protected boolean hasTrustStoreInfo() {
- return this.trustStore != null &&
- this.trustStoreType != null /*&&
- this.trustStorePasswd != null*/;
+ return this.trustStore != null && this.trustStoreType != null /*
+ * && this.trustStorePasswd != null
+ */;
}
public String toString() {
- return new StringBuilder("")
- .append("SSL(")
- .append(this.keyStore)
- .append(",")
- .append(this.keyStoreType)
- .append(",")
- .append(this.keyAlias)
- .append("/")
- .append(this.trustStore)
- .append(",")
- .append(this.trustStoreType)
- .append(")")
- .toString();
+ return new StringBuilder("").append("SSL(").append(this.keyStore).append(",").append(this.keyStoreType)
+ .append(",").append(this.keyAlias).append("/").append(this.trustStore).append(",")
+ .append(this.trustStoreType).append(")").toString();
}
}
public String toString() {
- return new StringBuilder("")
- .append("ClientConfiguration(")
- .append(this.ssl)
- .append(")")
- .toString();
+ return new StringBuilder("").append("ClientConfiguration(").append(this.ssl).append(")").toString();
}
- public HttpClient buildClient() {
+ public HttpClient buildClient() {
SSLContext sslContext = null;
log.info(EELFLoggerDelegate.debugLogger, "Build HttpClient with " + this);
if (this.ssl == null) {
log.info(EELFLoggerDelegate.debugLogger, "No ssl config was provided");
- }
- else {
+ } else {
KeyStore keyStore = null;
if (this.ssl.hasKeyStoreInfo()) {
try {
keyStore = KeyStore.getInstance(this.ssl.keyStoreType);
- keyStore.load(this.resourceLoader.getResource(this.ssl.keyStore)
- .getURL().openStream(),
- //new URI(this.ssl.keyStore).toURL().openStream(),
- this.ssl.keyStorePasswd.toCharArray());
+ keyStore.load(this.resourceLoader.getResource(this.ssl.keyStore).getURL().openStream(),
+ // new URI(this.ssl.keyStore).toURL().openStream(),
+ this.ssl.keyStorePasswd.toCharArray());
log.info(EELFLoggerDelegate.debugLogger, "Loaded key store: " + this.ssl.keyStore);
- }
- catch (Exception x) {
- throw new IllegalStateException(
- "Error loading key material: " + x, x);
+ } catch (Exception x) {
+ throw new IllegalStateException("Error loading key material: " + x, x);
}
}
if (this.ssl.hasTrustStoreInfo()) {
try {
trustStore = KeyStore.getInstance(this.ssl.trustStoreType);
- trustStore.load(this.resourceLoader.getResource(this.ssl.trustStore)
- .getURL().openStream(),
- //new URI(this.ssl.trustStore).toURL().openStream(),
- this.ssl.trustStorePasswd.toCharArray());
+ trustStore.load(this.resourceLoader.getResource(this.ssl.trustStore).getURL().openStream(),
+ // new URI(this.ssl.trustStore).toURL().openStream(),
+ this.ssl.trustStorePasswd.toCharArray());
log.info(EELFLoggerDelegate.debugLogger, "Loaded trust store: " + this.ssl.trustStore);
- }
- catch (Exception x) {
- throw new IllegalStateException(
- "Error loading trust material: " + x, x);
+ } catch (Exception x) {
+ throw new IllegalStateException("Error loading trust material: " + x, x);
}
}
SSLContextBuilder contextBuilder = SSLContexts.custom();
try {
if (keyStore != null) {
- contextBuilder.loadKeyMaterial(
- keyStore,
- this.ssl.keyStorePasswd.toCharArray()/*,
- (aliases, socket) -> {
-
- return this.ssl.keyAlias;
- }*/);
+ contextBuilder.loadKeyMaterial(keyStore,
+ this.ssl.keyStorePasswd.toCharArray()/*
+ * , (aliases, socket) -> {
+ *
+ * return this.ssl.keyAlias; }
+ */);
}
- if (trustStore != null) {
- contextBuilder.loadTrustMaterial(
- trustStore,
- (x509Certificates, s) -> false);
+ if (trustStore != null) {
+ contextBuilder.loadTrustMaterial(trustStore, (x509Certificates, s) -> false);
}
sslContext = contextBuilder.build();
- }
- catch (Exception x) {
- throw new IllegalStateException(
- "Error building ssl context", x);
+ } catch (Exception x) {
+ throw new IllegalStateException("Error building ssl context", x);
}
}
-//!!TODO: teh default hostname verifier needs to be changed!!
-
- SSLConnectionSocketFactory sslSocketFactory = null;
+ // !!TODO: teh default hostname verifier needs to be changed!!
+
+ SSLConnectionSocketFactory sslSocketFactory = null;
if (sslContext != null) {
- sslSocketFactory =
- new SSLConnectionSocketFactory(
- sslContext,
- new String[] { "TLSv1.2" },
- null,
- SSLConnectionSocketFactory.getDefaultHostnameVerifier());
- log.info(EELFLoggerDelegate.debugLogger, "SSL connection factory configured");
+ sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null,
+ SSLConnectionSocketFactory.getDefaultHostnameVerifier());
+ log.info(EELFLoggerDelegate.debugLogger, "SSL connection factory configured");
}
- RegistryBuilder<ConnectionSocketFactory> registryBuilder =
- RegistryBuilder.<ConnectionSocketFactory>create();
+ RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
if (sslSocketFactory != null) {
registryBuilder.register("https", sslSocketFactory);
Registry<ConnectionSocketFactory> registry = registryBuilder.build();
/*
- PoolingHttpClientConnectionManager connectionManager =
- new PoolingHttpClientConnectionManager(registry);
- connectionManager.setMaxTotal(this.poolSize);
- connectionManager.setDefaultMaxPerRoute(this.poolSize);
- */
+ * PoolingHttpClientConnectionManager connectionManager = new
+ * PoolingHttpClientConnectionManager(registry);
+ * connectionManager.setMaxTotal(this.poolSize);
+ * connectionManager.setDefaultMaxPerRoute(this.poolSize);
+ */
CredentialsProvider credsProvider = null;
- if (this.username != null && this.passwd != null) {
+ if (this.username != null && this.passwd != null) {
credsProvider = new BasicCredentialsProvider();
- credsProvider.setCredentials(
- AuthScope.ANY, new UsernamePasswordCredentials(
- this.username, this.passwd));
+ credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(this.username, this.passwd));
log.info(EELFLoggerDelegate.debugLogger, "Credentials configured");
- }
- else {
+ } else {
log.info(EELFLoggerDelegate.debugLogger, "No credentials were provided");
}
HttpClientBuilder clientBuilder = HttpClients.custom();
- //clientBuilder.setConnectionManager(connectionManager);
+ // clientBuilder.setConnectionManager(connectionManager);
clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
if (sslSocketFactory != null)
- clientBuilder.setSSLSocketFactory(sslSocketFactory);
+ clientBuilder.setSSLSocketFactory(sslSocketFactory);
if (credsProvider != null)
clientBuilder.setDefaultCredentialsProvider(credsProvider);
return clientBuilder.build();
- }
+ }
}
-
package org.acumos.federation.gateway.common;
-
-
public class HttpClientConfigurationBuilder
-// <A extends HttpClientConfigurationBuilder<A,T>,
-// T extends HttpClientConfiguration>
- {
+// <A extends HttpClientConfigurationBuilder<A,T>,
+// T extends HttpClientConfiguration>
+{
- private /*T*/HttpClientConfiguration config = newConfig();
+ private /* T */HttpClientConfiguration config = newConfig();
- protected /*A*/HttpClientConfigurationBuilder builder() {
+ protected /* A */HttpClientConfigurationBuilder builder() {
return this;
}
- protected /*T*/HttpClientConfiguration newConfig() {
+ protected /* T */HttpClientConfiguration newConfig() {
return new HttpClientConfiguration();
}
- public /*T*/HttpClientConfiguration buildConfig() {
- return this.config;
+ public /* T */HttpClientConfiguration buildConfig() {
+ return this.config;
}
-
- public HttpClientConfigurationBuilder/*A*/ withUsername(String theUsername) {
+
+ public HttpClientConfigurationBuilder/* A */ withUsername(String theUsername) {
this.config.setUsername(theUsername);
return builder();
}
-
- public HttpClientConfigurationBuilder/*A*/ withPassword(String thePassword) {
+
+ public HttpClientConfigurationBuilder/* A */ withPassword(String thePassword) {
this.config.setPassword(thePassword);
return builder();
}
-
- public HttpClientConfigurationBuilder/*A*/ withPoolSize(int thePoolSize) {
+
+ public HttpClientConfigurationBuilder/* A */ withPoolSize(int thePoolSize) {
this.config.setPoolSize(thePoolSize);
return builder();
}
-
- public HttpClientConfigurationBuilder/*A*/ withSSL(HttpClientConfiguration.SSL theSSL) {
+
+ public HttpClientConfigurationBuilder/* A */ withSSL(HttpClientConfiguration.SSL theSSL) {
this.config.setSSL(theSSL);
return builder();
}
-
public static class SSLBuilder {
- private HttpClientConfiguration.SSL ssl =
- new HttpClientConfiguration.SSL();
+ private HttpClientConfiguration.SSL ssl = new HttpClientConfiguration.SSL();
- public SSLBuilder withKeyStore(String theKeyStore) {
- this.ssl.setKeyStore(theKeyStore);
+ public SSLBuilder withKeyStore(String theKeyStore) {
+ this.ssl.setKeyStore(theKeyStore);
return this;
}
-
- public SSLBuilder withKeyStoreType(String theKeyStoreType) {
+
+ public SSLBuilder withKeyStoreType(String theKeyStoreType) {
this.ssl.setKeyStoreType(theKeyStoreType);
return this;
}
- public SSLBuilder withKeyStorePassword(String theKeyStorePassword) {
+ public SSLBuilder withKeyStorePassword(String theKeyStorePassword) {
this.ssl.setKeyStorePassword(theKeyStorePassword);
return this;
}
-
- public SSLBuilder withKeyAlias(String theKeyAlias) {
+
+ public SSLBuilder withKeyAlias(String theKeyAlias) {
this.ssl.setKeyAlias(theKeyAlias);
return this;
}
-
- public SSLBuilder withTrustStore(String theTrustStore) {
+
+ public SSLBuilder withTrustStore(String theTrustStore) {
this.ssl.setTrustStore(theTrustStore);
return this;
}
-
- public SSLBuilder withTrustStoreType(String theTrustStoreType) {
+
+ public SSLBuilder withTrustStoreType(String theTrustStoreType) {
this.ssl.setTrustStoreType(theTrustStoreType);
return this;
}
- public SSLBuilder withTrustStorePassword(String theTrustStorePassword) {
+ public SSLBuilder withTrustStorePassword(String theTrustStorePassword) {
this.ssl.setTrustStorePassword(theTrustStorePassword);
return this;
}
package org.acumos.federation.gateway.common;
public class JSONTags {
-
+
public static final String TAG_STATUS_SUCCESS = "success";
public static final String TAG_RESPONSE_STATUS = "status";
public static final String TAG_REQUEST_FROM = "request_from";
public static final String TAG_REQUEST_ID = "request_id";
-
+
public static final String TAG_REQUEST_BODY = "request_body";
public static final String TAG_STATUS_FAILURE = "failure";
public static final String TAG_ERROR_CODE_SUCCESS = "200";
public static final String TAG_ERROR_CODE_FAILURE = "403";
public static final String TAG_ERROR_CODE_EXCEPTION = "500";
-
+
}
import com.fasterxml.jackson.annotation.JsonProperty;
/**
-* This class represents a common format set for the request body sent from the client.
-* Getters and setters encapsulate the fields of a class by making them accessible
-* only through its public methods and keep the values themselves private.
-*/
+ * This class represents a common format set for the request body sent from the
+ * client. Getters and setters encapsulate the fields of a class by making them
+ * accessible only through its public methods and keep the values themselves
+ * private.
+ */
-public class JsonRequest<T> implements Serializable{
+public class JsonRequest<T> implements Serializable {
private static final long serialVersionUID = 7576436006913504503L;
*/
@JsonProperty(value = JSONTags.TAG_REQUEST_ID)
private String requestId;
-
+
/**
* Json property body. It represents the type of generic object.
*/
public void setRequestId(String requestId) {
this.requestId = requestId;
}
-
-
+
public T getBody() {
return body;
}
public void setRequestFrom(String requestFrom) {
this.requestFrom = requestFrom;
}
-
+
}
package org.acumos.federation.gateway.common;
-
/**
* This class represents a common format set for the response send to the client.
* Getters and setters encapsulate the fields of a class by making them accessible
*/
@JsonProperty(value = JSONTags.TAG_RESPONSE_BODY)
private T responseBody;
-
+
public Boolean getStatus() {
return status;
}
}
public String toString() {
- return new StringBuilder("JsonResponse")
- .append(System.identityHashCode(this))
- .append('(')
- .append(this.responseCode)
- .append(' ')
- .append(this.responseDetail)
- .append(", ")
- .append(this.responseBody == null ? "null" : this.responseBody)
- .append(')')
- .toString();
+ return new StringBuilder("JsonResponse").append(System.identityHashCode(this)).append('(')
+ .append(this.responseCode).append(' ').append(this.responseDetail).append(", ")
+ .append(this.responseBody == null ? "null" : this.responseBody).append(')').toString();
}
}
}
/**
- * Gets a logger for the specified class name. If the logger does not
- * already exist in the map, this creates a new logger.
+ * Gets a logger for the specified class name. If the logger does not already
+ * exist in the map, this creates a new logger.
*
* @param className
* If null or empty, uses EELFLoggerDelegate as the class name.
import org.acumos.federation.gateway.config.EELFLoggerDelegate;
-
/**
*
*
import org.acumos.federation.gateway.service.ServiceContext;
import org.acumos.federation.gateway.security.Peer;
-
/**
*
*
public class ControllerContext implements ServiceContext {
public Peer getPeer() {
- return (Peer)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+ return (Peer) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
-
*/
public class PeerSubscriptionEvent extends EventObject {
- private MLPPeer peer;
- private MLPPeerSubscription subscription;
- private List<MLPSolution> solutions;
+ private MLPPeer peer;
+ private MLPPeerSubscription subscription;
+ private List<MLPSolution> solutions;
-
- public PeerSubscriptionEvent(Object theSource,
- MLPPeer thePeer,
- MLPPeerSubscription theSubscription,
- List<MLPSolution> theSolutions) {
+ public PeerSubscriptionEvent(Object theSource, MLPPeer thePeer, MLPPeerSubscription theSubscription,
+ List<MLPSolution> theSolutions) {
super(theSource);
this.peer = thePeer;
this.subscription = theSubscription;
*/
public class Peer extends User {
- private MLPPeer peerInfo;
+ private MLPPeer peerInfo;
public Peer(MLPPeer thePeerInfo, Role theRole) {
this(thePeerInfo, theRole.priviledges());
- }
+ }
public Peer(MLPPeer thePeerInfo, Collection<? extends GrantedAuthority> theAuthorities) {
- super (thePeerInfo.getName(), "", true, true, true, true, theAuthorities);
+ super(thePeerInfo.getName(), "", true, true, true, true, theAuthorities);
this.peerInfo = thePeerInfo;
}
return this.peerInfo;
}
-
private static PeerService peerService = null;
@Autowired
peerService = thePeerService;
}
-
private static Peer self = null;
-
+
public static Peer self() {
if (self == null) {
- if (peerService == null)
+ if (peerService == null)
throw new IllegalStateException("Initialization not completed");
self = new Peer(peerService.getSelf(), Role.SELF.priviledges());
}
}
}
-
-
*/
package org.acumos.federation.gateway.security;
-
import org.springframework.security.core.GrantedAuthority;
/**
*/
public enum Priviledge implements GrantedAuthority {
- /**
- Gives access to catalog items (solutions); coarse at this point, all
- (list/read/download) or nothing
+ /**
+ * Gives access to catalog items (solutions); coarse at this point, all
+ * (list/read/download) or nothing
*/
CATALOG_ACCESS,
/**
- Gives access to the local list of peers.
- In the future we might want to refine this by defining which peers should be provided (byb some base selection criteria)
+ * Gives access to the local list of peers. In the future we might want to
+ * refine this by defining which peers should be provided (byb some base
+ * selection criteria)
*/
PEERS_ACCESS,
/**
- The right to submit a subscription request. This is granted to ANY if so enabled system wide.
+ * The right to submit a subscription request. This is granted to ANY if so
+ * enabled system wide.
*/
SUBSCRIPTION;
return name();
}
}
-
*/
package org.acumos.federation.gateway.security;
-
import java.util.Collection;
import java.util.Collections;
import java.util.Arrays;
public enum Role {
/**
- * Un-authenticated client. Will at most be granted access to subscribe
+ * Un-authenticated client. Will at most be granted access to subscribe
* functionality
*/
ANY(Collections.EMPTY_LIST),
/**
* Common peer, grants generic solution catalog access
*/
- PEER(Collections.unmodifiableList(
- Arrays.asList(Priviledge.CATALOG_ACCESS))),
+ PEER(Collections.unmodifiableList(Arrays.asList(Priviledge.CATALOG_ACCESS))),
/**
- * Enhanced peer, gains (some lovel of) read access to the local peer list
+ * Enhanced peer, gains (some lovel of) read access to the local peer list
*/
- PARTNER(Collections.unmodifiableList(
- Arrays.asList(Priviledge.CATALOG_ACCESS, Priviledge.PEERS_ACCESS))),
+ PARTNER(Collections.unmodifiableList(Arrays.asList(Priviledge.CATALOG_ACCESS, Priviledge.PEERS_ACCESS))),
/**
- * The Acumos instance this gateway is serving, including local calls and
- * calls received through the gateways' private interface from other
- * components, grants all priviledges
+ * The Acumos instance this gateway is serving, including local calls and calls
+ * received through the gateways' private interface from other components,
+ * grants all priviledges
*/
- SELF(Collections.unmodifiableList(
- Arrays.asList(Priviledge.class.getEnumConstants())));
-
+ SELF(Collections.unmodifiableList(Arrays.asList(Priviledge.class.getEnumConstants())));
private Collection<Priviledge> priviledges;
}
}
-
/**
*
- * X.509 certificate authentication : verifying the identity of a communication peer when using the HTTPS (HTTP over SSL) protocol.
+ * X.509 certificate authentication : verifying the identity of a communication
+ * peer when using the HTTPS (HTTP over SSL) protocol.
*
*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class X509AuthenticationFilter extends WebSecurityConfigurerAdapter {
-
+
private final EELFLoggerDelegate log = EELFLoggerDelegate.getLogger(getClass().getName());
@Autowired
public X509AuthenticationFilter() {
}
-/*
- public X509AuthenticationFilter(boolean disableDefaults) {
- super(disableDefaults);
- }
-*/
+ /*
+ * public X509AuthenticationFilter(boolean disableDefaults) {
+ * super(disableDefaults); }
+ */
/**
- * subjectPrincipalRegex("CN=(.*?)(?:,|$)") :- The regular expression used to extract a username from the client certificates subject name.
- * (CN value of the client certificate)
- */
+ * subjectPrincipalRegex("CN=(.*?)(?:,|$)") :- The regular expression used to
+ * extract a username from the client certificates subject name. (CN value of
+ * the client certificate)
+ */
@Override
protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .x509()
- .subjectPrincipalRegex("CN=(.*?)(?:,|$)")
+ http.authorizeRequests().anyRequest().authenticated().and().x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)")
.userDetailsService(userDetailsService());
}
-
- //@Bean
+
+ // @Bean
public UserDetailsService userDetailsService() {
return (username -> {
log.info(EELFLoggerDelegate.debugLogger, " X509 subject : " + username);
List<MLPPeer> mlpPeers = peerService.getPeerBySubjectName(username);
log.info(EELFLoggerDelegate.debugLogger, " Peers matching X509 subject : " + mlpPeers);
- if(!Utils.isEmptyList(mlpPeers)) {
+ if (!Utils.isEmptyList(mlpPeers)) {
log.info(EELFLoggerDelegate.debugLogger, " We are providing a matching Use ");
return new Peer(mlpPeers.get(0), Role.PEER);
- }
- else {
+ } else {
MLPPeer unknown = new MLPPeer();
- //set it up with available info
+ // set it up with available info
unknown.setSubjectName(username);
return new Peer(unknown, Role.ANY);
}
});
- }
+ }
}
-
import org.acumos.cds.domain.MLPSolutionRevision;
import org.acumos.cds.transport.RestPageResponse;
-
/**
- * Handles access to the solutions catalog
+ * Handles access to the solutions catalog. The APIs of tis interface take a
+ * ServiceContext argument which determines the identity of the peer on bahalf
+ * of whom the call is executed. This information allows us to tailor the
+ * response according to a peer's granted access. It is the responsability of
+ * each implementation to ensure that the peer on whose behalf the service is
+ * executed only accesses solutions it was granted access to.
*/
public interface CatalogService {
-
/**
+ * API to be invoked by Peer Acumos to fetch the Catalog Solutions List.
*
- * API to be invoked by Peer Acumos to fetch the Catalog Solutions List.
- *
- * @param theSelector contains the selection criteria.
+ * @param theSelector
+ * contains the selection criteria. Must match the available criteria
+ * in CDS.
+ * @param theContext
+ * the execution context.
*
- * @return List of the Catalog Solutions for the specified list of query parameters
+ * @return List of the Catalog Solutions for the selection criteria
+ */
+ public List<MLPSolution> getSolutions(Map<String, ?> theSelector, ServiceContext theContext);
+
+ /**
+ * Default interface for calls in behalf of the local Acumos service.
+ *
+ * @param theSelector
+ * contains the selection criteria. Must match the available criteria
+ * in CDS
+ * @return list of the solutions for the selection criteria
*/
- public List<MLPSolution> getSolutions(Map<String,?> theSelector, ServiceContext theContext);
-
- public default List<MLPSolution> getSolutions(Map<String,?> theSelector) {
+ public default List<MLPSolution> getSolutions(Map<String, ?> theSelector) {
return getSolutions(theSelector, ServiceContext.selfService());
}
/**
+ * Retrieve a solution's details from CDS.
+ *
+ * @param theSolutionId
+ * solution identifier (UUID).
+ * @param theContext
+ * the execution context
+ * @return solution information
*/
public MLPSolution getSolution(String theSolutionId, ServiceContext theContext);
-
+
+ /**
+ * Default solution access interface for calls in behalf of the local Acumos
+ * service.
+ *
+ * @param theSolutionId
+ * solution identifier (UUID).
+ * @return solution information
+ */
public default MLPSolution getSolution(String theSolutionId) {
return getSolution(theSolutionId, ServiceContext.selfService());
}
-
-
+
/**
- * @param solutionId : SolutionId for which Solution Revision Needs to be returned
+ * Provides revision information given a solution identifier.
*
- * @return List of the Solution Revision for the specified solution Id
+ * @param theSolutionId
+ * identifier of the solution whose revisions are to be provided
+ * @param theContext
+ * the execution context
+ * @return list of the solution revision for the specified solution Id
*/
- public List<MLPSolutionRevision> getSolutionRevisions(
- String theSolutionId, ServiceContext theContext);
-
+ public List<MLPSolutionRevision> getSolutionRevisions(String theSolutionId, ServiceContext theContext);
+
public default List<MLPSolutionRevision> getSolutionRevisions(String theSolutionId) {
return getSolutionRevisions(theSolutionId, ServiceContext.selfService());
}
+
/**
+ * Access to a solution revision information.
+ *
+ * @param theSolutionId
+ * solution identifier (UUID).
+ * @param theRevisionId
+ * revision identifier (UUID).
+ * @param theContext
+ * the execution context
+ * @return solution revision information
*/
- public MLPSolutionRevision getSolutionRevision(
- String theSolutionId, String theRevisionId, ServiceContext theContext);
+ public MLPSolutionRevision getSolutionRevision(String theSolutionId, String theRevisionId,
+ ServiceContext theContext);
- public default MLPSolutionRevision getSolutionRevision(
- String theSolutionId, String theRevisionId) {
+ /**
+ * Default solution revision access interface for calls in behalf of the local
+ * Acumos service.
+ *
+ * @param theSolutionId
+ * solution identifier (UUID).
+ * @param theRevisionId
+ * revision identifier (UUID).
+ * @return solution revision information
+ */
+ public default MLPSolutionRevision getSolutionRevision(String theSolutionId, String theRevisionId) {
return getSolutionRevision(theSolutionId, theRevisionId, ServiceContext.selfService());
}
/**
- * @param solutionId : SolutionId for which Solution Revision Artifacts Needs to be returned
- *
- * @param revisionid : RevisionId of the Solution for which List of Artifacts are needed.
+ * Access the list of solution revision artifacts.
*
- * @return List of the Solution Artifacts for the specified solution Id & revisionId
+ * @param theSolutionId
+ * solution identifier (UUID).
+ * @param theRevisionId
+ * revision identifier (UUID).
+ * @param theContext
+ * the execution context
+ * @return list of the related artifacts
*/
- public List<MLPArtifact> getSolutionRevisionArtifacts(
- String theSolutionId, String theRevisionId, ServiceContext theContext);
-
- public default List<MLPArtifact> getSolutionRevisionArtifacts(
- String theSolutionId, String theRevisionId) {
+ public List<MLPArtifact> getSolutionRevisionArtifacts(String theSolutionId, String theRevisionId,
+ ServiceContext theContext);
+
+ /**
+ * Default solution revision access interface for calls in behalf of the local
+ * Acumos service.
+ *
+ * @param theSolutionId
+ * solution identifier (UUID).
+ * @param theRevisionId
+ * revision identifier (UUID).
+ * @return list of the related artifacts
+ */
+ public default List<MLPArtifact> getSolutionRevisionArtifacts(String theSolutionId, String theRevisionId) {
return getSolutionRevisionArtifacts(theSolutionId, theRevisionId, ServiceContext.selfService());
}
-
+
/**
- * @param artifactId of the File stored in Nexus repository
- * @return Artifact File for the Machine Learning Solution
+ * Retrieve artifact content.
+ *
+ * @param theArtifactId
+ * identifier of the acumos artifact whose content needs to be
+ * retrieved
+ * @param theContext
+ * the execution context
+ * @return resource containing access to the actual artifact content
*/
public InputStreamResource getSolutionRevisionArtifactContent(String theArtifactId, ServiceContext theContext);
-
+
}
public interface PeerService {
/**
- * Strictly an internal service call.
- * Needs to avoid the 'chicken,egg' problem: one needs a context to access
- * peers, including the 'self' peer.
+ * Provides the information for the 'self' peer. Needs to avoid the
+ * 'chicken,egg' problem: one needs a context to access peers, including the
+ * 'self' peer. Strictly an internal service call.
+ *
+ * @return peer information for the local Acumos system
*/
public MLPPeer getSelf();
/**
- * Provide the list of locally registered peers to one of our peers
- * It is the responsability of the implementation to decide which peer
- * information to expose in each case
+ * Provide the list of locally registered peers to one of our peers It is the
+ * responsability of the implementation to decide which peer information to
+ * expose.
+ *
+ * @param theContext
+ * the execution context
+ * @return lits ot peers for the local acumoms system
*/
public List<MLPPeer> getPeers(ServiceContext theContext);
-
+
+ /**
+ * Default peer info access on half of the local Acumos system
+ *
+ * @return list of peers for the local acumoms system
+ */
public default List<MLPPeer> getPeers() {
return getPeers(ServiceContext.selfService());
}
-
+
/**
- * @return Peer based on the configured Subject Name
+ * Lookup peer info by subject name. Not sure that this call should be offered
+ * based on a context, it isi strictly a local call.
+ *
+ * @param theSubjectName
+ * peer registered subject name
+ * @param theContext
+ * the execution context
+ * @return list of peers with the given subject name. Should contain only one
+ * entry.
+ */
+ public List<MLPPeer> getPeerBySubjectName(String theSubjectName, ServiceContext theContext);
+
+ /**
+ * Lookup peer info by subject name. Call on behalf of local Acumos system.
+ *
+ * @param theSubjectName
+ * peer registered subject name
+ * @return list of peers with the given subject name. Should contain only one
+ * entry.
*/
- public List<MLPPeer> getPeerBySubjectName(
- String theSubjectName, ServiceContext theContext);
-
public default List<MLPPeer> getPeerBySubjectName(String theSubjectName) {
return getPeerBySubjectName(theSubjectName, ServiceContext.selfService());
}
-
- /** */
+
+ /**
+ * Retrieve peer information based on peer identifier.
+ *
+ * @param thePeerId
+ * peer identifier
+ * @param theContext
+ * the execution context
+ * @return peer information
+ */
public MLPPeer getPeerById(String thePeerId, ServiceContext theContext);
-
+
+ /**
+ * Retrieve peer information based on peer identifier. Call on bahalf of local
+ * Acumos system.
+ *
+ * @param thePeerId
+ * peer identifier
+ * @return peer information
+ */
public default MLPPeer getPeerById(String thePeerId) {
return getPeerById(thePeerId, ServiceContext.selfService());
}
-
+
/**
- * Optional operation allowing the gateway to provision a peer in some
- * initial state as part of a in-band peer handshake mechanism.
- * The whole handshake procedure is to be completed elsewhere (portal);
- * We do not pass a context as this operation is performed with
- * frespect to 'self' (to reconsider).
+ * Optional operation allowing the gateway to provision a peer in some initial
+ * state as part of a in-band peer handshake mechanism. The whole handshake
+ * procedure is to be completed elsewhere (portal); We do not pass a context as
+ * this operation is performed with frespect to 'self' (to reconsider).
*
- * @param mlpPeer MLPPeer New Peer info to be submitted to the platform
- *
- * @return Peer configuration that has been created.
+ * @param thePeer
+ * new peer info to be submitted to the platform
+ * @throws ServiceException
+ * if anything goes wrong during the check/provisioning process
*/
- public void subscribePeer(MLPPeer mlpPeer) throws ServiceException;
-
+ public void subscribePeer(MLPPeer thePeer) throws ServiceException;
+
/**
* Optional operation allowing the gateway to update a peer and mark it for
* removal as part of a in-band peer handshake mechanism.
*
- * @param mlpPeer MLPPeer New Peer info to be submitted to the platform
- *
- * @return Peer configuration that has been created.
+ * @param thePeer
+ * MLPPeer New Peer info to be submitted to the platform
+ * @throws ServiceException
+ * if anything goes wrong during the check/provisioning process
*/
- public void unsubscribePeer(MLPPeer mlpPeer) throws ServiceException;
-
-
+ public void unsubscribePeer(MLPPeer thePeer) throws ServiceException;
+
}
import org.acumos.federation.gateway.security.Peer;
-
-
/**
* Expose the invocation frame for service calls (whenever a call is selectively
* provided).
*/
public interface ServiceContext {
-
+
/*
* In who's behalf are we providing the service.
*/
- public Peer getPeer();
+ public Peer getPeer();
/*
- * Is the service to be provided for the benefit of the local Acumos system?
+ * Is the service to be provided for the benefit of the local Acumos system?
*/
public default boolean isSelf() {
return getPeer().getPeerInfo().isSelf();
return () -> Peer.self();
}
}
-
package org.acumos.federation.gateway.service;
-
/**
*
*/
package org.acumos.federation.gateway.service.impl;
-
import org.springframework.beans.factory.annotation.Autowired;
import org.acumos.federation.gateway.config.EELFLoggerDelegate;
import org.acumos.cds.client.ICommonDataServiceRestClient;
-
-
/** */
public abstract class AbstractServiceImpl {
protected final EELFLoggerDelegate log = EELFLoggerDelegate.getLogger(getClass().getName());
-
public ICommonDataServiceRestClient getClient() {
return clients.getClient();
}
-
+
}
package org.acumos.federation.gateway.service.impl;
-
import org.springframework.core.io.Resource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.apache.commons.io.IOUtils;
-
public class AbstractServiceLocalImpl {
-
protected EELFLoggerDelegate log = EELFLoggerDelegate.getLogger(getClass().getName());
- protected Resource resource;
+ protected Resource resource;
- @Autowired
+ @Autowired
protected ApplicationContext appCtx;
@Autowired
- protected LocalWatchService watcher;
-
+ protected LocalWatchService watcher;
public void setSource(String theSource) {
this.resource = this.appCtx.getResource(theSource);
import org.acumos.cds.transport.RestPageResponse;
/**
- * CDS based implementation of the CatalogService.
+ * CDS based implementation of the CatalogService.
*
*/
@Service
@Conditional(GatewayCondition.class)
-public class CatalogServiceImpl
- extends AbstractServiceImpl
- implements CatalogService {
+public class CatalogServiceImpl extends AbstractServiceImpl implements CatalogService {
@Autowired
private Environment env;
private Map<String, Object> baseSelector;
-
+
@PostConstruct
public void initService() {
baseSelector = new HashMap<String, Object>();
- baseSelector.put("active", true); //Fetch all active solutions
+ baseSelector.put("active", true); // Fetch all active solutions
baseSelector.put("accessTypeCode", AccessTypeCode.PB.toString()); // Fetch allowed only for Public models
- baseSelector.put("validationStatusCode", ValidationStatusCode.PS.toString()); // Validation status should be Passed locally
-// baseSelector.put("source", "");
-
+ baseSelector.put("validationStatusCode", ValidationStatusCode.PS.toString()); // Validation status should be
+ // Passed locally
+ // baseSelector.put("source", "");
+
}
@Override
- public List<MLPSolution> getSolutions(
- Map<String,?> theSelector, ServiceContext theContext) {
-
+ public List<MLPSolution> getSolutions(Map<String, ?> theSelector, ServiceContext theContext) {
+
log.debug(EELFLoggerDelegate.debugLogger, "getSolutions");
List<MLPSolution> filteredMLPSolutions = null;
ICommonDataServiceRestClient cdsClient = getClient();
-
- Map<String, Object> selector =
- new HashMap<String, Object>(this.baseSelector);
+
+ Map<String, Object> selector = new HashMap<String, Object>(this.baseSelector);
if (theSelector != null)
selector.putAll(theSelector);
}
@Override
- public MLPSolution getSolution(
- String theSolutionId, ServiceContext theContext) {
-
+ public MLPSolution getSolution(String theSolutionId, ServiceContext theContext) {
+
log.debug(EELFLoggerDelegate.debugLogger, "getSolution");
ICommonDataServiceRestClient cdsClient = getClient();
return cdsClient.getSolution(theSolutionId);
}
-
+
@Override
- public List<MLPSolutionRevision> getSolutionRevisions(
- String theSolutionId, ServiceContext theContext) {
+ public List<MLPSolutionRevision> getSolutionRevisions(String theSolutionId, ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getSolutionRevisions");
ICommonDataServiceRestClient cdsClient = getClient();
- List<MLPSolutionRevision> mlpSolutionRevisions =
- cdsClient.getSolutionRevisions(theSolutionId);
+ List<MLPSolutionRevision> mlpSolutionRevisions = cdsClient.getSolutionRevisions(theSolutionId);
return mlpSolutionRevisions;
}
@Override
- public MLPSolutionRevision getSolutionRevision(
- String theSolutionId, String theRevisionId, ServiceContext theContext) {
+ public MLPSolutionRevision getSolutionRevision(String theSolutionId, String theRevisionId,
+ ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getSolutionRevision");
ICommonDataServiceRestClient cdsClient = getClient();
- MLPSolutionRevision mlpSolutionRevision =
- cdsClient.getSolutionRevision(theSolutionId, theRevisionId);
+ MLPSolutionRevision mlpSolutionRevision = cdsClient.getSolutionRevision(theSolutionId, theRevisionId);
return mlpSolutionRevision;
}
@Override
- public List<MLPArtifact> getSolutionRevisionArtifacts(
- String theSolutionId, String theRevisionId, ServiceContext theContext) {
-
+ public List<MLPArtifact> getSolutionRevisionArtifacts(String theSolutionId, String theRevisionId,
+ ServiceContext theContext) {
+
log.debug(EELFLoggerDelegate.debugLogger, "getSolutionRevisionArtifacts");
ICommonDataServiceRestClient cdsClient = getClient();
List<MLPArtifact> mlpArtifacts = cdsClient.getSolutionRevisionArtifacts(theSolutionId, theRevisionId);
}
@Override
- public InputStreamResource getSolutionRevisionArtifactContent(
- String theArtifactId, ServiceContext theContext) {
+ public InputStreamResource getSolutionRevisionArtifactContent(String theArtifactId, ServiceContext theContext) {
InputStreamResource streamResource = null;
- ByteArrayOutputStream byteArrayOutputStream = null;
- try{
+ ByteArrayOutputStream byteArrayOutputStream = null;
+ try {
ICommonDataServiceRestClient cdsClient = getClient();
MLPArtifact mlpArtifact = cdsClient.getArtifact(theArtifactId);
-
+
NexusArtifactClient artifactClient = this.clients.getNexusClient();
-
+
byteArrayOutputStream = artifactClient.getArtifact(mlpArtifact.getUri());
InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
-
- //Plain Old Java. Sprint 3 will use try resource handling
- if(inputStream != null) {
+
+ // Plain Old Java. Sprint 3 will use try resource handling
+ if (inputStream != null) {
streamResource = new InputStreamResource(inputStream
- /*, some_description
- */);
+ /*
+ * , some_description
+ */);
}
- if(byteArrayOutputStream != null) {
+ if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
-
+
} catch (Exception e) {
log.error(EELFLoggerDelegate.errorLogger, "getSolutionRevisionArtifactiContent", e);
- }
+ }
// TODO Auto-generated method stub
return streamResource;
}
-
}
import org.acumos.cds.domain.MLPSolutionRevision;
import org.acumos.cds.transport.RestPageResponse;
-
/**
*
*
*/
@Service
-@ConfigurationProperties(prefix="catalogLocal")
+@ConfigurationProperties(prefix = "catalogLocal")
@Conditional(AdapterCondition.class)
-public class CatalogServiceLocalImpl extends AbstractServiceLocalImpl
- implements CatalogService {
-
- private List<FLPSolution> solutions;
+public class CatalogServiceLocalImpl extends AbstractServiceLocalImpl implements CatalogService {
+ private List<FLPSolution> solutions;
@PostConstruct
public void initService() {
checkResource();
try {
- watcher.watchOn(this.resource.getURL().toURI(),
- (uri) -> { loadSolutionsCatalogInfo(); });
+ watcher.watchOn(this.resource.getURL().toURI(), (uri) -> {
+ loadSolutionsCatalogInfo();
+ });
- }
- catch (IOException | URISyntaxException iox) {
- log.info(EELFLoggerDelegate.errorLogger, "Catalog watcher registration failed for " + this.resource, iox);
- }
+ } catch (IOException | URISyntaxException iox) {
+ log.info(EELFLoggerDelegate.errorLogger, "Catalog watcher registration failed for " + this.resource, iox);
+ }
loadSolutionsCatalogInfo();
- // Done
- log.debug(EELFLoggerDelegate.debugLogger, "Local CatalogService available");
+ // Done
+ log.debug(EELFLoggerDelegate.debugLogger, "Local CatalogService available");
}
@PreDestroy
public void cleanupService() {
- }
+ }
/** */
private void loadSolutionsCatalogInfo() {
synchronized (this) {
try {
- ObjectReader objectReader =
- new ObjectMapper().reader(FLPSolution.class);
- MappingIterator objectIterator =
- objectReader.readValues(this.resource.getURL());
+ ObjectReader objectReader = new ObjectMapper().reader(FLPSolution.class);
+ MappingIterator objectIterator = objectReader.readValues(this.resource.getURL());
this.solutions = objectIterator.readAll();
log.info(EELFLoggerDelegate.debugLogger, "loaded " + this.solutions.size() + " solutions");
- }
- catch (Exception x) {
+ } catch (Exception x) {
throw new BeanInitializationException("Failed to load solutions catalog from " + this.resource, x);
}
}
}
-
@Override
- public List<MLPSolution> getSolutions(
- Map<String,?> theSelector, ServiceContext theContext) {
+ public List<MLPSolution> getSolutions(Map<String, ?> theSelector, ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getSolutions");
- String modelTypeSelector = theSelector == null ? null
- :(String)theSelector.get("modelTypeCode");
- final List<String> modelTypes =
- modelTypeSelector == null ? null
- : Arrays.asList(modelTypeSelector.split(","));
- return solutions.stream()
- .filter(solution -> {
- log.debug(EELFLoggerDelegate.debugLogger, "getPeerCatalogSolutionsList: looking for " + modelTypes + ", has " + solution.getModelTypeCode());
- return modelTypes == null ||
- modelTypes.contains(solution.getModelTypeCode());
- })
- .collect(Collectors.toList());
+ String modelTypeSelector = theSelector == null ? null : (String) theSelector.get("modelTypeCode");
+ final List<String> modelTypes = modelTypeSelector == null ? null : Arrays.asList(modelTypeSelector.split(","));
+ return solutions.stream().filter(solution -> {
+ log.debug(EELFLoggerDelegate.debugLogger,
+ "getPeerCatalogSolutionsList: looking for " + modelTypes + ", has " + solution.getModelTypeCode());
+ return modelTypes == null || modelTypes.contains(solution.getModelTypeCode());
+ }).collect(Collectors.toList());
}
@Override
- public MLPSolution getSolution(
- final String theSolutionId, ServiceContext theContext) {
+ public MLPSolution getSolution(final String theSolutionId, ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getSolution");
- return solutions.stream()
- .filter(solution -> {
- return theSolutionId.equals(solution.getSolutionId());
- })
- .findFirst()
- .orElse(null);
+ return solutions.stream().filter(solution -> {
+ return theSolutionId.equals(solution.getSolutionId());
+ }).findFirst().orElse(null);
}
-
+
@Override
- public List<MLPSolutionRevision> getSolutionRevisions(
- final String theSolutionId, ServiceContext theContext) {
+ public List<MLPSolutionRevision> getSolutionRevisions(final String theSolutionId, ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getSolutionRevisions");
- FLPSolution solution =
- this.solutions.stream()
- .filter(sol ->
- sol.getSolutionId().equals(theSolutionId))
- .findFirst()
- .orElse(null);
-
+ FLPSolution solution = this.solutions.stream().filter(sol -> sol.getSolutionId().equals(theSolutionId))
+ .findFirst().orElse(null);
+
return (solution == null) ? null : solution.getMLPRevisions();
}
-
+
@Override
- public MLPSolutionRevision getSolutionRevision(
- String theSolutionId, String theRevisionId, ServiceContext theContext) {
+ public MLPSolutionRevision getSolutionRevision(String theSolutionId, String theRevisionId,
+ ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getSolutionRevision");
List<MLPSolutionRevision> revisions = getSolutionRevisions(theSolutionId, theContext);
if (revisions == null)
return null;
- return revisions.stream()
- .filter(rev ->
- rev.getRevisionId().equals(theRevisionId))
- .findFirst()
- .orElse(null);
+ return revisions.stream().filter(rev -> rev.getRevisionId().equals(theRevisionId)).findFirst().orElse(null);
}
@Override
- public List<MLPArtifact> getSolutionRevisionArtifacts(
- final String theSolutionId, final String theRevisionId, ServiceContext theContext) {
+ public List<MLPArtifact> getSolutionRevisionArtifacts(final String theSolutionId, final String theRevisionId,
+ ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getSolutionRevisionArtifacts");
- FLPRevision revision = (FLPRevision)
- getSolutionRevision(theSolutionId, theRevisionId, theContext);
+ FLPRevision revision = (FLPRevision) getSolutionRevision(theSolutionId, theRevisionId, theContext);
return (revision == null) ? null : revision.getArtifacts();
}
@Override
- public InputStreamResource getSolutionRevisionArtifactContent(
- String theArtifactId, ServiceContext theContext) {
+ public InputStreamResource getSolutionRevisionArtifactContent(String theArtifactId, ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getSolutionRevisionArtifactContent");
- //cumbersome
- for (FLPSolution solution: this.solutions) {
- for (FLPRevision revision: solution.getRevisions()) {
- for (MLPArtifact artifact: revision.getArtifacts()) {
+ // cumbersome
+ for (FLPSolution solution : this.solutions) {
+ for (FLPRevision revision : solution.getRevisions()) {
+ for (MLPArtifact artifact : revision.getArtifacts()) {
if (artifact.getArtifactId().equals(theArtifactId)) {
try {
- return new InputStreamResource(
- new URI(artifact.getUri()).toURL().openStream());
- }
- catch (Exception x) {
- log.debug(EELFLoggerDelegate.debugLogger, "failed to load content from " + artifact.getUri(), x);
+ return new InputStreamResource(new URI(artifact.getUri()).toURL().openStream());
+ } catch (Exception x) {
+ log.debug(EELFLoggerDelegate.debugLogger,
+ "failed to load content from " + artifact.getUri(), x);
}
}
}
/** */
public static class FLPSolution extends MLPSolution {
- @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
+ @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private List<FLPRevision> revisions;
- //@JsonIgnore
+ // @JsonIgnore
public List<FLPRevision> getRevisions() {
return this.revisions;
}
-
- //@JsonIgnore
+
+ // @JsonIgnore
protected List<MLPSolutionRevision> getMLPRevisions() {
- return this.revisions == null ? null :
- this.revisions.stream()
- .map(rev -> (MLPSolutionRevision)rev)
- .collect(Collectors.toList());
+ return this.revisions == null ? null
+ : this.revisions.stream().map(rev -> (MLPSolutionRevision) rev).collect(Collectors.toList());
}
public void setRevisions(List<FLPRevision> theRevisions) {
}
}
-
+
/** */
public static class FLPRevision extends MLPSolutionRevision {
- @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
+ @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private List<MLPArtifact> artifacts;
- //@JsonIgnore
- //we send a deep clone as the client can modify them and we only have one copy
+ // @JsonIgnore
+ // we send a deep clone as the client can modify them and we only have one copy
public List<MLPArtifact> getArtifacts() {
List<MLPArtifact> copy = new LinkedList<MLPArtifact>();
- for (MLPArtifact artifact: this.artifacts) {
+ for (MLPArtifact artifact : this.artifacts) {
MLPArtifact acopy = new MLPArtifact();
acopy.setArtifactId(artifact.getArtifactId());
acopy.setArtifactTypeCode(artifact.getArtifactTypeCode());
}
}
-
}
*
*/
package org.acumos.federation.gateway.service.impl;
+
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public PeerServiceImpl() {
}
- @Override
- public MLPPeer getSelf() {
- return (MLPPeer)
- getClient().searchPeers(
- new MapBuilder()
- .put("isSelf", Boolean.TRUE)
- .build(),
- false)
- .get(0);
- }
-
+ @Override
+ public MLPPeer getSelf() {
+ return (MLPPeer) getClient().searchPeers(new MapBuilder().put("isSelf", Boolean.TRUE).build(), false).get(0);
+ }
/**
* ToDo:
log.debug(EELFLoggerDelegate.debugLogger, "getPeers");
ICommonDataServiceRestClient cdsClient = getClient();
List<MLPPeer> mlpPeers = null;
-/*
- cdsClient.searchPeers(
- new MapBuilder()
- .put("status", PeerStatus.ACTIVE)
- .build(),
- false);
-*/
+ /*
+ * cdsClient.searchPeers( new MapBuilder() .put("status", PeerStatus.ACTIVE)
+ * .build(), false);
+ */
RestPageResponse<MLPPeer> mlpPeersPage = cdsClient.getPeers(null);
if (mlpPeersPage != null)
mlpPeers = mlpPeersPage.getContent();
- if(mlpPeers !=null) {
+ if (mlpPeers != null) {
log.debug(EELFLoggerDelegate.debugLogger, "getPeers size:{}", mlpPeers.size());
}
return mlpPeers;
}
@Override
- public List<MLPPeer> getPeerBySubjectName(String theSubjectName,
- ServiceContext theContext) {
+ public List<MLPPeer> getPeerBySubjectName(String theSubjectName, ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getPeerBySubjectName");
- List<MLPPeer> mlpPeers =
- getClient().searchPeers(new MapBuilder()
- .put("subjectName", theSubjectName)
- .build(),
- false);
- if(mlpPeers != null && mlpPeers.size() > 0) {
+ List<MLPPeer> mlpPeers = getClient().searchPeers(new MapBuilder().put("subjectName", theSubjectName).build(),
+ false);
+ if (mlpPeers != null && mlpPeers.size() > 0) {
log.debug(EELFLoggerDelegate.debugLogger, "getPeerBySubjectName size:{}", mlpPeers.size());
}
return mlpPeers;
}
-
+
@Override
public MLPPeer getPeerById(String thePeerId, ServiceContext theContext) {
log.debug(EELFLoggerDelegate.debugLogger, "getPeerById: {}", thePeerId);
MLPPeer mlpPeer = getClient().getPeer(thePeerId);
- if(mlpPeer !=null) {
+ if (mlpPeer != null) {
log.error(EELFLoggerDelegate.debugLogger, "getPeerById: {}", mlpPeer.toString());
}
return mlpPeer;
}
-
+
@Override
public void subscribePeer(MLPPeer thePeer) throws ServiceException {
log.debug(EELFLoggerDelegate.debugLogger, "subscribePeer");
throw new ServiceException("No subject name is available");
ICommonDataServiceRestClient cdsClient = getClient();
- List<MLPPeer> mlpPeers =
- cdsClient.searchPeers(new MapBuilder()
- .put("subjectName", subjectName)
- .build(),
- false);
+ List<MLPPeer> mlpPeers = cdsClient.searchPeers(new MapBuilder().put("subjectName", subjectName).build(), false);
- if(mlpPeers != null && mlpPeers.size() > 0) {
+ if (mlpPeers != null && mlpPeers.size() > 0) {
throw new ServiceException("Peer with subjectName '" + subjectName + "' already exists: " + mlpPeers);
}
- log.error(EELFLoggerDel