Also added serializationId to several classes to address eclipse warnings.
Issue-ID: POLICY-2188
Change-Id: I3df5e8abaad8da9261c0d5cd19a93ed68dceb870
Signed-off-by: Jim Hahn <jrh3@att.com>
synchronized (myPdpSync) {
if (myPdp == null) {
- myPdp = new DroolsPdpImpl(resourceName,false,4,MonitorTime.getInstance().getDate());
+ myPdp = new DroolsPdpImpl(resourceName, false, 4, MonitorTime.getInstance().getDate());
}
String siteName = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.SITE_NAME);
if (siteName == null) {
}
myPdp.setSite(siteName);
if (electionHandler == null) {
- electionHandler = new DroolsPdpsElectionHandler(conn,myPdp);
+ electionHandler = new DroolsPdpsElectionHandler(conn, myPdp);
}
}
logger.info("\n\nThis controller is a standby, waiting to be chosen as primary...\n\n");
private Date updatedDate;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name = "designatedDate",nullable = false)
+ @Column(name = "designatedDate", nullable = false)
private Date designatedDate;
@Column(name = "site", nullable = true, length = 50)
@Override
public boolean equals(Object other) {
if (other instanceof DroolsPdp) {
- return this.getPdpId().equals(((DroolsPdp)other).getPdpId());
+ return this.getPdpId().equals(((DroolsPdp) other).getPdpId());
} else {
return false;
}
}
private int commonCompare(DroolsPdp other) {
- if (nullSafeCompare(this.getSite(),other.getSite()) == 0) {
+ if (nullSafeCompare(this.getSite(), other.getSite()) == 0) {
if (this.getPriority() != other.getPriority()) {
return this.getPriority() - other.getPriority();
}
return this.getPdpId().compareTo(other.getPdpId());
} else {
- return nullSafeCompare(this.getSite(),other.getSite());
+ return nullSafeCompare(this.getSite(), other.getSite());
}
}
}
logger.debug("INFO: DesignatedWaiter.run: PDP= {} "
+ "designated= {}, current= {}, "
+ "designatedPdpHasFailed= {}, "
- + "standbyStatus= {}",pdp.getPdpId(),
+ + "standbyStatus= {}", pdp.getPdpId(),
pdp.isDesignated(), false, designatedPdpHasFailed, standbyStatus);
pdpNotDesignatedNotCurrent(pdp, standbyStatus);
}
} else { //it is a remote PDP that is failed
logger.debug("\n\nDesignatedWaiter.run: PDP {} is not Current. "
+ " Executing stateManagement.disableFailed(otherResourceName)\n\n",
- pdp.getPdpId() );
+ pdp.getPdpId());
// We found a PDP is designated but not current
// We already called standdown(pdp) which will change designated to false
// Now we need to disableFail it to get its states in synch. The standbyStatus
private void designateNoPdp() {
// Just to be sure the parameters are correctly set
myPdp.setDesignated(false);
- pdpsConnector.setDesignated(myPdp,false);
+ pdpsConnector.setDesignated(myPdp, false);
isDesignated = false;
waitTimerLastRunDate = currentTime.getDate();
logger.error("ERROR: DesignatedWaiter.run: Caught Exception attempting to promote PDP={}"
+ ", message=", myPdp.getPdpId(), e);
myPdp.setDesignated(false);
- pdpsConnector.setDesignated(myPdp,false);
+ pdpsConnector.setDesignated(myPdp, false);
isDesignated = false;
//If you can't promote it, demote it
try {
List<DroolsPdp> listForRemoval = new ArrayList<>();
for (DroolsPdp pdp : listOfDesignated) {
logger.debug("DesignatedWaiter.run sanitizing: pdp = {}"
- + " isDesignated = {}",pdp.getPdpId(), pdp.isDesignated());
+ + " isDesignated = {}", pdp.getPdpId(), pdp.isDesignated());
if (pdp.isDesignated()) {
containsDesignated = true;
} else {
}
// If the rejectedPdp is myPdp, we need to stand it down and demote it. Each pdp is responsible
// for demoting itself
- if (rejectedPdp != null && nullSafeEquals(rejectedPdp.getPdpId(),myPdp.getPdpId())) {
+ if (rejectedPdp != null && nullSafeEquals(rejectedPdp.getPdpId(), myPdp.getPdpId())) {
logger.debug("\n\nDesignatedWaiter.run: myPdp: {} listOfDesignated myPdp ID: {}"
+ " is NOT the lowest priority. Executing stateManagement.demote()\n\n",
myPdp.getPdpId(),
return null;
} else {
if (pdp.getPdpId().equals((lowestPrioritySameSite.getPdpId()))) {
- return null;//nothing to compare
+ return null; //nothing to compare
}
if (pdp.comparePriority(lowestPrioritySameSite) < 0) {
logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {}"
- + " has lower priority than pdp ID: {}",myPdp.getPdpId(), pdp.getPdpId(),
+ + " has lower priority than pdp ID: {}", myPdp.getPdpId(), pdp.getPdpId(),
lowestPrioritySameSite.getPdpId());
//we need to reject lowestPrioritySameSite
DroolsPdp rejectedPdp = lowestPrioritySameSite;
} else {
//we need to reject pdp and keep lowestPrioritySameSite
logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {} "
- + " has higher priority than pdp ID: {}", myPdp.getPdpId(),pdp.getPdpId(),
+ + " has higher priority than pdp ID: {}", myPdp.getPdpId(), pdp.getPdpId(),
lowestPrioritySameSite.getPdpId());
return pdp;
}
return null;
}
if (pdp.getPdpId().equals((lowestPriorityDifferentSite.getPdpId()))) {
- return null;//nothing to compare
+ return null; //nothing to compare
}
if (pdp.comparePriority(lowestPriorityDifferentSite) < 0) {
logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {}"
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
-
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
continue;
}
//Make sure it is not a cached version
- DroolsPdp droolsPdp = (DroolsPdp)o;
+ DroolsPdp droolsPdp = (DroolsPdp) o;
em.refresh(droolsPdp);
droolsPdpsReturnList.add(droolsPdp);
if (logger.isDebugEnabled()) {
.setFlushMode(FlushModeType.COMMIT).getResultList();
DroolsPdpEntity droolsPdpEntity;
if (droolsPdpsList.size() == 1 && (droolsPdpsList.get(0) instanceof DroolsPdpEntity)) {
- droolsPdpEntity = (DroolsPdpEntity)droolsPdpsList.get(0);
+ droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0);
em.refresh(droolsPdpEntity); //Make sure we have current values
Date currentDate = currentTime.getDate();
long difference = currentDate.getTime() - droolsPdpEntity.getUpdatedDate().getTime();
if (!droolsPdpEntity.getUpdatedDate().equals(pdp.getUpdatedDate())) {
droolsPdpEntity.setUpdatedDate(pdp.getUpdatedDate());
}
- if (!nullSafeEquals(droolsPdpEntity.getSite(),pdp.getSite())) {
+ if (!nullSafeEquals(droolsPdpEntity.getSite(), pdp.getSite())) {
droolsPdpEntity.setSite(pdp.getSite());
}
if (droolsPdpsList.size() == 1 && droolsPdpsList.get(0) instanceof DroolsPdpEntity) {
logger.debug("isPdpCurrent: PDP={} designated but not current; setting designated to false",
pdp.getPdpId());
- DroolsPdpEntity droolsPdpEntity = (DroolsPdpEntity)droolsPdpsList.get(0);
+ DroolsPdpEntity droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0);
droolsPdpEntity.setDesignated(false);
em.getTransaction().commit();
} else {
droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0);
droolsPdpEntity.setDesignated(false);
em.persist(droolsPdpEntity);
- logger.debug("standDownPdp: PDP={} persisted as non-designated.", pdpId );
+ logger.debug("standDownPdp: PDP={} persisted as non-designated.", pdpId);
} else {
logger.error("standDownPdp: Missing record in droolspdpentity for pdpId={}"
+ "; cannot stand down PDP", pdpId);
String userDir = System.getProperty("user.dir");
logger.debug("setUpClass: userDir={}", userDir);
System.setProperty("com.sun.management.jmxremote.port", "9980");
- System.setProperty("com.sun.management.jmxremote.authenticate","false");
+ System.setProperty("com.sun.management.jmxremote.authenticate", "false");
DroolsPdpsElectionHandler.setIsUnitTesting(true);
package org.onap.policy.drools.activestandby;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import java.util.Date;
import lombok.Setter;
import org.junit.Before;
import org.junit.Test;
-import org.onap.policy.drools.activestandby.DroolsPdp;
-import org.onap.policy.drools.activestandby.DroolsPdpObject;
public class DroolsPdpObjectTest {
private static final String PDP_ID = "my-id";
@Test
public void testEqualsObject() {
// self
- assertEquals(pdp,pdp);
+ assertEquals(pdp, pdp);
// same id
MyPdp pdp2 = new MyPdp();
pdp2.setPdpId(PDP_ID);
- assertEquals(pdp,pdp2);
+ assertEquals(pdp, pdp2);
// different id
pdp2.setPdpId(PDP_ID2);
- assertNotEquals(pdp,pdp2);
+ assertNotEquals(pdp, pdp2);
// different type of object
- assertNotEquals(pdp,"");
+ assertNotEquals(pdp, "");
}
@Test
String userDir = System.getProperty("user.dir");
logger.debug("setUpClass: userDir={}", userDir);
System.setProperty("com.sun.management.jmxremote.port", "9980");
- System.setProperty("com.sun.management.jmxremote.authenticate","false");
+ System.setProperty("com.sun.management.jmxremote.authenticate", "false");
saveTime = Whitebox.getInternalState(MonitorTime.class, MONITOR_FIELD_NAME);
saveFactory = Factory.getInstance();
listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated);
- logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size = {}\n\n",listOfDesignated.size());
+ logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size = {}\n\n", listOfDesignated.size());
assertEquals(4, listOfDesignated.size());
sm.deleteAllStateManagementEntities();
- sm = new StateManagement(emfx, activePdpId);//pdp2
+ sm = new StateManagement(emfx, activePdpId); //pdp2
// Artificially putting a PDP into service is really a two step process, 1)
// inserting it as designated and 2) promoting it so that its standbyStatus
//At this point, the newly created pdp will have set the state to disabled/failed/cold standby
//because it is stale. So, it cannot be promoted. We need to call sm.enableNotFailed() so we
//can promote it and demote the other pdp - else the other pdp will just spring back to providingservice
- sm.enableNotFailed();//pdp2
+ sm.enableNotFailed(); //pdp2
sm.promote();
String standbyStatus = sm.getStandbyStatus(activePdpId);
logger.info("testHotStandby2: After promoting, PDP= {} has standbyStatus= {}", activePdpId, standbyStatus);
// demoting PDP should ensure that state transits to hotstandby
logger.info("testHotStandby2: Runner started; demoting PDP= {}", thisPdpId);
- sm2.demote();//pdp1
+ sm2.demote(); //pdp1
standbyStatus = sm.getStandbyStatus(thisPdpId);
- logger.info("testHotStandby2: After demoting, PDP={} has standbyStatus= {}",thisPdpId , standbyStatus);
+ logger.info("testHotStandby2: After demoting, PDP={} has standbyStatus= {}", thisPdpId, standbyStatus);
logger.info("testHotStandby2: Sleeping {} ms, to allow JpaDroolsPdpsConnector "
+ "time to check droolspdpentity table", SLEEP_TIME);
sleep(SLEEP_TIME);
logger.debug("testLocking1: Waking up and invoking startTransaction on active PDP={}"
- + ", designated= {}",thisPdpId, conn.getPdp(thisPdpId).isDesignated());
+ + ", designated= {}", thisPdpId, conn.getPdp(thisPdpId).isDesignated());
IntegrityMonitor droolsPdpIntegrityMonitor = IntegrityMonitor.getInstance();
sleep(100);
logger.debug("testLocking1: Invoking startTransaction on locked PDP= {}"
- + ", designated= {}",thisPdpId, conn.getPdp(thisPdpId).isDesignated());
+ + ", designated= {}", thisPdpId, conn.getPdp(thisPdpId).isDesignated());
try {
droolsPdpIntegrityMonitor.startTransaction();
logger.error("testLocking1: startTransaction unexpectedly successful");
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import org.kie.api.runtime.rule.FactHandle;
-
import org.onap.policy.drools.core.PolicySession;
import org.onap.policy.drools.core.PolicySessionFeatureApi;
import org.onap.policy.drools.system.PolicyEngineConstants;
import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
-
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
}
protected boolean updatePoliciesAction(List<ToscaPolicy> toscaPolicies) {
- return (this.scheduler.submit( () -> state.updatePolicies(toscaPolicies)) != null);
+ return (this.scheduler.submit(() -> state.updatePolicies(toscaPolicies)) != null);
}
/* ** Action Helpers ** */
@Override
protected boolean stateChangeToActive(@NonNull PdpStateChange change) {
fsm.transitionToAction(new LifecycleStateActive(fsm));
- fsm.statusAction(response(change.getRequestId(), PdpResponseStatus.SUCCESS,null));
+ fsm.statusAction(response(change.getRequestId(), PdpResponseStatus.SUCCESS, null));
return fsm.updatePoliciesAction(fsm.resetPoliciesAction());
}
@Override
protected boolean stateChangeToPassive(@NonNull PdpStateChange change) {
- return fsm.statusAction(response(change.getRequestId(), PdpResponseStatus.SUCCESS,null));
+ return fsm.statusAction(response(change.getRequestId(), PdpResponseStatus.SUCCESS, null));
}
@Override
List<ToscaPolicy> policies =
LifecycleFeature.fsm.getPoliciesMap().values().stream().collect(Collectors.toList());
- policies.removeIf(aPolicy -> policy.getIdentifier().equals(aPolicy.getIdentifier()));
+ policies.removeIf(otherPolicy -> policy.getIdentifier().equals(otherPolicy.getIdentifier()));
return Response.status(Response.Status.OK)
.entity(LifecycleFeature.fsm.update(getPolicyUpdate(policies)))
.build();
assertTrue(PolicyControllerConstants.getFactory().get("lifecycle").getDrools().isBrained());
assertEquals(1,
PolicyControllerConstants
- .getFactory().get("lifecycle").getDrools().facts("junits", ToscaPolicy.class) .size());
+ .getFactory().get("lifecycle").getDrools().facts("junits", ToscaPolicy.class).size());
resourceLists("policies", 3);
get("policies/" + opPolicy.getName() + "/" + opPolicy.getVersion(), Status.OK.getStatusCode());
Status.OK.getStatusCode(), Boolean.TRUE);
assertEquals(0,
PolicyControllerConstants
- .getFactory().get("lifecycle").getDrools().facts("junits", ToscaPolicy.class) .size());
+ .getFactory().get("lifecycle").getDrools().facts("junits", ToscaPolicy.class).size());
resourceLists("policies", 2);
get("policies/" + opPolicy.getName() + "/" + opPolicy.getVersion(), Status.NOT_FOUND.getStatusCode());
booleanPost("policies/operations/deployment", toString(opPolicy), Status.OK.getStatusCode(), Boolean.TRUE);
assertEquals(1,
PolicyControllerConstants
- .getFactory().get("lifecycle").getDrools().facts("junits", ToscaPolicy.class) .size());
+ .getFactory().get("lifecycle").getDrools().facts("junits", ToscaPolicy.class).size());
resourceLists("policies", 2);
get("policies/" + opPolicy.getName() + "/" + opPolicy.getVersion(), Status.NOT_FOUND.getStatusCode());
"policies/operations/undeployment", toString(opPolicy), Status.OK.getStatusCode(), Boolean.TRUE);
assertEquals(0,
PolicyControllerConstants
- .getFactory().get("lifecycle").getDrools().facts("junits", ToscaPolicy.class) .size());
+ .getFactory().get("lifecycle").getDrools().facts("junits", ToscaPolicy.class).size());
resourceLists("policies", 2);
get("policies/" + opPolicy.getName() + "/" + opPolicy.getVersion(), Status.NOT_FOUND.getStatusCode());
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
- modifiers.setInt(fsmField, fsmField.getModifiers() & ~Modifier.FINAL );
+ modifiers.setInt(fsmField, fsmField.getModifiers() & ~Modifier.FINAL);
LifecycleFsm fsm = new LifecycleFsm();
fsmField.set(null, fsm);
package org.onap.policy.drools.pooling;
import java.util.List;
-
import org.onap.policy.common.endpoints.event.comm.FilterableTopicSource;
import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* <dt>PolicyEngine, PolicyController, DroolsController</dt>
* <dd>mocked</dd>
* </dl>
- *
+ *
* <p>Invoke {@link #runSlow()}, before the test, to slow things down.
*/
public class FeatureTest {
private String makeMessage(int reqnum) {
return "{\"reqid\":\"req" + reqnum + "\", \"data\":\"hello " + reqnum + "\"}";
}
-
+
/**
* Invoke this to slow the timers down.
*/
/**
* Decodes an event.
- *
+ *
* @param event event
* @return the decoded event, or {@code null} if it cannot be decoded
*/
/**
* Constructor.
- *
+ *
* @param nEvents number of events to be processed
*/
public Context(int events) {
/**
* Creates and adds a new host to the context.
- *
+ *
* @return the new Host
*/
public Host addHost() {
/**
* Sets {@link #currentHost} to the specified host, and then invokes the given
* function. Resets {@link #currentHost} to {@code null} before returning.
- *
+ *
* @param host host
* @param func function to invoke
*/
/**
* Offers an event to the external topic.
- *
+ *
* @param event event
*/
public void offerExternal(String event) {
/**
* Adds an internal channel to the set of channels.
- *
+ *
* @param channel channel
* @param queue the channel's queue
*/
/**
* Offers a message to all internal channels.
- *
+ *
* @param message message
*/
public void offerInternal(String message) {
/**
* Offers amessage to an internal channel.
- *
+ *
* @param channel channel
* @param message message
*/
/**
* Associates a controller with its drools controller.
- *
+ *
* @param controller controller
* @param droolsController drools controller
*/
/**
* Get controller.
- *
+ *
* @param droolsController drools controller
* @return the controller associated with a drools controller, or {@code null} if
* it has no associated controller
/**
* Constructor.
- *
+ *
* @return queue for the external topic
*/
public BlockingQueue<String> getExternalTopic() {
/**
* Get decode errors.
- *
+ *
* @return the number of decode errors so far
*/
public int getDecodeErrors() {
/**
* Get remaining events.
- *
+ *
* @return the number of events that haven't been processed
*/
public long getRemainingEvents() {
/**
* Waits, for a period of time, for all events to be processed.
- *
+ *
* @param time time
* @param units units
* @return {@code true} if all events have been processed, {@code false} otherwise
/**
* Gets the current host, provided this is used from within a call to
* {@link #withHost(Host, VoidFunction)}.
- *
+ *
* @return the current host, or {@code null} if there is no current host
*/
public Host getCurrentHost() {
/**
* Constructor.
- *
+ *
* @param context context
*/
public Host(Context context) {
// arrange to read from the external topic
externalSource = new TopicSourceImpl(context, false);
-
+
feature = new PoolingFeatureImpl(context);
}
/**
* Get name.
- *
+ *
* @return the host name
*/
public String getName() {
/**
* Offers an event to the feature, before the policy controller handles it.
- *
+ *
* @param protocol protocol
* @param topic2 topic
* @param event event
/**
* Offers an event to the feature, after the policy controller handles it.
- *
+ *
* @param protocol protocol
* @param topic topic
* @param event event
/**
* Offers an event to the feature, before the drools controller handles it.
- *
+ *
* @param fact fact
* @return {@code true} if the event was handled, {@code false} otherwise
*/
/**
* Offers an event to the feature, after the drools controller handles it.
- *
+ *
* @param fact fact
* @param successInsert {@code true} if it was successfully inserted by the drools
* controller, {@code false} otherwise
/**
* Message seen.
- *
+ *
* @return {@code true} if a message was seen for this host, {@code false}
* otherwise
*/
/**
* Get internal queue.
- *
+ *
* @return the queue associated with this host's internal topic
*/
public BlockingQueue<String> getInternalQueue() {
/**
* Constructor.
- *
+ *
* @param context context
*/
public TopicSinkImpl(Context context) {
/**
* Constructor.
- *
+ *
* @param context context
* @param internal {@code true} if to read from the internal topic, {@code false}
* to read from the external topic
try {
do {
processMessages(newPair.first(), listener);
- }
- while (!newPair.first().await(stdInterPollMs, TimeUnit.MILLISECONDS));
+ } while (!newPair.first().await(stdInterPollMs, TimeUnit.MILLISECONDS));
logger.info("topic source thread completed");
/**
* Registers a new "pair" with this source, stopping the consumer associated with
* any previous registration.
- *
+ *
* @param newPair the new "pair", or {@code null} to unregister
*/
private void reregister(Pair<CountDownLatch, CountDownLatch> newPair) {
/**
* Polls for messages from the topic and offers them to the listener.
- *
+ *
* @param stopped triggered if processing should stop
* @param listener listener
* @throws InterruptedException throws interrupted exception
/**
* Constructor.
- *
+ *
* @param context context
*/
public PoolingFeatureImpl(Context context) {
/**
* Embeds a specializer within a property name, after the prefix.
- *
+ *
* @param propnm property name into which it should be embedded
* @param spec specializer to be embedded
* @return the property name, with the specializer embedded within it
CountDownLatch activeLatch) {
currentContext.set(context);
-
+
return new PoolingManagerTest(host, controller, props, activeLatch);
}
}
/**
* Constructor.
- *
+ *
* @param host the host
* @param controller the controller
* @param props the properties
/**
* Constructor.
- *
+ *
* @param context this manager's context
* @param topic the topic
* @throws PoolingFeatureException if an error occurs
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
public class MapExtractorTest {
private static final String KEY = "a.key";
private static final String VALUE = "a.value";
-
+
private MapExtractor ext;
-
+
@Before
public void setUp() {
- ext = new MapExtractor(KEY);
+ ext = new MapExtractor(KEY);
}
@Test
public void testExtract_NotAMap() {
-
+
// object is not a map (i.e., it's a String)
assertNull(ext.extract(KEY));
}
@Test
public void testExtract_MissingValue() {
- Map<String,Object> map = new HashMap<>();
+ Map<String, Object> map = new HashMap<>();
map.put(KEY + "x", VALUE + "x");
-
+
// object is a map, but doesn't have the key
assertNull(ext.extract(map));
}
@Test
public void testExtract() {
- Map<String,Object> map = new HashMap<>();
+ Map<String, Object> map = new HashMap<>();
map.put(KEY + "x", VALUE + "x");
map.put(KEY, VALUE);
-
+
// object is a map and contains the key
assertEquals(VALUE, ext.extract(map));
-
+
// change to value to a different type
map.put(KEY, 20);
assertEquals(20, ext.extract(map));
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@Test
public void testRemoveExcessHosts() {
- /**
+ /*
* All hosts are still alive, plus some others.
*/
state.setAssignments(ASGN3);
@Test
public void testRebalanceBuckets() {
- /**
+ /*
* Some are very lopsided.
*/
String[] asgn = {MY_HOST, HOST1, MY_HOST, MY_HOST, MY_HOST, MY_HOST, HOST1, HOST2, HOST1, HOST3};
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
static {
// create hash bucket entries, but there are no assignments yet
- for (int i = 0 ; i < indexToBucket.length ; i += 1) {
+ for (int i = 0; i < indexToBucket.length; i += 1) {
Bucket bucket = new Bucket(i);
indexToBucket[i] = bucket;
}
* current host.
*/
UUID key = oldHost.uuid;
- for (int count = new Random().nextInt(rb.testServers.size() - 1) ;
- count >= 0 ; count -= 1) {
+ for (int count = new Random().nextInt(rb.testServers.size() - 1); count >= 0; count -= 1) {
key = rb.testServers.higherKey(key);
if (key == null) {
// wrap to the beginning of the list
}
}
- /********************************************/
- /* Comparable<AdjustedTestServer> interface */
- /********************************************/
+ /* ****************************************** */
+ /* Comparable<AdjustedTestServer> interface */
+ /* ****************************************** */
/**
* {@inheritDoc}
TestBucket[] buckets = new TestBucket[indexToBucket.length];
// this table resembles the 'Server.servers' table
- TreeMap<UUID,TestServer> testServers = new TreeMap<>(Util.uuidComparator);
+ TreeMap<UUID, TestServer> testServers = new TreeMap<>(Util.uuidComparator);
/* this is a special server instance, which is allocated any
* owned, primary, or secondary buckets that haven't been allocated to
*/
Callable<Integer> callable = () -> {
// copy the 'Bucket' table
- for (int i = 0 ; i < indexToBucket.length; i += 1) {
+ for (int i = 0; i < indexToBucket.length; i += 1) {
// makes a snapshot of the bucket information
Bucket bucket = indexToBucket[i];
if (primaryBackup != null
&& !Objects.equals(siteSocketAddress,
primaryBackup.siteSocketAddress)) {
- /**
+ /*
* primary backup is from the wrong site -- see if we can
* use the secondary.
*/
DataOutputStream dos = new DataOutputStream(bos);
// go through the entire 'buckets' table
- for (int i = 0 ; i < buckets.length ; i += 1) {
+ for (int i = 0; i < buckets.length; i += 1) {
// fetch the 'TestBucket' associated with index 'i'
TestBucket testBucket = buckets[i];
final Entity<String> entity =
Entity.entity(new String(Base64.getEncoder().encode(packet),
StandardCharsets.UTF_8), MediaType.APPLICATION_OCTET_STREAM_TYPE);
- /**
+ /*
* This method is running within the 'MainLoop' thread.
*/
Runnable task = () -> {
}
}
- /*********************/
- /* 'State' interface */
- /*********************/
+ /* ******************* */
+ /* 'State' interface */
+ /* ******************* */
/**
* {@inheritDoc}
}
}
- /**********************/
- /* 'Thread' interface */
- /**********************/
+ /* ******************** */
+ /* 'Thread' interface */
+ /* ******************** */
/**
* {@inheritDoc}
*/
private void restoreBucketData(Object obj) {
if (obj instanceof List) {
- for (Object entry : (List<?>)obj) {
+ for (Object entry : (List<?>) obj) {
if (entry instanceof Restore) {
// entry-specific 'restore' operation
- ((Restore)entry).restore(Bucket.this.index);
+ ((Restore) entry).restore(Bucket.this.index);
} else {
logger.error("{}: Expected '{}' but got '{}'",
this, Restore.class.getName(),
start();
}
- /*********************/
- /* 'State' interface */
- /*********************/
+ /* ******************* */
+ /* 'State' interface */
+ /* ******************* */
/**
* {@inheritDoc}
logger.error("{}: 'bulkSerializedData()' shouldn't be called in this state", this);
}
- /**********************/
- /* 'Thread' interface */
- /**********************/
+ /* ******************** */
+ /* 'Thread' interface */
+ /* ******************** */
/**
* {@inheritDoc}
import static org.onap.policy.drools.serverpool.ServerPoolProperties.getProperty;
import com.google.gson.Gson;
-
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Properties;
-
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
import org.onap.policy.common.endpoints.event.comm.TopicListener;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import lombok.AllArgsConstructor;
-
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
* table[0] = {"requestID"}
* table[1] = {"CommonHeader", "RequestID"}
*/
- private static HashMap<String,String[][]> topicToPaths = new HashMap<>();
+ private static HashMap<String, String[][]> topicToPaths = new HashMap<>();
// this table is used for any topics that aren't in 'topicToPaths'
private static String[][] defaultPaths = new String[0][];
private static final String QP_PROTOCOL = "protocol";
private static final String QP_TOPIC = "topic";
- /******************************/
- /* 'OrderedService' interface */
- /******************************/
+ /* **************************** */
+ /* 'OrderedService' interface */
+ /* **************************** */
/**
* {@inheritDoc}
return -1000000;
}
- /**************************************/
- /* 'PolicyEngineFeatureApi' interface */
- /**************************************/
+ /* ************************************ */
+ /* 'PolicyEngineFeatureApi' interface */
+ /* ************************************ */
/**
* {@inheritDoc}
return true;
}
- /******************************************/
- /* 'PolicyControllerFeatureApi' interface */
- /******************************************/
+ /* **************************************** */
+ /* 'PolicyControllerFeatureApi' interface */
+ /* **************************************** */
/**
* This method is called from 'AggregatedPolicyController.onTopicEvent',
* TBD: it would be nice to limit the number of hops, in case we
* somehow have a loop.
*/
- ((TopicListener)controller).onTopicEvent(
+ ((TopicListener) controller).onTopicEvent(
CommInfrastructure.valueOf(protocol), topic, event);
} else {
/*
// Example: requestID,CommonHeader.RequestID
String[] commaSeparatedEntries = prop.getProperty(name).split(",");
String[][] paths = new String[commaSeparatedEntries.length][];
- for (int i = 0 ; i < commaSeparatedEntries.length ; i += 1) {
+ for (int i = 0; i < commaSeparatedEntries.length; i += 1) {
paths[i] = commaSeparatedEntries[i].split("\\.");
}
* TBD: it would be nice to limit the number of hops, in case we
* somehow have a loop.
*/
- ((TopicListener)controller).onTopicEvent(protocol, topic, event);
+ ((TopicListener) controller).onTopicEvent(protocol, topic, event);
} else {
/*
* This 'PolicyController' was also a 'TopicListener' on the sender's
* This class is used to generate and restore backup Drools data.
*/
static class DroolsSessionRestore implements Bucket.Restore, Serializable {
+ private static final long serialVersionUID = 1L;
+
// backup data for all Drools sessions on this host
private final List<SingleSession> sessions = new LinkedList<>();
}
}
- /**
+ /*
* data copying can start as soon as we receive results
* from pending sessions (there may not be any)
*/
PolicySession session = pair.second();
long delay = endTime - System.currentTimeMillis();
if (delay < 0) {
- /**
+ /*
* we have already reached the time limit, so we will
* only process data that has already been received
*/
* been backed up, or is being restored.
*/
static class SingleSession implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// the group id associated with the Drools container
String groupId;
Object obj = ois.readObject();
if (obj instanceof List) {
- final List<?> droolsObjects = (List<?>)obj;
+ final List<?> droolsObjects = (List<?>) obj;
logger.info("{}: session={}, got {} object(s)",
this, session.getFullName(), droolsObjects.size());
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
-
import lombok.AllArgsConstructor;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// this table maps class name to a sequence of method calls and field
// references, based upon 'keyword.<CLASS-NAME>.lookup' entries found
// in the property list
- private static Map<String,String> classNameToSequence = null;
+ private static Map<String, String> classNameToSequence = null;
static final String KEYWORD_PROPERTY_START = "keyword.";
static final String KEYWORD_PROPERTY_END = ".lookup";
*/
private static Class<?> buildReflectiveLookup_findKeyClass(Class<?> clazz) {
Class<?> keyClass = null;
- for (Class<?> cl = clazz ; cl != null ; cl = cl.getSuperclass()) {
+ for (Class<?> cl = clazz; cl != null; cl = cl.getSuperclass()) {
if (classNameToSequence.containsKey(cl.getName())) {
// matches the class
keyClass = cl;
// we found a matching key in the table -- now, process the values
Class<?> currentClass = keyClass;
- /**
+ /*
* there may potentially be a chain of entries if multiple
* field and/or method calls are in the sequence -- this is the first
*/
// this is the last entry in the list
ReflectiveLookup last = null;
- /**
+ /*
* split the value into segments, where each segment has the form
* 'FIELD-NAME' or 'METHOD-NAME()', with an optional ':CONVERSION'
* at the end
field = clazz.getField(segment);
}
- /********************************/
- /* 'ReflectiveLookup' interface */
- /********************************/
+ /* ****************************** */
+ /* 'ReflectiveLookup' interface */
+ /* ****************************** */
/**
* {@inheritDoc}
return field.getType();
}
- /**********************/
- /* 'Lookup' interface */
- /**********************/
+ /* ******************** */
+ /* 'Lookup' interface */
+ /* ******************** */
/**
* {@inheritDoc}
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TimeUnit;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
-
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.glassfish.jersey.client.ClientProperties;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.http.client.HttpClient;
possibleError = "HTTP server initialization error";
restServer = HttpServletServerFactoryInstance.getServerFactory().build(
- "SERVER-POOL", // name
- useHttps, // https
- socketAddress.getAddress().getHostAddress(),// host (maybe 0.0.0.0)
- port, // port (can no longer be 0)
- null, // contextPath
- false, // swagger
- false); // managed
+ "SERVER-POOL", // name
+ useHttps, // https
+ socketAddress.getAddress().getHostAddress(), // host (maybe 0.0.0.0)
+ port, // port (can no longer be 0)
+ null, // contextPath
+ false, // swagger
+ false); // managed
restServer.addServletClass(null, RestServerPool.class.getName());
// add any additional servlets
// TBD: We need a way to get this information without reflection
Field field = client.getClass().getDeclaredField("client");
field.setAccessible(true);
- Client rsClient = (Client)field.get(client);
+ Client rsClient = (Client) field.get(client);
field.setAccessible(false);
rsClient.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
}
getThreadPool().execute(() -> {
- /**
+ /*
* This method is running within the 'MainLoop' thread.
*/
try {
package org.onap.policy.drools.serverpool;
import java.util.Collection;
-
import org.onap.policy.common.utils.services.OrderedService;
import org.onap.policy.common.utils.services.OrderedServiceImpl;
package org.onap.policy.drools.serverpool;
import java.util.Properties;
-
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.onap.policy.drools.serverpool;
-import static org.junit.Assert.assertTrue;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DEFAULT_LOCK_AUDIT_GRACE_PERIOD;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DEFAULT_LOCK_AUDIT_PERIOD;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DEFAULT_LOCK_AUDIT_RETRY_DELAY;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import lombok.EqualsAndHashCode;
-import lombok.NonNull;
import org.onap.policy.drools.core.DroolsRunnable;
import org.onap.policy.drools.core.PolicyContainer;
import org.onap.policy.drools.core.PolicySession;
* owned by the host containing the entry.
*/
public class TargetLock implements Lock, Serializable {
+ private static final long serialVersionUID = 1L;
+
private static Logger logger = LoggerFactory.getLogger(TargetLock.class);
// Listener class to handle state changes that require restarting the audit
context = new PolicySessionContext(session);
session.setAdjunct(PolicySessionContext.class, context);
} else {
- context = (LockCallback)lcontext;
+ context = (LockCallback) lcontext;
}
} else {
// no context to deliver through -- call back directly to owner
logger.info("Lock response={} (code={})",
response, response.getStatus());
- /**
+ /*
* there are three possible responses:
* 204 No Content - operation was successful
* 202 Accepted - operation is still in progress
});
}
- /********************/
- /* 'Lock' Interface */
- /********************/
+ /* ****************** */
+ /* 'Lock' Interface */
+ /* ****************** */
/**
* This method will free the current lock, or remove it from the waiting
// not implemented yet
}
- /********************/
+ /* ****************** */
/**
* Update the state.
+ ", state=" + state + ")";
}
- /*****************/
- /* Serialization */
- /*****************/
+ /* *************** */
+ /* Serialization */
+ /* *************** */
/**
* This method modifies the behavior of 'TargetLock' deserialization by
/* ============================================================ */
private static class LockFactory implements PolicyResourceLockManager {
- /*****************************************/
- /* 'PolicyResourceLockManager' interface */
- /*****************************************/
+ /* *************************************** */
+ /* 'PolicyResourceLockManager' interface */
+ /* *************************************** */
/**
* {@inheritDoc}
return new TargetLock(resourceId, ownerKey, callback, waitForLock);
}
- /*************************/
- /* 'Startable' interface */
- /*************************/
+ /* *********************** */
+ /* 'Startable' interface */
+ /* *********************** */
/**
* {@inheritDoc}
return true;
}
- /************************/
- /* 'Lockable' interface */
- /************************/
+ /* ********************** */
+ /* 'Lockable' interface */
+ /* ********************** */
/**
* {@inheritDoc}
*/
@EqualsAndHashCode
private static class Identity implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// this is the key associated with the lock
String key;
* the callback to 'TargetLock.owner' runs within the Drools thread.
*/
private static class PolicySessionContext implements LockCallback, Serializable {
+ private static final long serialVersionUID = 1L;
+
// the 'PolicySession' instance in question
PolicySession policySession;
this.policySession = policySession;
}
- /*********************/
- /* 'Owner' interface */
- /*********************/
+ /* ******************* */
+ /* 'Owner' interface */
+ /* ******************* */
/**
* {@inheritDoc}
// Run 'owner.lockAvailable' within the Drools session
if (policySession != null) {
DroolsRunnable callback = () -> {
- ((TargetLock)lock).owner.lockAvailable(lock);
+ ((TargetLock) lock).owner.lockAvailable(lock);
};
policySession.getKieSession().insert(callback);
}
// Run 'owner.unlockAvailable' within the Drools session
if (policySession != null) {
DroolsRunnable callback = () -> {
- ((TargetLock)lock).owner.lockUnavailable(lock);
+ ((TargetLock) lock).owner.lockUnavailable(lock);
};
policySession.getKieSession().insert(callback);
}
}
- /*****************/
- /* Serialization */
- /*****************/
+ /* *************** */
+ /* Serialization */
+ /* *************** */
/**
* Specializes serialization of 'PolicySessionContext'.
* of the lock implementation.
*/
public static class GlobalLocks implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// this is the lock table, mapping 'key' to 'LockEntry', which indicates
// the current lock holder, and all those waiting
private Map<String, LockEntry> keyToEntry = new HashMap<>();
* any that are waiting.
*/
private static class LockEntry implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// string key identifying the lock
private String key;
* This corresponds to a member of 'LockEntry.waitingList'
*/
private static class Waiting implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// string key identifying the owner
String ownerKey;
* This class is used to restore a 'GlobalLocks' instance from a backup.
*/
static class LockRestore implements Bucket.Restore, Serializable {
+ private static final long serialVersionUID = 1L;
+
GlobalLocks globalLocks;
/**
// here. The alternative is to add some additional information
// to make this mapping quick, at the expense of a slight
// slow down of normal lock operations.
- for (int i = 0 ; i < Bucket.BUCKETCOUNT ; i += 1) {
+ for (int i = 0; i < Bucket.BUCKETCOUNT; i += 1) {
LocalLocks localLocks =
Bucket.getBucket(i).getAdjunctDontCreate(LocalLocks.class);
if (localLocks != null) {
Object decodedData = Util.deserialize(Base64.getDecoder().decode(data));
if (decodedData instanceof HostData) {
// deserialized data
- HostData hostData = (HostData)decodedData;
+ HostData hostData = (HostData) decodedData;
// fetch 'Server' instance associated with the responding server
Server server = Server.getServer(hostData.hostUuid);
* host that is consolidating the information for display.
*/
static class HostData implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// the UUID of the host sending the data
private UUID hostUuid;
serverDataList = new ArrayList<ServerData>();
// go through buckets
- for (int i = 0 ; i < Bucket.BUCKETCOUNT ; i += 1) {
+ for (int i = 0; i < Bucket.BUCKETCOUNT; i += 1) {
Bucket bucket = Bucket.getBucket(i);
// client data
* Information derived from the 'LocalLocks' adjunct to a single bucket.
*/
static class ClientData implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// number of the bucket
private int bucketNumber;
* single 'TargetLock'.
*/
static class ClientDataRecord implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// contains key, ownerKey, uuid
private Identity identity;
* Information derived from the 'GlobalLocks' adjunct to a single bucket.
*/
static class ServerData implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// number of the bucket
private int bucketNumber;
* 'TargetLock' audit.
*/
static class AuditData implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// sending UUID
private UUID hostUuid;
Object decodedData =
Util.deserialize(Base64.getDecoder().decode(encodedData));
if (decodedData instanceof AuditData) {
- return (AuditData)decodedData;
+ return (AuditData) decodedData;
} else {
logger.error(
"TargetLock.AuditData.decode returned instance of class {}",
static TimerTask timerTask = null;
// maps 'Server' to audit data associated with that server
- Map<Server,AuditData> auditMap = new IdentityHashMap<>();
+ Map<Server, AuditData> auditMap = new IdentityHashMap<>();
/**
* Run a single audit cycle.
* remote server.
*/
void build() {
- for (int i = 0 ; i < Bucket.BUCKETCOUNT ; i += 1) {
+ for (int i = 0; i < Bucket.BUCKETCOUNT; i += 1) {
Bucket bucket = Bucket.getBucket(i);
// client data
import java.util.Comparator;
import java.util.Timer;
import java.util.UUID;
-
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
-
import org.kie.api.event.rule.ObjectDeletedEvent;
import org.kie.api.event.rule.ObjectInsertedEvent;
import org.kie.api.event.rule.ObjectUpdatedEvent;
private static final String QP_COUNT = "count";
private static final String QP_DEST = "dest";
- /***************************************/
- /* 'PolicySessionFeatureApi' interface */
- /***************************************/
+ /* ************************************* */
+ /* 'PolicySessionFeatureApi' interface */
+ /* ************************************* */
/**
* {@inheritDoc}
}
}
- /*****************************/
- /* 'ServerPoolApi' interface */
- /*****************************/
+ /* *************************** */
+ /* 'ServerPoolApi' interface */
+ /* *************************** */
/**
* {@inheritDoc}
for (PolicySession session : sbd.sessionData.keySet()) {
Object obj = session.getAdjunct(PersistenceRunnable.class);
if (obj instanceof PersistenceRunnable) {
- PersistenceRunnable pr = (PersistenceRunnable)obj;
+ PersistenceRunnable pr = (PersistenceRunnable) obj;
synchronized (pr.modifiedBuckets) {
// mark bucket associated with this session
// as modified
session.getKieSession().addEventListener(this);
}
- /******************************/
- /* 'DroolsRunnable' interface */
- /******************************/
+ /* **************************** */
+ /* 'DroolsRunnable' interface */
+ /* **************************** */
/**
* {@inheritDoc}
}
}
- /****************************************/
- /* 'RuleRuntimeEventListener' interface */
- /****************************************/
+ /* ************************************** */
+ /* 'RuleRuntimeEventListener' interface */
+ /* ************************************** */
/**
* {@inheritDoc}
*/
static class SenderSessionBucketData {
// the set of all objects in the session associated with this bucket
- Map<Object,Object> droolsObjects = new IdentityHashMap<>();
+ Map<Object, Object> droolsObjects = new IdentityHashMap<>();
// used by the receiver to determine whether an update is really newer
int count = 0;
// if we reach this point, we have decoded the persistent data
- final Map<?,?> droolsObjects = (Map<?,?>) obj;
+ final Map<?, ?> droolsObjects = (Map<?, ?>) obj;
// signal when restore is complete
final CountDownLatch sessionLatch = new CountDownLatch(1);
bucket.putAdjunct(obj);
// send out updated date
- sendLockDataToBackups(bucket, (GlobalLocks)obj);
+ sendLockDataToBackups(bucket, (GlobalLocks) obj);
} else {
logger.error(RESTORE_BUCKET_ERROR
+ "Expected 'GlobalLocks', got '{}'",
TimeUnit.MILLISECONDS).until(() -> Leader.getLeader() != null);
// wait for each bucket to have an owner
- for (int i = 0 ; i < Bucket.BUCKETCOUNT ; i += 1) {
+ for (int i = 0; i < Bucket.BUCKETCOUNT; i += 1) {
Bucket bucket = Bucket.getBucket(i);
while (bucket.getOwner() == null) {
Thread.sleep(Math.min(endTime - System.currentTimeMillis(), 100L));
*/
logger.info("{}: Calling 'sendEvent': packages = {}", this,
policySession.getKieSession().getKieBase().getKiePackages());
- ((TopicListener)policyController).onTopicEvent(
+ ((TopicListener) policyController).onTopicEvent(
CommInfrastructure.UEB, "JUNIT-TEST-TOPIC",
"{\"key\":\"" + key + "\"}");
}
String rval = null;
// try up to 10000 numeric values to locate one on a particular host
- for (int i = 0 ; i < 10000 ; i += 1) {
+ for (int i = 0; i < 10000; i += 1) {
// generate key, and see if it is on the desired server
String testString = prefix + (startingIndex + i);
if (ServerWrapperImpl.getWrapper(
import java.io.PrintStream;
import java.util.IdentityHashMap;
-
import org.onap.policy.drools.serverpooltest.BucketWrapper;
import org.onap.policy.drools.serverpooltest.ServerWrapper;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.UUID;
-
import org.onap.policy.drools.serverpooltest.ServerWrapper;
/**
package org.onap.policy.drools.serverpool;
import java.io.Serializable;
-import java.util.IdentityHashMap;
-
import org.onap.policy.drools.core.lock.Lock;
import org.onap.policy.drools.core.lock.LockCallback;
import org.onap.policy.drools.serverpooltest.TargetLockWrapper;
* 'TargetLockWrapperImpl' class for each simulated host.
*/
public class TargetLockWrapperImpl implements TargetLockWrapper {
+ private static final long serialVersionUID = 1L;
+
// this is the 'TargetLock' instance associated with the wrapper
private TargetLock targetLock;
* interface, translating it to a 'TargetLockWrapper.Owner' callback.
*/
public static class OwnerAdapter implements LockCallback, Serializable {
+ private static final long serialVersionUID = 1L;
+
// the 'TargetLockWrapper' instance to pass as an argument in the callback
TargetLockWrapper targetLock;
ClassLoader saveClassLoader =
Thread.currentThread().getContextClassLoader();
if (saveClassLoader instanceof URLClassLoader) {
- urls = ((URLClassLoader)saveClassLoader).getURLs();
+ urls = ((URLClassLoader) saveClassLoader).getURLs();
} else {
// the parent is not a 'URLClassLoader' --
// try to get this information from 'java.class.path'
urls = tmpUrls.toArray(new URL[0]);
}
try {
- for (int i = 0 ; i < adapters.length ; i += 1) {
+ for (int i = 0; i < adapters.length; i += 1) {
/*
* Build a new 'ClassLoader' for this adapter. The
* 'ClassLoader' hierarchy is:
// being blocked
int index = name.lastIndexOf('.');
if (index >= 0) {
- if (packages.contains(name.substring(0,index))) {
+ if (packages.contains(name.substring(0, index))) {
throw(new ClassNotFoundException(name));
}
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
-
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
-
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
/* ============================================================ */
// maps topic name to 'Topic' instance
- static Map<String,Topic> topicTable = new ConcurrentHashMap<>();
+ static Map<String, Topic> topicTable = new ConcurrentHashMap<>();
/**
* Each instance of this class corresponds to a DMAAP or UEB topic.
String topic;
// maps group name into group instance
- Map<String,Group> groupTable = new ConcurrentHashMap<>();
+ Map<String, Group> groupTable = new ConcurrentHashMap<>();
/**
* Create or get a Topic.
// no more messages
break;
}
- String[] prefix = data.substring(cur,leftBrace).split("\\.");
+ String[] prefix = data.substring(cur, leftBrace).split("\\.");
if (prefix.length == 3) {
try {
// determine length of message, and advance current position
builder.append("[\"").append(message);
// add up to '<limit>-1' more messages
- for (int i = 1 ; i < limit ; i += 1) {
+ for (int i = 1; i < limit; i += 1) {
// fetch the next message -- don't wait if it isn't currently there
message = messages.poll();
if (message == null) {
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
-
import org.awaitility.Durations;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
-
import org.kie.api.runtime.KieSession;
import org.onap.policy.drools.core.DroolsRunnable;
import org.onap.policy.drools.serverpool.BucketWrapperImpl;
if (count > thr.length) {
count = thr.length;
}
- for (int i = 0 ; i < count ; i += 1) {
+ for (int i = 0; i < count; i += 1) {
StringBuilder sb = new StringBuilder();
sb.append(" ").append(thr[i]);
if (stackTrace) {
if (adapter == firstAdapter) {
// make sure an owner and primary backup have been chosen
// for each bucket (secondary backups aren't implemented yet)
- for (int i = 0 ; i < bucketStatic.getBucketCount() ; i += 1) {
+ for (int i = 0; i < bucketStatic.getBucketCount(); i += 1) {
BucketWrapper bucket = bucketStatic.getBucket(i);
assertNotNull(bucket.getOwner());
assertNotNull(bucket.getPrimaryBackup());
} else {
// make sure the bucket assignments are consistent with
// the primary backup
- for (int i = 0 ; i < bucketStatic.getBucketCount() ; i += 1) {
+ for (int i = 0; i < bucketStatic.getBucketCount(); i += 1) {
BucketWrapper firstBucket = firstBucketStatic.getBucket(i);
BucketWrapper bucket = bucketStatic.getBucket(i);
assertEquals(firstBucket.getOwner().getUuid(),
KieSession kieSession = newClient.getKieSession();
for (Object obj : new ArrayList<Object>(kieSession.getObjects())) {
if (obj instanceof KeywordWrapper) {
- KeywordWrapper kw = (KeywordWrapper)obj;
+ KeywordWrapper kw = (KeywordWrapper) obj;
if ("lmt.owner".equals(kw.id)) {
owner = kw.getObject(LockOwner.class);
// need a 'LockOwner' variant
final LockOwner owner = new LockOwner() {
+ private static final long serialVersionUID = 1L;
+
/**
* {@inheritDoc}
*/
*/
public static class LockOwner extends LinkedBlockingQueue<Object[]>
implements TargetLockWrapper.Owner, Serializable {
+
+ private static final long serialVersionUID = 1L;
+
/**
* Constructor -- initialize the 'LinkedBlockingQueue'.
*/
* testing.
*/
public static class KeywordWrapper implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// this is the keyword, which determines the associated bucket,
// which then determines when this object is migrated
public String key;
package org.onap.policy.drools.serverpooltest;
import java.io.Serializable;
-import java.util.Objects;
-
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@ToString
@EqualsAndHashCode
public class TestDroolsObject implements Serializable {
+ private static final long serialVersionUID = 1L;
+
// determines the bucket number
private String key;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
-
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.hibernate.cfg.AvailableSettings;
}
}
- /** Factory for various items. Methods can be overridden for junit testing. */
+ /* Factory for various items. Methods can be overridden for junit testing. */
/**
* Gets the transaction manager.
import static org.junit.Assert.assertTrue;
import java.util.Date;
-
import org.junit.Test;
-import org.onap.policy.drools.persistence.DroolsSessionEntity;
public class DroolsSessionEntityTest {
@Test
public void testEqualsObject() {
DroolsSessionEntity entity = makeEnt("mynameA", 1);
-
+
// diff object type
assertFalse(entity.equals("hello"));
import java.util.HashMap;
import java.util.Map;
-
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.onap.policy.drools.persistence.DroolsSessionEntity;
-import org.onap.policy.drools.persistence.EntityMgrTrans;
-import org.onap.policy.drools.persistence.JpaDroolsSessionConnector;
public class JpaDroolsSessionConnectorTest {
/**
* Setup.
- *
+ *
* @throws Exception exception
*/
@Before
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
-
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.After;
import org.junit.Before;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
-
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
if (queues.containsKey(topicName)) {
return getNextMessageFromQueue(timeout, topicName);
- }
- else if (timeout > 0) {
+ } else if (timeout > 0) {
return waitForNextMessageFromQueue(timeout, topicName);
}
return NO_TOPIC_MSG;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
-
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.SQLException;
import java.util.Properties;
import java.util.UUID;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Get the instance.
- *
+ *
* @return the single 'DbAudit' instance. */
public static DroolsPdpIntegrityMonitor.AuditBase getInstance() {
return instance;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
-
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
if (stateManagement == null) {
logger.debug("StateManagementFeature.globalInit(): stateManagement is NULL!");
- }
- else {
+ } else {
logger.debug("StateManagementFeature.globalInit(): "
+ "stateManagement.getAdminState(): {}", stateManagement.getAdminState());
}
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package org.onap.policy.drools.statemanagement;
import java.util.Properties;
-
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Initialize the parameter values from the feature-state-management.properties file values.
- *
+ *
* <p>This is designed so that the Properties object is obtained from the
* feature-state-management.properties file and then is passed to this method to initialize the
* value of the parameters. This allows the flexibility of JUnit tests using
* getProperties(filename) to get the properties while runtime methods can use
* getPropertiesFromClassPath(filename).
- *
+ *
* @param prop properties
*/
public static void initProperties(Properties prop) {
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package org.onap.policy.drools.statemanagement.test;
import java.io.Serializable;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
-
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.ws.rs.core.Response;
-
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
String userDir = System.getProperty("user.dir");
logger.debug("setUpClass: userDir=" + userDir);
System.setProperty("com.sun.management.jmxremote.port", "9980");
- System.setProperty("com.sun.management.jmxremote.authenticate","false");
+ System.setProperty("com.sun.management.jmxremote.authenticate", "false");
initializeDb();
assertTrue("Standby status not coldstandby after promote()", standby.equals(StateManagement.COLD_STANDBY));
- /**************Repository Audit Test. **************/
+ /* *************Repository Audit Test. ************* */
logger.debug("\n\ntestStateManagementOperation: Repository Audit\n\n");
try {
StateManagementProperties.initProperties(fsmProperties);
logger.debug("testSubsytemTest RepositoryAudit InterruptedException", e);
}
- /*****************Db Audit Test. ***************/
+ /* ****************Db Audit Test. ************** */
logger.debug("\n\ntestStateManagementOperation: DB Audit\n\n");
try {
logger.debug("testSubsytemTest DbAudit exception", e);
}
- /*************IntegrityMonitorRestManager Test. *************/
+ /* ************IntegrityMonitorRestManager Test. ************ */
logger.debug("\n\ntestStateManagementOperation: IntegrityMonitorRestManager\n\n");
IntegrityMonitorRestManager integrityMonitorRestManager = new IntegrityMonitorRestManager();
logger.debug("initializeDb: Entering");
Properties cleanProperties = new Properties();
- cleanProperties.put(StateManagementProperties.DB_DRIVER,"org.h2.Driver");
+ cleanProperties.put(StateManagementProperties.DB_DRIVER, "org.h2.Driver");
cleanProperties.put(StateManagementProperties.DB_URL, "jdbc:h2:mem:statemanagement");
cleanProperties.put(StateManagementProperties.DB_USER, "sa");
cleanProperties.put(StateManagementProperties.DB_PWD, "");
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
-
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieScanner;
package org.onap.policy.drools.core;
import java.util.concurrent.ConcurrentHashMap;
-
import org.kie.api.event.rule.AfterMatchFiredEvent;
import org.kie.api.event.rule.AgendaEventListener;
import org.kie.api.event.rule.AgendaGroupPoppedEvent;
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package org.onap.policy.drools.core.jmx;
import java.lang.management.ManagementFactory;
-
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
server.unregisterMBean(new ObjectName("PolicyEngine:type=PdpJmx"));
} catch (MBeanRegistrationException | InstanceNotFoundException
| MalformedObjectNameException e) {
- logger.error("PdpJmxListener.stop(): "
+ logger.error("PdpJmxListener.stop(): "
+ "Could not unregister PolicyEngine:type=PdpJmx MBean "
+ "with the MBean server", e);
}
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
-
import lombok.NonNull;
-
import org.apache.commons.io.IOUtils;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.drools.compiler.kproject.models.KieModuleModelImpl;
if (!stillNeeded.isEmpty()) {
// there are still packages we need to add --
// this code makes use of an internal class and method
- ((KnowledgeBaseImpl)kieBase).addPackages(stillNeeded);
+ ((KnowledgeBaseImpl) kieBase).addPackages(stillNeeded);
}
}
}
@Test
public void getPackages() {
assertEquals(Arrays.asList("java.util", "java.util.concurrent", "org.onap.policy.drools.core.test"),
- KieUtils.getPackages(container) .stream().map(KiePackage::getName).collect(Collectors.toList()));
+ KieUtils.getPackages(container).stream().map(KiePackage::getName).collect(Collectors.toList()));
}
@Test
new ToscaPolicyTypeIdentifier(OPERATIONAL_LEGACY_POLICY_TYPE, "1.0.0");
DomainMaker domainMaker = new DomainMaker();
- assertTrue(domainMaker .isConformant(legacyType, rawVcpeToscaPolicy));
+ assertTrue(domainMaker.isConformant(legacyType, rawVcpeToscaPolicy));
LegacyPolicy legacyPolicy = domainMaker.convertTo(legacyType, rawVcpeToscaPolicy, LegacyPolicy.class);
ToscaPolicy policy = new StandardCoder().decode(rawVcpeToscaPolicy, ToscaPolicy.class);
if (feature.beforeDeliver(this, sink, event)) {
return true;
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
logger.error("{}: feature {} before-deliver failure because of {}", this, feature.getClass().getName(),
e.getMessage(), e);
}
if (feature.afterDeliver(this, sink, event, json, success)) {
return true;
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
logger.error("{}: feature {} after-deliver failure because of {}", this, feature.getClass().getName(),
e.getMessage(), e);
}
}
@Override
- public Map<String,Integer> factClassNames(String sessionName) {
+ public Map<String, Integer> factClassNames(String sessionName) {
validateSessionName(sessionName);
- Map<String,Integer> classNames = new HashMap<>();
+ Map<String, Integer> classNames = new HashMap<>();
PolicySession session = getSession(sessionName);
KieSession kieSession = session.getKieSession();
import java.util.Comparator;
import java.util.List;
import java.util.Properties;
-
import java.util.function.BiPredicate;
import org.onap.policy.drools.properties.DroolsPropertyConstants;
import org.onap.policy.drools.utils.PropertyUtil;
package org.onap.policy.drools.system;
import com.fasterxml.jackson.annotation.JsonIgnore;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Policy Controller Name Index.
*/
- private final HashMap<String,PolicyController> policyControllers =
+ private final HashMap<String, PolicyController> policyControllers =
new HashMap<>();
/**
* Group/Artifact Ids Index.
*/
- private final HashMap<String,PolicyController> coordinates2Controller =
+ private final HashMap<String, PolicyController> coordinates2Controller =
new HashMap<>();
/**
}
synchronized (this) {
- String key = toKey(groupId,artifactId);
+ String key = toKey(groupId, artifactId);
if (this.coordinates2Controller.containsKey(key)) {
return this.coordinates2Controller.get(key);
} else {
}
private <T> void attempt(AtomicReference<Boolean> success, List<T> items, PredicateWithEx<T> pred,
- BiConsumer<T,Exception> handleEx) {
+ BiConsumer<T, Exception> handleEx) {
for (T item : items) {
try {
}
private <T> void applyAll(List<T> items, Consumer<T> function,
- BiConsumer<T,Exception> handleEx) {
+ BiConsumer<T, Exception> handleEx) {
for (T item : items) {
try {
controller.getContainer()
.getPolicySession(KBSESSION_RULES)
.getKieSession()
- .addEventListener( new RuleRuntimeEventListener() {
+ .addEventListener(new RuleRuntimeEventListener() {
@Override
public void objectInserted(ObjectInsertedEvent objectInsertedEvent) {
logger.info("RULE {}: inserting {}",
logger.info("RULE {}: deleting {}",
objectDeletedEvent.getRule().getName(), objectDeletedEvent.getOldObject());
}
- } );
+ });
controller.getContainer()
.getPolicySession(KBSESSION_RULES)
public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent ruleFlowGroupDeactivatedEvent) {
/* do nothing */
}
- } );
+ });
}
}
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package org.onap.policy.drools.utils;
-public class Pair<F,S> {
+public class Pair<F, S> {
protected F first;
protected S second;
-
+
public Pair(F first, S second) {
this.first = first;
this.second = second;
public void run() {
try {
poll();
- }
- catch (Exception e) {
+ } catch (Exception e) {
logger.warn("Polling for property changes", e);
}
}
*/
synchronized Properties addListener(Listener listener) {
listeners.add(listener);
- return (Properties)properties.clone();
+ return (Properties) properties.clone();
}
/**
// Copy 'properties' and 'changedProperties', so it doesn't
// cause problems if the recipient makes changes.
final Properties tmpProperties =
- (Properties)(properties.clone());
+ (Properties) properties.clone();
final HashSet<String> tmpChangedProperties =
new HashSet<>(changedProperties);
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package org.onap.policy.drools.utils;
-public class Triple<F,S,T> {
+public class Triple<F, S, T> {
private F first;
private S second;
/**
* Constructor.
- *
+ *
* @param first first
* @param second second
* @param third third
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.junit.Test;
public class PairTripleTest {
-
+
@Test
public void testPair() {
Pair<String, String> pair = new Pair<String, String>("foo", "bar");
-
+
assertEquals("foo", pair.first());
assertEquals("bar", pair.second());
assertEquals("foo", pair.getFirst());
assertEquals("two", pair.getSecond());
assertNotNull(pair.toString());
-
- }
+
+ }
@Test
public void testTriple() {
- Triple<String, String, String> triple = new Triple<String, String,String>("foo", "bar", "fiz");
-
+ Triple<String, String, String> triple = new Triple<String, String, String>("foo", "bar", "fiz");
+
assertEquals("foo", triple.first());
assertEquals("bar", triple.second());
assertEquals("fiz", triple.third());
assertEquals("one", triple.first());
assertEquals("two", triple.second());
- assertEquals("three", triple.third());
+ assertEquals("three", triple.third());
}
}
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.junit.Test;
public class ReflectionUtilTest {
-
+
public class ParentClass {
}
-
+
public class ChildClass extends ParentClass{
}
@Test
public void testReflection() {
-
+
try {
Class<?> class1 = Class.forName("org.onap.policy.drools.utils.ReflectionUtil");
-
+
ClassLoader classLoader = class1.getClassLoader();
-
+
Class<?> class2 = ReflectionUtil.fetchClass(classLoader, "org.onap.policy.drools.utils.ReflectionUtil");
-
-
+
+
assertTrue(ReflectionUtil.isClass(classLoader, "org.onap.policy.drools.utils.ReflectionUtil"));
- assertEquals(class1,class2);
+ assertEquals(class1, class2);
assertTrue(ReflectionUtil.isSubclass(ParentClass.class, ChildClass.class));
assertFalse(ReflectionUtil.isSubclass(ChildClass.class, ParentClass.class));
-
-
+
+
} catch (ClassNotFoundException e) {
fail();
}
}
-
+
@Test(expected = IllegalArgumentException.class)
public void testException1() {
ReflectionUtil.fetchClass(null, "org.onap.policy.drools.utils.ReflectionUtil");
MDC.get(MdcTransactionConstants.ELAPSED_TIME));
assertEquals(trans.getServiceInstanceId(), MDC.get(MdcTransactionConstants.SERVICE_INSTANCE_ID));
assertEquals(trans.getInstanceUuid(), MDC.get(MdcTransactionConstants.INSTANCE_UUID));
- assertEquals(trans.getProcessKey(),MDC.get(MdcTransactionConstants.PROCESS_KEY));
+ assertEquals(trans.getProcessKey(), MDC.get(MdcTransactionConstants.PROCESS_KEY));
assertEquals(trans.getStatusCode(), MDC.get(MdcTransactionConstants.STATUS_CODE));
assertEquals(trans.getResponseCode(), MDC.get(MdcTransactionConstants.RESPONSE_CODE));
assertEquals(trans.getResponseDescription(), MDC.get(MdcTransactionConstants.RESPONSE_DESCRIPTION));
<build>
<plugins>
- <plugin>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <executions>
- <execution>
- <id>onap-java-style</id>
- <goals>
- <goal>check</goal>
- </goals>
- <phase>process-sources</phase>
- <configuration>
- <!-- Use Google Java Style Guide: https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml
- with minor changes -->
- <configLocation>onap-checkstyle/onap-java-style.xml</configLocation>
- <!-- <sourceDirectory> is needed so that checkstyle ignores the generated sources directory -->
- <sourceDirectories>${project.build.sourceDirectory}</sourceDirectories>
- <includeResources>true</includeResources>
- <includeTestSourceDirectory>true</includeTestSourceDirectory>
- <includeTestResources>true</includeTestResources>
- <excludes>
- </excludes>
- <!-- suppressionsLocation>${project.baseUri}checkstyle-suppressions.xml</suppressionsLocation -->
- <consoleOutput>true</consoleOutput>
- <failsOnViolation>true</failsOnViolation>
- <violationSeverity>warning</violationSeverity>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.onap.oparent</groupId>
- <artifactId>checkstyle</artifactId>
- <version>${oparent.version}</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
- </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>