http://git-wip-us.apache.org/repos/asf/cloudstack/blob/782c5306/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java ---------------------------------------------------------------------- diff --git a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java index 23ae50c..3159059 100644 --- a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java @@ -83,8 +83,6 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu protected VolumeDao _volsDao; @Inject protected ConfigurationDao _configDao; - @Inject - protected ApiDispatcher _dispatcher; protected AsyncJobDispatcher _asyncDispatcher; @@ -98,21 +96,21 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu return _asyncDispatcher; } - public void setAsyncJobDispatcher(final AsyncJobDispatcher dispatcher) { + public void setAsyncJobDispatcher(AsyncJobDispatcher dispatcher) { _asyncDispatcher = dispatcher; } - private Date getNextScheduledTime(final long policyId, final Date currentTimestamp) { - final SnapshotPolicyVO policy = _snapshotPolicyDao.findById(policyId); + private Date getNextScheduledTime(long policyId, Date currentTimestamp) { + SnapshotPolicyVO policy = _snapshotPolicyDao.findById(policyId); Date nextTimestamp = null; if (policy != null) { - final short intervalType = policy.getInterval(); - final IntervalType type = DateUtil.getIntervalType(intervalType); - final String schedule = policy.getSchedule(); - final String timezone = policy.getTimezone(); + short intervalType = policy.getInterval(); + IntervalType type = DateUtil.getIntervalType(intervalType); + String schedule = policy.getSchedule(); + String timezone = policy.getTimezone(); nextTimestamp = DateUtil.getNextRunTime(type, schedule, timezone, currentTimestamp); - final String currentTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, currentTimestamp); - final String nextScheduledTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, nextTimestamp); + String currentTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, currentTimestamp); + String nextScheduledTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, nextTimestamp); s_logger.debug("Current time is " + currentTime + ". NextScheduledTime of policyId " + policyId + " is " + nextScheduledTime); } return nextTimestamp; @@ -122,7 +120,7 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu * {@inheritDoc} */ @Override - public void poll(final Date currentTimestamp) { + public void poll(Date currentTimestamp) { // We don't maintain the time. The timer task does. _currentTimestamp = currentTimestamp; @@ -154,12 +152,12 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu } private void checkStatusOfCurrentlyExecutingSnapshots() { - final SearchCriteria<SnapshotScheduleVO> sc = _snapshotScheduleDao.createSearchCriteria(); + SearchCriteria<SnapshotScheduleVO> sc = _snapshotScheduleDao.createSearchCriteria(); sc.addAnd("asyncJobId", SearchCriteria.Op.NNULL); - final List<SnapshotScheduleVO> snapshotSchedules = _snapshotScheduleDao.search(sc, null); - for (final SnapshotScheduleVO snapshotSchedule : snapshotSchedules) { - final Long asyncJobId = snapshotSchedule.getAsyncJobId(); - final AsyncJobVO asyncJob = _asyncJobDao.findById(asyncJobId); + List<SnapshotScheduleVO> snapshotSchedules = _snapshotScheduleDao.search(sc, null); + for (SnapshotScheduleVO snapshotSchedule : snapshotSchedules) { + Long asyncJobId = snapshotSchedule.getAsyncJobId(); + AsyncJobVO asyncJob = _asyncJobDao.findById(asyncJobId); switch (asyncJob.getStatus()) { case SUCCEEDED: // The snapshot has been successfully backed up. @@ -170,7 +168,7 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu break; case FAILED: // Check the snapshot status. - final Long snapshotId = snapshotSchedule.getSnapshotId(); + Long snapshotId = snapshotSchedule.getSnapshotId(); if (snapshotId == null) { // createSnapshotAsync exited, successfully or unsuccessfully, // even before creating a snapshot record @@ -178,7 +176,7 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu // Schedule the next snapshot. scheduleNextSnapshotJob(snapshotSchedule); } else { - final SnapshotVO snapshot = _snapshotDao.findById(snapshotId); + SnapshotVO snapshot = _snapshotDao.findById(snapshotId); if (snapshot == null || snapshot.getRemoved() != null) { // This snapshot has been deleted successfully from the primary storage // Again no cleanup needs to be done. @@ -222,16 +220,16 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu String displayTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, _currentTimestamp); s_logger.debug("Snapshot scheduler.poll is being called at " + displayTime); - final List<SnapshotScheduleVO> snapshotsToBeExecuted = _snapshotScheduleDao.getSchedulesToExecute(_currentTimestamp); + List<SnapshotScheduleVO> snapshotsToBeExecuted = _snapshotScheduleDao.getSchedulesToExecute(_currentTimestamp); s_logger.debug("Got " + snapshotsToBeExecuted.size() + " snapshots to be executed at " + displayTime); - for (final SnapshotScheduleVO snapshotToBeExecuted : snapshotsToBeExecuted) { + for (SnapshotScheduleVO snapshotToBeExecuted : snapshotsToBeExecuted) { SnapshotScheduleVO tmpSnapshotScheduleVO = null; - final long snapshotScheId = snapshotToBeExecuted.getId(); - final long policyId = snapshotToBeExecuted.getPolicyId(); - final long volumeId = snapshotToBeExecuted.getVolumeId(); + long snapshotScheId = snapshotToBeExecuted.getId(); + long policyId = snapshotToBeExecuted.getPolicyId(); + long volumeId = snapshotToBeExecuted.getVolumeId(); try { - final VolumeVO volume = _volsDao.findById(volumeId); + VolumeVO volume = _volsDao.findById(volumeId); if (volume.getPoolId() == null) { // this volume is not attached continue; @@ -240,41 +238,40 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu _snapshotScheduleDao.remove(snapshotToBeExecuted.getId()); } if (s_logger.isDebugEnabled()) { - final Date scheduledTimestamp = snapshotToBeExecuted.getScheduledTimestamp(); + Date scheduledTimestamp = snapshotToBeExecuted.getScheduledTimestamp(); displayTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, scheduledTimestamp); s_logger.debug("Scheduling 1 snapshot for volume " + volumeId + " for schedule id: " + snapshotToBeExecuted.getId() + " at " + displayTime); } tmpSnapshotScheduleVO = _snapshotScheduleDao.acquireInLockTable(snapshotScheId); - final Long eventId = + Long eventId = ActionEventUtils.onScheduledActionEvent(User.UID_SYSTEM, volume.getAccountId(), EventTypes.EVENT_SNAPSHOT_CREATE, "creating snapshot for volume Id:" + volumeId, 0); - final Map<String, Object> params = new HashMap<String, Object>(); + Map<String, String> params = new HashMap<String, String>(); params.put(ApiConstants.VOLUME_ID, "" + volumeId); params.put(ApiConstants.POLICY_ID, "" + policyId); params.put("ctxUserId", "1"); params.put("ctxAccountId", "" + volume.getAccountId()); params.put("ctxStartEventId", String.valueOf(eventId)); - final CreateSnapshotCmd cmd = new CreateSnapshotCmd(); + CreateSnapshotCmd cmd = new CreateSnapshotCmd(); ComponentContext.inject(cmd); - _dispatcher.dispatchCreateCmd(cmd, params); + ApiDispatcher.getInstance().dispatchCreateCmd(cmd, params); params.put("id", "" + cmd.getEntityId()); params.put("ctxStartEventId", "1"); - final AsyncJobVO job = + AsyncJobVO job = new AsyncJobVO(UUID.randomUUID().toString(), User.UID_SYSTEM, volume.getAccountId(), CreateSnapshotCmd.class.getName(), ApiGsonHelper.getBuilder() .create() .toJson(params), cmd.getEntityId(), cmd.getInstanceType() != null ? cmd.getInstanceType().toString() : null); job.setDispatcher(_asyncDispatcher.getName()); - final long jobId = _asyncMgr.submitAsyncJob(job); + long jobId = _asyncMgr.submitAsyncJob(job); tmpSnapshotScheduleVO.setAsyncJobId(jobId); _snapshotScheduleDao.update(snapshotScheId, tmpSnapshotScheduleVO); - } catch (final Exception e) { - // TODO Logging this exception is enough? + } catch (Exception e) { s_logger.warn("Scheduling snapshot failed due to " + e.toString()); } finally { if (tmpSnapshotScheduleVO != null) { @@ -284,16 +281,16 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu } } - private Date scheduleNextSnapshotJob(final SnapshotScheduleVO snapshotSchedule) { + private Date scheduleNextSnapshotJob(SnapshotScheduleVO snapshotSchedule) { if (snapshotSchedule == null) { return null; } - final Long policyId = snapshotSchedule.getPolicyId(); + Long policyId = snapshotSchedule.getPolicyId(); if (policyId.longValue() == Snapshot.MANUAL_POLICY_ID) { // Don't need to schedule the next job for this. return null; } - final SnapshotPolicyVO snapshotPolicy = _snapshotPolicyDao.findById(policyId); + SnapshotPolicyVO snapshotPolicy = _snapshotPolicyDao.findById(policyId); if (snapshotPolicy == null) { _snapshotScheduleDao.expunge(snapshotSchedule.getId()); } @@ -302,15 +299,15 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu @Override @DB - public Date scheduleNextSnapshotJob(final SnapshotPolicyVO policy) { + public Date scheduleNextSnapshotJob(SnapshotPolicyVO policy) { if (policy == null) { return null; } - final long policyId = policy.getId(); + long policyId = policy.getId(); if (policyId == Snapshot.MANUAL_POLICY_ID) { return null; } - final Date nextSnapshotTimestamp = getNextScheduledTime(policyId, _currentTimestamp); + Date nextSnapshotTimestamp = getNextScheduledTime(policyId, _currentTimestamp); SnapshotScheduleVO spstSchedVO = _snapshotScheduleDao.findOneByVolumePolicy(policy.getVolumeId(), policy.getId()); if (spstSchedVO == null) { spstSchedVO = new SnapshotScheduleVO(policy.getVolumeId(), policyId, nextSnapshotTimestamp); @@ -334,9 +331,9 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu @Override @DB - public boolean removeSchedule(final Long volumeId, final Long policyId) { + public boolean removeSchedule(Long volumeId, Long policyId) { // We can only remove schedules which are in the future. Not which are already executed in the past. - final SnapshotScheduleVO schedule = _snapshotScheduleDao.getCurrentSchedule(volumeId, policyId, false); + SnapshotScheduleVO schedule = _snapshotScheduleDao.getCurrentSchedule(volumeId, policyId, false); boolean success = true; if (schedule != null) { success = _snapshotScheduleDao.remove(schedule.getId()); @@ -348,18 +345,18 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu } @Override - public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { + public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _snapshotPollInterval = NumbersUtil.parseInt(_configDao.getValue("snapshot.poll.interval"), 300); - final boolean snapshotsRecurringTest = Boolean.parseBoolean(_configDao.getValue("snapshot.recurring.test")); + boolean snapshotsRecurringTest = Boolean.parseBoolean(_configDao.getValue("snapshot.recurring.test")); if (snapshotsRecurringTest) { // look for some test values in the configuration table so that snapshots can be taken more frequently (QA test code) - final int minutesPerHour = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.minutes.per.hour"), 60); - final int hoursPerDay = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.hours.per.day"), 24); - final int daysPerWeek = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.days.per.week"), 7); - final int daysPerMonth = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.days.per.month"), 30); - final int weeksPerMonth = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.weeks.per.month"), 4); - final int monthsPerYear = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.months.per.year"), 12); + int minutesPerHour = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.minutes.per.hour"), 60); + int hoursPerDay = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.hours.per.day"), 24); + int daysPerWeek = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.days.per.week"), 7); + int daysPerMonth = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.days.per.month"), 30); + int weeksPerMonth = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.weeks.per.month"), 4); + int monthsPerYear = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.months.per.year"), 12); _testTimerTask = new TestClock(this, minutesPerHour, hoursPerDay, daysPerWeek, daysPerMonth, weeksPerMonth, monthsPerYear); } @@ -374,8 +371,8 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu @DB public boolean start() { // reschedule all policies after management restart - final List<SnapshotPolicyVO> policyInstances = _snapshotPolicyDao.listAll(); - for (final SnapshotPolicyVO policyInstance : policyInstances) { + List<SnapshotPolicyVO> policyInstances = _snapshotPolicyDao.listAll(); + for (SnapshotPolicyVO policyInstance : policyInstances) { if (policyInstance.getId() != Snapshot.MANUAL_POLICY_ID) { scheduleNextSnapshotJob(policyInstance); } @@ -386,13 +383,13 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu // Else it becomes too confusing. _testClockTimer.schedule(_testTimerTask, 100 * 1000L, 60 * 1000L); } else { - final TimerTask timerTask = new ManagedContextTimerTask() { + TimerTask timerTask = new ManagedContextTimerTask() { @Override protected void runInContext() { try { - final Date currentTimestamp = new Date(); + Date currentTimestamp = new Date(); poll(currentTimestamp); - } catch (final Throwable t) { + } catch (Throwable t) { s_logger.warn("Catch throwable in snapshot scheduler ", t); } }
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/782c5306/server/test/com/cloud/api/ApiDispatcherTest.java ---------------------------------------------------------------------- diff --git a/server/test/com/cloud/api/ApiDispatcherTest.java b/server/test/com/cloud/api/ApiDispatcherTest.java new file mode 100644 index 0000000..7314a57 --- /dev/null +++ b/server/test/com/cloud/api/ApiDispatcherTest.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.api; + +import java.util.HashMap; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.context.CallContext; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.User; + +@RunWith(MockitoJUnitRunner.class) +public class ApiDispatcherTest { + + @Mock + AccountManager accountManager; + + public static class TestCmd extends BaseCmd { + + @Parameter(name = "strparam1") + String strparam1; + + @Parameter(name = "intparam1", type = CommandType.INTEGER) + int intparam1; + + @Parameter(name = "boolparam1", type = CommandType.BOOLEAN) + boolean boolparam1; + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException, NetworkRuleConflictException { + // well documented nothing + } + + @Override + public String getCommandName() { + return "test"; + } + + @Override + public long getEntityOwnerId() { + return 0; + } + + } + + @Before + public void setup() { + CallContext.register(Mockito.mock(User.class), Mockito.mock(Account.class)); + new ApiDispatcher().init(); + ApiDispatcher.getInstance()._accountMgr = accountManager; + } + + @After + public void cleanup() { + CallContext.unregister(); + } + + @Test + public void processParameters() { + HashMap<String, String> params = new HashMap<String, String>(); + params.put("strparam1", "foo"); + params.put("intparam1", "100"); + params.put("boolparam1", "true"); + TestCmd cmd = new TestCmd(); + //how lucky that field is not protected, this test would be impossible + ApiDispatcher.processParameters(cmd, params); + Assert.assertEquals("foo", cmd.strparam1); + Assert.assertEquals(100, cmd.intparam1); + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/782c5306/server/test/com/cloud/api/dispatch/CommandCreationWorkerTest.java ---------------------------------------------------------------------- diff --git a/server/test/com/cloud/api/dispatch/CommandCreationWorkerTest.java b/server/test/com/cloud/api/dispatch/CommandCreationWorkerTest.java deleted file mode 100644 index 775fd6a..0000000 --- a/server/test/com/cloud/api/dispatch/CommandCreationWorkerTest.java +++ /dev/null @@ -1,48 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.dispatch; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.apache.cloudstack.api.BaseAsyncCreateCmd; - -import com.cloud.exception.ResourceAllocationException; - -public class CommandCreationWorkerTest { - - @Test - public void testHandle() throws ResourceAllocationException { - // Prepare - final BaseAsyncCreateCmd asyncCreateCmd = mock(BaseAsyncCreateCmd.class); - final Map<String, Object> params = new HashMap<String, Object>(); - - // Execute - final CommandCreationWorker creationWorker = new CommandCreationWorker(); - - creationWorker.handle(asyncCreateCmd, params); - - // Assert - verify(asyncCreateCmd, times(1)).create(); - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/782c5306/server/test/com/cloud/api/dispatch/DispatchChainFactoryTest.java ---------------------------------------------------------------------- diff --git a/server/test/com/cloud/api/dispatch/DispatchChainFactoryTest.java b/server/test/com/cloud/api/dispatch/DispatchChainFactoryTest.java deleted file mode 100644 index 0d743d4..0000000 --- a/server/test/com/cloud/api/dispatch/DispatchChainFactoryTest.java +++ /dev/null @@ -1,54 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.dispatch; - -import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class DispatchChainFactoryTest { - - protected static final String STANDARD_CHAIN_ERROR = "Expecting worker of class %s at index %s of StandardChain"; - protected static final String ASYNC_CHAIN_ERROR = "Expecting worker of class %s at index %s of StandardChain"; - - @Test - public void testAllChainCreation() { - // Prepare - final DispatchChainFactory dispatchChainFactory = new DispatchChainFactory(); - dispatchChainFactory.paramGenericValidationWorker = new ParamGenericValidationWorker(); - dispatchChainFactory.paramSemanticValidationWorker = new ParamSemanticValidationWorker(); - dispatchChainFactory.paramProcessWorker = new ParamProcessWorker(); - dispatchChainFactory.commandCreationWorker = new CommandCreationWorker(); - - final Class<?>[] standardClasses = {ParamGenericValidationWorker.class, ParamProcessWorker.class, - ParamSemanticValidationWorker.class}; - final Class<?>[] asyncClasses = {ParamGenericValidationWorker.class, ParamProcessWorker.class, - ParamSemanticValidationWorker.class, CommandCreationWorker.class}; - - // Execute - dispatchChainFactory.setup(); - final DispatchChain standardChain = dispatchChainFactory.getStandardDispatchChain(); - final DispatchChain asyncChain = dispatchChainFactory.getAsyncCreationDispatchChain(); - for (int i = 0; i < standardClasses.length; i++) { - assertEquals(String.format(STANDARD_CHAIN_ERROR, standardClasses[i], i), - standardClasses[i], standardChain.workers.get(i).getClass()); - } - for (int i = 0; i < asyncClasses.length; i++) { - assertEquals(String.format(ASYNC_CHAIN_ERROR, asyncClasses[i], i), - asyncClasses[i], asyncChain.workers.get(i).getClass()); - } - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/782c5306/server/test/com/cloud/api/dispatch/ParamGenericValidationWorkerTest.java ---------------------------------------------------------------------- diff --git a/server/test/com/cloud/api/dispatch/ParamGenericValidationWorkerTest.java b/server/test/com/cloud/api/dispatch/ParamGenericValidationWorkerTest.java deleted file mode 100644 index 3fd37cc..0000000 --- a/server/test/com/cloud/api/dispatch/ParamGenericValidationWorkerTest.java +++ /dev/null @@ -1,163 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.dispatch; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.cloudstack.acl.RoleType; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; - -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; - -import org.apache.log4j.Logger; - -public class ParamGenericValidationWorkerTest { - - protected String loggerOutput = null; - - protected void driveTest(final BaseCmd cmd, final Map<String, Object> params) { - final ParamGenericValidationWorker genValidationWorker = new ParamGenericValidationWorker(); - - // We create a mock logger to verify the result - ParamGenericValidationWorker.s_logger = new Logger(""){ - @Override - public void warn(final Object msg){ - loggerOutput = msg.toString(); - } - }; - - // Execute - genValidationWorker.handle(cmd, params); - } - - @Test - public void testHandle() throws ResourceAllocationException { - // Prepare - final BaseCmd cmd = new FakeCmd(); - final Map<String, Object> params = new HashMap<String, Object>(); - params.put(ApiConstants.COMMAND, ""); - params.put("addedParam", ""); - - // Execute - driveTest(cmd, params); - - // Assert - assertEquals("There should be no errors since there are no unknown parameters for this command class", null, loggerOutput); - } - - @Test - public void testHandleWithUnknownParams() throws ResourceAllocationException { - // Prepare - final String unknownParamKey = "unknownParam"; - final BaseCmd cmd = new FakeCmd(); - final Map<String, Object> params = new HashMap<String, Object>(); - params.put(ApiConstants.COMMAND, ""); - params.put("addedParam", ""); - params.put(unknownParamKey, ""); - - // Execute - driveTest(cmd, params); - - // Assert - assertTrue("There should be error msg, since there is one unknown parameter", loggerOutput.contains(unknownParamKey)); - } - - @Test - public void testHandleWithoutAuthorization() throws ResourceAllocationException { - final short type = 2; - driveAuthTest(type); - - // Assert - assertTrue("There should be error msg, since there is one unauthorized parameter", loggerOutput.contains("paramWithRole")); - } - - @Test - public void testHandleWithAuthorization() throws ResourceAllocationException { - final short type = 1; - driveAuthTest(type); - - // Assert - assertEquals("There should be no errors since parameters have authorization", null, loggerOutput); - } - - protected void driveAuthTest(final short type) { - // Prepare - final BaseCmd cmd = new FakeCmdWithRoleAdmin(); - final Account account = mock(Account.class); - ((FakeCmdWithRoleAdmin)cmd).account = account; - when(account.getType()).thenReturn(type); - final Map<String, Object> params = new HashMap<String, Object>(); - params.put(ApiConstants.COMMAND, ""); - params.put("addedParam", ""); - params.put("paramWithRole", ""); - - // Execute - driveTest(cmd, params); - } -} - -class FakeCmd extends BaseCmd { - - @Parameter(name = "addedParam") - private String addedParam; - - public Account account; - - @Override - protected Account getCurrentContextAccount() { - return account; - } - - // - // Dummy methods for mere correct compilation - // - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, - NetworkRuleConflictException { - } - @Override - public String getCommandName() { - return null; - } - @Override - public long getEntityOwnerId() { - return 0; - } -} - -class FakeCmdWithRoleAdmin extends FakeCmd { - - @Parameter(name = "paramWithRole", authorized = {RoleType.Admin}) - private String paramWithRole; -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/782c5306/server/test/com/cloud/api/dispatch/ParamProcessWorkerTest.java ---------------------------------------------------------------------- diff --git a/server/test/com/cloud/api/dispatch/ParamProcessWorkerTest.java b/server/test/com/cloud/api/dispatch/ParamProcessWorkerTest.java deleted file mode 100644 index 1259713..0000000 --- a/server/test/com/cloud/api/dispatch/ParamProcessWorkerTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.cloud.api.dispatch; - -import java.util.HashMap; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; - -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.User; - -@RunWith(MockitoJUnitRunner.class) -public class ParamProcessWorkerTest { - - @Mock - protected AccountManager accountManager; - - protected ParamProcessWorker paramProcessWorker; - - public static class TestCmd extends BaseCmd { - - @Parameter(name = "strparam1") - String strparam1; - - @Parameter(name = "intparam1", type = CommandType.INTEGER) - int intparam1; - - @Parameter(name = "boolparam1", type = CommandType.BOOLEAN) - boolean boolparam1; - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { - // well documented nothing - } - - @Override - public String getCommandName() { - return "test"; - } - - @Override - public long getEntityOwnerId() { - return 0; - } - - } - - @Before - public void setup() { - CallContext.register(Mockito.mock(User.class), Mockito.mock(Account.class)); - paramProcessWorker = new ParamProcessWorker(); - paramProcessWorker._accountMgr = accountManager; - } - - @After - public void cleanup() { - CallContext.unregister(); - } - - @Test - public void processParameters() { - final HashMap<String, Object> params = new HashMap<String, Object>(); - params.put("strparam1", "foo"); - params.put("intparam1", "100"); - params.put("boolparam1", "true"); - final TestCmd cmd = new TestCmd(); - paramProcessWorker.processParameters(cmd, params); - Assert.assertEquals("foo", cmd.strparam1); - Assert.assertEquals(100, cmd.intparam1); - } - -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/782c5306/server/test/com/cloud/api/dispatch/ParamSemanticValidationWorkerTest.java ---------------------------------------------------------------------- diff --git a/server/test/com/cloud/api/dispatch/ParamSemanticValidationWorkerTest.java b/server/test/com/cloud/api/dispatch/ParamSemanticValidationWorkerTest.java deleted file mode 100644 index 920654e..0000000 --- a/server/test/com/cloud/api/dispatch/ParamSemanticValidationWorkerTest.java +++ /dev/null @@ -1,48 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.dispatch; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.apache.cloudstack.api.BaseCmd; - -import com.cloud.exception.ResourceAllocationException; - -public class ParamSemanticValidationWorkerTest { - - @Test - public void testHandle() throws ResourceAllocationException { - // Prepare - final BaseCmd cmd = mock(BaseCmd.class); - final Map<String, Object> params = new HashMap<String, Object>(); - - // Execute - final ParamSemanticValidationWorker semanticValWorker = new ParamSemanticValidationWorker(); - - semanticValWorker.handle(cmd, params); - - // Assert - verify(cmd, times(1)).validateSpecificParameters(params); - } -}