cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From d...@apache.org
Subject [1/6] CLOUDSTACK-6003 fixing plus refactoring dispatcher
Date Tue, 04 Feb 2014 12:38:32 GMT
Updated Branches:
  refs/heads/master ca1b340ce -> 447430c3d


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/447430c3/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 3159059..23ae50c 100644
--- a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java
+++ b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java
@@ -83,6 +83,8 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
     protected VolumeDao _volsDao;
     @Inject
     protected ConfigurationDao _configDao;
+    @Inject
+    protected ApiDispatcher _dispatcher;
 
     protected AsyncJobDispatcher _asyncDispatcher;
 
@@ -96,21 +98,21 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
         return _asyncDispatcher;
     }
 
-    public void setAsyncJobDispatcher(AsyncJobDispatcher dispatcher) {
+    public void setAsyncJobDispatcher(final AsyncJobDispatcher dispatcher) {
         _asyncDispatcher = dispatcher;
     }
 
-    private Date getNextScheduledTime(long policyId, Date currentTimestamp) {
-        SnapshotPolicyVO policy = _snapshotPolicyDao.findById(policyId);
+    private Date getNextScheduledTime(final long policyId, final Date currentTimestamp) {
+        final SnapshotPolicyVO policy = _snapshotPolicyDao.findById(policyId);
         Date nextTimestamp = null;
         if (policy != null) {
-            short intervalType = policy.getInterval();
-            IntervalType type = DateUtil.getIntervalType(intervalType);
-            String schedule = policy.getSchedule();
-            String timezone = policy.getTimezone();
+            final short intervalType = policy.getInterval();
+            final IntervalType type = DateUtil.getIntervalType(intervalType);
+            final String schedule = policy.getSchedule();
+            final String timezone = policy.getTimezone();
             nextTimestamp = DateUtil.getNextRunTime(type, schedule, timezone, currentTimestamp);
-            String currentTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, currentTimestamp);
-            String nextScheduledTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE,
nextTimestamp);
+            final String currentTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE,
currentTimestamp);
+            final String nextScheduledTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE,
nextTimestamp);
             s_logger.debug("Current time is " + currentTime + ". NextScheduledTime of policyId
" + policyId + " is " + nextScheduledTime);
         }
         return nextTimestamp;
@@ -120,7 +122,7 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
      * {@inheritDoc}
      */
     @Override
-    public void poll(Date currentTimestamp) {
+    public void poll(final Date currentTimestamp) {
         // We don't maintain the time. The timer task does.
         _currentTimestamp = currentTimestamp;
 
@@ -152,12 +154,12 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
     }
 
     private void checkStatusOfCurrentlyExecutingSnapshots() {
-        SearchCriteria<SnapshotScheduleVO> sc = _snapshotScheduleDao.createSearchCriteria();
+        final SearchCriteria<SnapshotScheduleVO> sc = _snapshotScheduleDao.createSearchCriteria();
         sc.addAnd("asyncJobId", SearchCriteria.Op.NNULL);
-        List<SnapshotScheduleVO> snapshotSchedules = _snapshotScheduleDao.search(sc,
null);
-        for (SnapshotScheduleVO snapshotSchedule : snapshotSchedules) {
-            Long asyncJobId = snapshotSchedule.getAsyncJobId();
-            AsyncJobVO asyncJob = _asyncJobDao.findById(asyncJobId);
+        final List<SnapshotScheduleVO> snapshotSchedules = _snapshotScheduleDao.search(sc,
null);
+        for (final SnapshotScheduleVO snapshotSchedule : snapshotSchedules) {
+            final Long asyncJobId = snapshotSchedule.getAsyncJobId();
+            final AsyncJobVO asyncJob = _asyncJobDao.findById(asyncJobId);
             switch (asyncJob.getStatus()) {
                 case SUCCEEDED:
                     // The snapshot has been successfully backed up.
@@ -168,7 +170,7 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
                     break;
                 case FAILED:
                     // Check the snapshot status.
-                    Long snapshotId = snapshotSchedule.getSnapshotId();
+                    final Long snapshotId = snapshotSchedule.getSnapshotId();
                     if (snapshotId == null) {
                         // createSnapshotAsync exited, successfully or unsuccessfully,
                         // even before creating a snapshot record
@@ -176,7 +178,7 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
                         // Schedule the next snapshot.
                         scheduleNextSnapshotJob(snapshotSchedule);
                     } else {
-                        SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
+                        final 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.
@@ -220,16 +222,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);
 
-        List<SnapshotScheduleVO> snapshotsToBeExecuted = _snapshotScheduleDao.getSchedulesToExecute(_currentTimestamp);
+        final List<SnapshotScheduleVO> snapshotsToBeExecuted = _snapshotScheduleDao.getSchedulesToExecute(_currentTimestamp);
         s_logger.debug("Got " + snapshotsToBeExecuted.size() + " snapshots to be executed
at " + displayTime);
 
-        for (SnapshotScheduleVO snapshotToBeExecuted : snapshotsToBeExecuted) {
+        for (final SnapshotScheduleVO snapshotToBeExecuted : snapshotsToBeExecuted) {
             SnapshotScheduleVO tmpSnapshotScheduleVO = null;
-            long snapshotScheId = snapshotToBeExecuted.getId();
-            long policyId = snapshotToBeExecuted.getPolicyId();
-            long volumeId = snapshotToBeExecuted.getVolumeId();
+            final long snapshotScheId = snapshotToBeExecuted.getId();
+            final long policyId = snapshotToBeExecuted.getPolicyId();
+            final long volumeId = snapshotToBeExecuted.getVolumeId();
             try {
-                VolumeVO volume = _volsDao.findById(volumeId);
+                final VolumeVO volume = _volsDao.findById(volumeId);
                 if (volume.getPoolId() == null) {
                     // this volume is not attached
                     continue;
@@ -238,40 +240,41 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
                     _snapshotScheduleDao.remove(snapshotToBeExecuted.getId());
                 }
                 if (s_logger.isDebugEnabled()) {
-                    Date scheduledTimestamp = snapshotToBeExecuted.getScheduledTimestamp();
+                    final 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);
-                Long eventId =
+                final Long eventId =
                     ActionEventUtils.onScheduledActionEvent(User.UID_SYSTEM, volume.getAccountId(),
EventTypes.EVENT_SNAPSHOT_CREATE, "creating snapshot for volume Id:" +
                         volumeId, 0);
 
-                Map<String, String> params = new HashMap<String, String>();
+                final Map<String, Object> params = new HashMap<String, Object>();
                 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));
 
-                CreateSnapshotCmd cmd = new CreateSnapshotCmd();
+                final CreateSnapshotCmd cmd = new CreateSnapshotCmd();
                 ComponentContext.inject(cmd);
-                ApiDispatcher.getInstance().dispatchCreateCmd(cmd, params);
+                _dispatcher.dispatchCreateCmd(cmd, params);
                 params.put("id", "" + cmd.getEntityId());
                 params.put("ctxStartEventId", "1");
 
-                AsyncJobVO job =
+                final 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());
 
-                long jobId = _asyncMgr.submitAsyncJob(job);
+                final long jobId = _asyncMgr.submitAsyncJob(job);
 
                 tmpSnapshotScheduleVO.setAsyncJobId(jobId);
                 _snapshotScheduleDao.update(snapshotScheId, tmpSnapshotScheduleVO);
-            } catch (Exception e) {
+            } catch (final Exception e) {
+                // TODO Logging this exception is enough?
                 s_logger.warn("Scheduling snapshot failed due to " + e.toString());
             } finally {
                 if (tmpSnapshotScheduleVO != null) {
@@ -281,16 +284,16 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
         }
     }
 
-    private Date scheduleNextSnapshotJob(SnapshotScheduleVO snapshotSchedule) {
+    private Date scheduleNextSnapshotJob(final SnapshotScheduleVO snapshotSchedule) {
         if (snapshotSchedule == null) {
             return null;
         }
-        Long policyId = snapshotSchedule.getPolicyId();
+        final Long policyId = snapshotSchedule.getPolicyId();
         if (policyId.longValue() == Snapshot.MANUAL_POLICY_ID) {
             // Don't need to schedule the next job for this.
             return null;
         }
-        SnapshotPolicyVO snapshotPolicy = _snapshotPolicyDao.findById(policyId);
+        final SnapshotPolicyVO snapshotPolicy = _snapshotPolicyDao.findById(policyId);
         if (snapshotPolicy == null) {
             _snapshotScheduleDao.expunge(snapshotSchedule.getId());
         }
@@ -299,15 +302,15 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
 
     @Override
     @DB
-    public Date scheduleNextSnapshotJob(SnapshotPolicyVO policy) {
+    public Date scheduleNextSnapshotJob(final SnapshotPolicyVO policy) {
         if (policy == null) {
             return null;
         }
-        long policyId = policy.getId();
+        final long policyId = policy.getId();
         if (policyId == Snapshot.MANUAL_POLICY_ID) {
             return null;
         }
-        Date nextSnapshotTimestamp = getNextScheduledTime(policyId, _currentTimestamp);
+        final Date nextSnapshotTimestamp = getNextScheduledTime(policyId, _currentTimestamp);
         SnapshotScheduleVO spstSchedVO = _snapshotScheduleDao.findOneByVolumePolicy(policy.getVolumeId(),
policy.getId());
         if (spstSchedVO == null) {
             spstSchedVO = new SnapshotScheduleVO(policy.getVolumeId(), policyId, nextSnapshotTimestamp);
@@ -331,9 +334,9 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
 
     @Override
     @DB
-    public boolean removeSchedule(Long volumeId, Long policyId) {
+    public boolean removeSchedule(final Long volumeId, final Long policyId) {
         // We can only remove schedules which are in the future. Not which are already executed
in the past.
-        SnapshotScheduleVO schedule = _snapshotScheduleDao.getCurrentSchedule(volumeId, policyId,
false);
+        final SnapshotScheduleVO schedule = _snapshotScheduleDao.getCurrentSchedule(volumeId,
policyId, false);
         boolean success = true;
         if (schedule != null) {
             success = _snapshotScheduleDao.remove(schedule.getId());
@@ -345,18 +348,18 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
     }
 
     @Override
-    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException
{
+    public boolean configure(final String name, final Map<String, Object> params) throws
ConfigurationException {
 
         _snapshotPollInterval = NumbersUtil.parseInt(_configDao.getValue("snapshot.poll.interval"),
300);
-        boolean snapshotsRecurringTest = Boolean.parseBoolean(_configDao.getValue("snapshot.recurring.test"));
+        final 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)
-            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);
+            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);
 
             _testTimerTask = new TestClock(this, minutesPerHour, hoursPerDay, daysPerWeek,
daysPerMonth, weeksPerMonth, monthsPerYear);
         }
@@ -371,8 +374,8 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
     @DB
     public boolean start() {
         // reschedule all policies after management restart
-        List<SnapshotPolicyVO> policyInstances = _snapshotPolicyDao.listAll();
-        for (SnapshotPolicyVO policyInstance : policyInstances) {
+        final List<SnapshotPolicyVO> policyInstances = _snapshotPolicyDao.listAll();
+        for (final SnapshotPolicyVO policyInstance : policyInstances) {
             if (policyInstance.getId() != Snapshot.MANUAL_POLICY_ID) {
                 scheduleNextSnapshotJob(policyInstance);
             }
@@ -383,13 +386,13 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu
             // Else it becomes too confusing.
             _testClockTimer.schedule(_testTimerTask, 100 * 1000L, 60 * 1000L);
         } else {
-            TimerTask timerTask = new ManagedContextTimerTask() {
+            final TimerTask timerTask = new ManagedContextTimerTask() {
                 @Override
                 protected void runInContext() {
                     try {
-                        Date currentTimestamp = new Date();
+                        final Date currentTimestamp = new Date();
                         poll(currentTimestamp);
-                    } catch (Throwable t) {
+                    } catch (final Throwable t) {
                         s_logger.warn("Catch throwable in snapshot scheduler ", t);
                     }
                 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/447430c3/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
deleted file mode 100644
index 7314a57..0000000
--- a/server/test/com/cloud/api/ApiDispatcherTest.java
+++ /dev/null
@@ -1,106 +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;
-
-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/447430c3/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
new file mode 100644
index 0000000..775fd6a
--- /dev/null
+++ b/server/test/com/cloud/api/dispatch/CommandCreationWorkerTest.java
@@ -0,0 +1,48 @@
+// 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/447430c3/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
new file mode 100644
index 0000000..0d743d4
--- /dev/null
+++ b/server/test/com/cloud/api/dispatch/DispatchChainFactoryTest.java
@@ -0,0 +1,54 @@
+// 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/447430c3/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
new file mode 100644
index 0000000..3fd37cc
--- /dev/null
+++ b/server/test/com/cloud/api/dispatch/ParamGenericValidationWorkerTest.java
@@ -0,0 +1,163 @@
+// 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/447430c3/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
new file mode 100644
index 0000000..1259713
--- /dev/null
+++ b/server/test/com/cloud/api/dispatch/ParamProcessWorkerTest.java
@@ -0,0 +1,107 @@
+/*
+ * 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/447430c3/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
new file mode 100644
index 0000000..920654e
--- /dev/null
+++ b/server/test/com/cloud/api/dispatch/ParamSemanticValidationWorkerTest.java
@@ -0,0 +1,48 @@
+// 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);
+    }
+}


Mime
View raw message