src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
RunnableUtils { public static void populateRackInfoForReplicationFactorChange(Map<Short, Set<String>> topicsByReplicationFactor, Cluster cluster, boolean skipTopicRackAwarenessCheck, Map<String, List<Integer>> brokersByRack, Map<Integer, String> rackByBroker) { for (Node node : cluster.nodes()) { String rack = getRackHandleNull(node); brokersByRack.putIfAbsent(rack, new ArrayList<>()); brokersByRack.get(rack).add(node.id()); rackByBroker.put(node.id(), rack); } topicsByReplicationFactor.forEach((replicationFactor, topics) -> { if (replicationFactor > rackByBroker.size()) { throw new RuntimeException(String.format("Unable to change replication factor (RF) of topics %s to %d since there are only %d " + "alive brokers in the cluster. Requested RF cannot be more than number of alive brokers.", topics, replicationFactor, rackByBroker.size())); } else if (replicationFactor > brokersByRack.size()) { if (skipTopicRackAwarenessCheck) { LOG.info("Target replication factor for topics {} is {}, which is larger than number of racks in cluster. Rack-awareness " + "property will be violated to add new replicas.", topics, replicationFactor); } else { throw new RuntimeException(String.format("Unable to change replication factor of topics %s to %d since there are only %d " + "racks in the cluster, to skip the rack-awareness check, set %s to true in the request.", topics, replicationFactor, brokersByRack.size(), ParameterUtils.SKIP_RACK_AWARENESS_CHECK_PARAM)); } } }); } private RunnableUtils(); static void populateRackInfoForReplicationFactorChange(Map<Short, Set<String>> topicsByReplicationFactor,
Cluster cluster,
boolean skipTopicRackAwarenessCheck,
Map<String, List<Integer>> brokersByRack,
Map<Integer, String> rackByBroker); static Map<Short, Set<String>> topicsForReplicationFactorChange(Map<Short, Pattern> topicPatternByReplicationFactor,
Cluster cluster); static boolean shouldRefreshClusterAndGeneration(Set<CruiseControlState.SubState> substates); static PartitionInfo partitionWithOfflineReplicas(Cluster cluster); static boolean isKafkaAssignerMode(Collection<String> goals); static void sanityCheckBrokersHavingOfflineReplicasOnBadDisks(List<String> goals, ClusterModel clusterModel); static void maybeStopOngoingExecutionToModifyAndWait(KafkaCruiseControl kafkaCruiseControl,
OperationProgress operationProgress); static OptimizationOptions computeOptimizationOptions(ClusterModel clusterModel,
boolean isTriggeredByGoalViolation,
KafkaCruiseControl kafkaCruiseControl,
Set<Integer> brokersToDrop,
boolean dryRun,
boolean excludeRecentlyDemotedBrokers,
boolean excludeRecentlyRemovedBrokers,
Pattern excludedTopicsPattern,
Set<Integer> requestedDestinationBrokerIds,
boolean onlyMoveImmigrantReplicas); static void sanityCheckOfflineReplicaPresence(ClusterModel clusterModel); static final boolean SELF_HEALING_DRYRUN; static final Set<Integer> SELF_HEALING_DESTINATION_BROKER_IDS; static final ReplicaMovementStrategy SELF_HEALING_REPLICA_MOVEMENT_STRATEGY; static final Pattern SELF_HEALING_EXCLUDED_TOPICS; static final Integer SELF_HEALING_CONCURRENT_MOVEMENTS; static final Long SELF_HEALING_EXECUTION_PROGRESS_CHECK_INTERVAL_MS; static final boolean SELF_HEALING_SKIP_HARD_GOAL_CHECK; static final boolean SELF_HEALING_STOP_ONGOING_EXECUTION; static final ModelCompletenessRequirements SELF_HEALING_MODEL_COMPLETENESS_REQUIREMENTS; static final boolean SELF_HEALING_SKIP_URP_DEMOTION; static final boolean SELF_HEALING_EXCLUDE_FOLLOWER_DEMOTION; static final boolean SELF_HEALING_SKIP_RACK_AWARENESS_CHECK; static final boolean SELF_HEALING_IS_TRIGGERED_BY_USER_REQUEST; } | @Test public void testPopulateRackInfoForReplicationFactorChange() { Map<String, List<Integer>> brokersByRack = new HashMap<>(); Map<Integer, String> rackByBroker = new HashMap<>(); assertThrows(RuntimeException.class, () -> populateRackInfoForReplicationFactorChange(Collections.singletonMap((short) (NODES.length + 1), Collections.singleton(TOPIC)), CLUSTER, false, brokersByRack, rackByBroker)); assertThrows(RuntimeException.class, () -> populateRackInfoForReplicationFactorChange(Collections.singletonMap((short) NODES.length, Collections.singleton(TOPIC)), CLUSTER, false, brokersByRack, rackByBroker)); populateRackInfoForReplicationFactorChange(Collections.singletonMap((short) NODES.length, Collections.singleton(TOPIC)), CLUSTER, true, brokersByRack, rackByBroker); assertEquals(2, brokersByRack.size()); assertEquals(NODES.length, rackByBroker.size()); } |
SessionManager { synchronized OperationFuture getAndCreateSessionIfNotExist(HttpServletRequest request, Supplier<OperationFuture> operation, int step) { HttpSession session = request.getSession(); SessionInfo info = _inProgressSessions.get(session); String requestString = toRequestString(request); if (info != null) { LOG.info("Found existing session {}", session); info.ensureSameRequest(requestString, request.getParameterMap()); if (step < info.numFutures()) { return info.future(step); } else if (step == info.numFutures()) { LOG.info("Adding new future to existing session {}.", session); OperationFuture future = operation.get(); info.addFuture(future); return future; } else { throw new IllegalArgumentException(String.format("There are %d steps in the session. Cannot add step %d.", info.numFutures(), step)); } } else { if (step > 0) { throw new IllegalArgumentException(String.format("There are no step in the session. Cannot add step %d.", step)); } if (_inProgressSessions.size() >= _capacity) { _sessionCreationFailureMeter.mark(); throw new RuntimeException("There are already " + _inProgressSessions.size() + " active sessions, which " + "has reached the servlet capacity."); } LOG.info("Created session for {}", session); info = new SessionInfo(requestString, request.getParameterMap(), ParameterUtils.endPoint(request)); OperationFuture future = operation.get(); info.addFuture(future); _inProgressSessions.put(session, info); return future; } } SessionManager(int capacity,
long sessionExpiryMs,
Time time,
MetricRegistry dropwizardMetricRegistry,
Map<EndPoint, Timer> successfulRequestExecutionTimer); void close(); } | @Test public void testMultipleOperationRequest() { TestContext context = prepareRequests(false, 1); SessionManager sessionManager = new SessionManager(1, 1000, context.time(), new MetricRegistry(), null); HttpServletRequest request = context.request(0); OperationFuture future1 = new OperationFuture("future1"); OperationFuture future2 = new OperationFuture("future2"); for (int i = 0; i < 2; i++) { OperationFuture firstFuture = sessionManager.getAndCreateSessionIfNotExist(request, () -> future1, 0); assertSame(firstFuture, future1); future1.complete(new PauseSamplingResult(null)); OperationFuture secondFuture = sessionManager.getAndCreateSessionIfNotExist(request, () -> future2, 1); assertSame(secondFuture, future2); future2.complete(new ResumeSamplingResult(null)); } }
@Test (expected = IllegalArgumentException.class) public void testSkipStep() { TestContext context = prepareRequests(false, 1); SessionManager sessionManager = new SessionManager(1, 1000, context.time(), new MetricRegistry(), null); HttpServletRequest request = context.request(0); sessionManager.getAndCreateSessionIfNotExist(request, () -> null, 1); } |
BrokerFailures extends KafkaAnomaly { @Override public String toString() { StringBuilder sb = new StringBuilder().append("{"); sb.append(_fixable ? "Fixable " : " Unfixable "); sb.append("broker failures detected: {"); if (_failedBrokers != null) { _failedBrokers.forEach((key, value) -> { sb.append("Broker ").append(key).append(" failed at ").append(toDateString(value)).append(",\t"); }); sb.setLength(sb.length() - 2); } sb.append("}}"); return sb.toString(); } BrokerFailures(); Map<Integer, Long> failedBrokers(); boolean fixable(); @Override boolean fix(); @Override AnomalyType anomalyType(); @Override Supplier<String> reasonSupplier(); @Override String toString(); @SuppressWarnings("unchecked") @Override void configure(Map<String, ?> configs); } | @Test public void testToString() { assertNotNull(new BrokerFailures().toString()); } |
SlackSelfHealingNotifier extends SelfHealingNotifier { @Override public void alert(Object anomaly, boolean autoFixTriggered, long selfHealingStartTime, AnomalyType anomalyType) { super.alert(anomaly, autoFixTriggered, selfHealingStartTime, anomalyType); if (_slackWebhook == null) { LOG.warn("Slack webhook is null, can't send Slack self healing notification"); return; } if (_slackChannel == null) { LOG.warn("Slack channel name is null, can't send Slack self healing notification"); return; } String text = String.format("%s detected %s. Self healing %s.%s", anomalyType, anomaly, _selfHealingEnabled.get(anomalyType) ? String.format("start time %s", toDateString(selfHealingStartTime)) : "is disabled", autoFixTriggered ? "%nSelf-healing has been triggered." : ""); try { sendSlackMessage(new SlackMessage(_slackUser, text, _slackIcon, _slackChannel), _slackWebhook); } catch (IOException e) { LOG.warn("ERROR sending alert to Slack", e); } } SlackSelfHealingNotifier(); SlackSelfHealingNotifier(Time time); @Override void configure(Map<String, ?> config); @Override void alert(Object anomaly, boolean autoFixTriggered, long selfHealingStartTime, AnomalyType anomalyType); static final String SLACK_SELF_HEALING_NOTIFIER_WEBHOOK; static final String SLACK_SELF_HEALING_NOTIFIER_ICON; static final String SLACK_SELF_HEALING_NOTIFIER_USER; static final String SLACK_SELF_HEALING_NOTIFIER_CHANNEL; static final String DEFAULT_SLACK_SELF_HEALING_NOTIFIER_ICON; static final String DEFAULT_SLACK_SELF_HEALING_NOTIFIER_USER; } | @Test public void testSlackAlertWithNoWebhook() { _notifier = new MockSlackSelfHealingNotifier(MOCK_TIME); _notifier.alert(FAILURES, false, 1L, KafkaAnomalyType.BROKER_FAILURE); assertEquals(0, _notifier.getSlackMessageList().size()); }
@Test public void testSlackAlertWithNoChannel() { _notifier = new MockSlackSelfHealingNotifier(MOCK_TIME); _notifier._slackWebhook = "http: _notifier.alert(FAILURES, false, 1L, KafkaAnomalyType.BROKER_FAILURE); assertEquals(0, _notifier.getSlackMessageList().size()); }
@Test public void testSlackAlertWithDefaultOptions() { _notifier = new MockSlackSelfHealingNotifier(MOCK_TIME); _notifier._slackWebhook = "http: _notifier._slackChannel = "#dummy-channel"; _notifier.alert(FAILURES, false, 1L, KafkaAnomalyType.BROKER_FAILURE); assertEquals(1, _notifier.getSlackMessageList().size()); SlackMessage message = _notifier.getSlackMessageList().get(0); assertEquals("#dummy-channel", message.getChannel()); } |
SelfHealingNotifier implements AnomalyNotifier { @Override public AnomalyNotificationResult onBrokerFailure(BrokerFailures brokerFailures) { long earliestFailureTimeMs = Long.MAX_VALUE; for (long t : brokerFailures.failedBrokers().values()) { earliestFailureTimeMs = Math.min(earliestFailureTimeMs, t); } long nowMs = _time.milliseconds(); long alertTimeMs = earliestFailureTimeMs + _brokerFailureAlertThresholdMs; long selfHealingTimeMs = earliestFailureTimeMs + _selfHealingThresholdMs; AnomalyNotificationResult result = null; if (nowMs < alertTimeMs) { long delayMs = alertTimeMs - nowMs; result = AnomalyNotificationResult.check(delayMs); } else if (nowMs < selfHealingTimeMs) { if (hasNewFailureToAlert(brokerFailures, false)) { alert(brokerFailures, false, selfHealingTimeMs, KafkaAnomalyType.BROKER_FAILURE); } long delay = selfHealingTimeMs - nowMs; result = AnomalyNotificationResult.check(delay); } else { boolean autoFixTriggered = _selfHealingEnabled.get(KafkaAnomalyType.BROKER_FAILURE) && brokerFailures.fixable(); if (hasNewFailureToAlert(brokerFailures, autoFixTriggered)) { alert(brokerFailures, autoFixTriggered, selfHealingTimeMs, KafkaAnomalyType.BROKER_FAILURE); } result = autoFixTriggered ? AnomalyNotificationResult.fix() : AnomalyNotificationResult.ignore(); } return result; } SelfHealingNotifier(); SelfHealingNotifier(Time time); @Override AnomalyNotificationResult onGoalViolation(GoalViolations goalViolations); @Override AnomalyNotificationResult onMetricAnomaly(KafkaMetricAnomaly metricAnomaly); @Override AnomalyNotificationResult onTopicAnomaly(TopicAnomaly topicAnomaly); @Override AnomalyNotificationResult onMaintenanceEvent(MaintenanceEvent maintenanceEvent); @Override AnomalyNotificationResult onDiskFailure(DiskFailures diskFailures); @Override Map<AnomalyType, Boolean> selfHealingEnabled(); @Override synchronized boolean setSelfHealingFor(AnomalyType anomalyType, boolean isSelfHealingEnabled); @Override synchronized Map<AnomalyType, Float> selfHealingEnabledRatio(); @Override AnomalyNotificationResult onBrokerFailure(BrokerFailures brokerFailures); void alert(Object anomaly, boolean autoFixTriggered, long selfHealingStartTime, AnomalyType anomalyType); @Override void configure(Map<String, ?> config); @Override long uptimeMs(long nowMs); static final String BROKER_FAILURE_ALERT_THRESHOLD_MS_CONFIG; static final String SELF_HEALING_ENABLED_CONFIG; static final String SELF_HEALING_BROKER_FAILURE_ENABLED_CONFIG; static final String SELF_HEALING_GOAL_VIOLATION_ENABLED_CONFIG; static final String SELF_HEALING_METRIC_ANOMALY_ENABLED_CONFIG; static final String SELF_HEALING_DISK_FAILURE_ENABLED_CONFIG; static final String SELF_HEALING_TOPIC_ANOMALY_ENABLED_CONFIG; static final String SELF_HEALING_MAINTENANCE_EVENT_ENABLED_CONFIG; static final String BROKER_FAILURE_SELF_HEALING_THRESHOLD_MS_CONFIG; } | @Test public void testOnBrokerFailure() { final long failureTime1 = 200L; final long failureTime2 = 400L; final long startTime = 500L; KafkaCruiseControl mockKafkaCruiseControl = EasyMock.mock(KafkaCruiseControl.class); Properties props = KafkaCruiseControlUnitTestUtils.getKafkaCruiseControlProperties(); KafkaCruiseControlConfig kafkaCruiseControlConfig = new KafkaCruiseControlConfig(props); EasyMock.expect(mockKafkaCruiseControl.config()).andReturn(kafkaCruiseControlConfig).atLeastOnce(); EasyMock.replay(mockKafkaCruiseControl); Time mockTime = new MockTime(0, startTime, TimeUnit.NANOSECONDS.convert(startTime, TimeUnit.MILLISECONDS)); TestingBrokerFailureAutoFixNotifier anomalyNotifier = new TestingBrokerFailureAutoFixNotifier(mockTime); anomalyNotifier.configure(Collections.singletonMap(SelfHealingNotifier.SELF_HEALING_BROKER_FAILURE_ENABLED_CONFIG, "true")); Map<Integer, Long> failedBrokers = new HashMap<>(); failedBrokers.put(1, failureTime1); failedBrokers.put(2, failureTime2); Map<String, Object> parameterConfigOverrides = new HashMap<>(4); parameterConfigOverrides.put(KAFKA_CRUISE_CONTROL_OBJECT_CONFIG, mockKafkaCruiseControl); parameterConfigOverrides.put(FAILED_BROKERS_OBJECT_CONFIG, failedBrokers); parameterConfigOverrides.put(ANOMALY_DETECTION_TIME_MS_OBJECT_CONFIG, failureTime1); parameterConfigOverrides.put(BROKER_FAILURES_FIXABLE_CONFIG, true); AnomalyNotificationResult result = anomalyNotifier.onBrokerFailure( kafkaCruiseControlConfig.getConfiguredInstance(AnomalyDetectorConfig.BROKER_FAILURES_CLASS_CONFIG, BrokerFailures.class, parameterConfigOverrides)); assertEquals(AnomalyNotificationResult.Action.CHECK, result.action()); assertEquals(SelfHealingNotifier.DEFAULT_ALERT_THRESHOLD_MS + failureTime1 - mockTime.milliseconds(), result.delay()); assertFalse(anomalyNotifier._alertCalled.get(KafkaAnomalyType.BROKER_FAILURE)); mockTime.sleep(result.delay() - 1); result = anomalyNotifier.onBrokerFailure( kafkaCruiseControlConfig.getConfiguredInstance(AnomalyDetectorConfig.BROKER_FAILURES_CLASS_CONFIG, BrokerFailures.class, parameterConfigOverrides)); assertEquals(AnomalyNotificationResult.Action.CHECK, result.action()); assertEquals(1, result.delay()); assertFalse(anomalyNotifier._alertCalled.get(KafkaAnomalyType.BROKER_FAILURE)); mockTime.sleep(1); anomalyNotifier.resetAlert(KafkaAnomalyType.BROKER_FAILURE); result = anomalyNotifier.onBrokerFailure( kafkaCruiseControlConfig.getConfiguredInstance(AnomalyDetectorConfig.BROKER_FAILURES_CLASS_CONFIG, BrokerFailures.class, parameterConfigOverrides)); assertEquals(AnomalyNotificationResult.Action.CHECK, result.action()); assertEquals(SelfHealingNotifier.DEFAULT_AUTO_FIX_THRESHOLD_MS + failureTime1 - mockTime.milliseconds(), result.delay()); assertTrue(anomalyNotifier._alertCalled.get(KafkaAnomalyType.BROKER_FAILURE)); mockTime.sleep(result.delay() - 1); anomalyNotifier.resetAlert(KafkaAnomalyType.BROKER_FAILURE); result = anomalyNotifier.onBrokerFailure( kafkaCruiseControlConfig.getConfiguredInstance(AnomalyDetectorConfig.BROKER_FAILURES_CLASS_CONFIG, BrokerFailures.class, parameterConfigOverrides)); assertEquals(AnomalyNotificationResult.Action.CHECK, result.action()); assertEquals(1, result.delay()); assertFalse(anomalyNotifier._alertCalled.get(KafkaAnomalyType.BROKER_FAILURE)); assertFalse(anomalyNotifier._autoFixTriggered.get(KafkaAnomalyType.BROKER_FAILURE)); mockTime.sleep(1); anomalyNotifier.resetAlert(KafkaAnomalyType.BROKER_FAILURE); result = anomalyNotifier.onBrokerFailure( kafkaCruiseControlConfig.getConfiguredInstance(AnomalyDetectorConfig.BROKER_FAILURES_CLASS_CONFIG, BrokerFailures.class, parameterConfigOverrides)); assertEquals(AnomalyNotificationResult.Action.FIX, result.action()); assertEquals(-1L, result.delay()); assertTrue(anomalyNotifier._alertCalled.get(KafkaAnomalyType.BROKER_FAILURE)); assertTrue(anomalyNotifier._autoFixTriggered.get(KafkaAnomalyType.BROKER_FAILURE)); assertFalse(anomalyNotifier._alertCalled.get(KafkaAnomalyType.GOAL_VIOLATION)); assertFalse(anomalyNotifier._alertCalled.get(KafkaAnomalyType.METRIC_ANOMALY)); assertFalse(anomalyNotifier._alertCalled.get(KafkaAnomalyType.DISK_FAILURE)); assertFalse(anomalyNotifier._alertCalled.get(KafkaAnomalyType.TOPIC_ANOMALY)); } |
SlackMessage implements Serializable { @Override public String toString() { return "{\"username\" : " + (_username == null ? null : "\"" + _username + "\"") + ",\"text\" : " + (_text == null ? null : "\"" + _text + "\"") + ",\"icon_emoji\" : " + (_iconEmoji == null ? null : "\"" + _iconEmoji + "\"") + ",\"channel\" : " + (_channel == null ? null : "\"" + _channel + "\"") + "}"; } SlackMessage(String username, String text, String iconEmoji, String channel); String getUsername(); String getText(); String getIconEmoji(); String getChannel(); @Override String toString(); } | @Test public void testSlackMessageJsonFormat() { String expectedJson = "{\"username\" : \"userA\",\"text\" : \"cc alert\",\"icon_emoji\" : \":information_source:" + "\",\"channel\" : \"#cc-alerts\"}"; assertEquals(expectedJson, new SlackMessage("userA", "cc alert", ":information_source:", "#cc-alerts").toString()); } |
SlowBrokerFinder implements MetricAnomalyFinder<BrokerEntity> { @Override public Collection<MetricAnomaly<BrokerEntity>> metricAnomalies(Map<BrokerEntity, ValuesAndExtrapolations> metricsHistoryByBroker, Map<BrokerEntity, ValuesAndExtrapolations> currentMetricsByBroker) { LOG.info("Slow broker detection started."); try { Set<BrokerEntity> detectedMetricAnomalies = detectMetricAnomalies(metricsHistoryByBroker, currentMetricsByBroker); updateBrokerSlownessScore(detectedMetricAnomalies); return createSlowBrokerAnomalies(detectedMetricAnomalies, metricsHistoryByBroker.size()); } catch (Exception e) { LOG.warn("Slow broker detector encountered exception: ", e); } finally { LOG.info("Slow broker detection finished."); } return Collections.emptySet(); } SlowBrokerFinder(); @Override Collection<MetricAnomaly<BrokerEntity>> metricAnomalies(Map<BrokerEntity, ValuesAndExtrapolations> metricsHistoryByBroker,
Map<BrokerEntity, ValuesAndExtrapolations> currentMetricsByBroker); @Override void configure(Map<String, ?> configs); static final String SELF_HEALING_SLOW_BROKER_REMOVAL_ENABLED_CONFIG; static final String REMOVE_SLOW_BROKER_CONFIG; static final String SLOW_BROKER_BYTES_IN_RATE_DETECTION_THRESHOLD_CONFIG; static final double DEFAULT_SLOW_BROKER_BYTES_IN_RATE_DETECTION_THRESHOLD; static final String SLOW_BROKER_LOG_FLUSH_TIME_THRESHOLD_MS_CONFIG; static final double DEFAULT_SLOW_BROKER_LOG_FLUSH_TIME_THRESHOLD_MS_CONFIG; static final String SLOW_BROKER_METRIC_HISTORY_PERCENTILE_THRESHOLD_CONFIG; static final double DEFAULT_SLOW_BROKER_METRIC_HISTORY_PERCENTILE_THRESHOLD; static final String SLOW_BROKER_METRIC_HISTORY_MARGIN_CONFIG; static final double DEFAULT_SLOW_BROKER_METRIC_HISTORY_MARGIN; static final String SLOW_BROKER_PEER_METRIC_PERCENTILE_THRESHOLD_CONFIG; static final double DEFAULT_SLOW_BROKER_PEER_METRIC_PERCENTILE_THRESHOLD; static final String SLOW_BROKER_PEER_METRIC_MARGIN_CONFIG; static final double DEFAULT_SLOW_BROKER_PEER_METRIC_MARGIN; static final String SLOW_BROKER_DEMOTION_SCORE_CONFIG; static final int DEFAULT_SLOW_BROKER_DEMOTION_SCORE; static final String SLOW_BROKER_DECOMMISSION_SCORE_CONFIG; static final int DEFAULT_SLOW_BROKER_DECOMMISSION_SCORE; static final String SLOW_BROKER_SELF_HEALING_UNFIXABLE_RATIO_CONFIG; } | @Test public void testDetectingSlowBrokerFromHistory() { SlowBrokerFinder slowBrokerFinder = createSlowBrokerFinder(); Map<BrokerEntity, ValuesAndExtrapolations> history = createHistory(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), populateMetricValues(NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_LOG_FLUSH_TIME_MS * LOG_FLUSH_TIME_MS_VARIANCE_RATIO), METRIC_HISTORY_WINDOW_SIZE, BROKER_ENTITIES.get(0)); Map<BrokerEntity, ValuesAndExtrapolations> currentMetrics = createCurrentMetrics(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS * METRIC_ANOMALY_MULTIPLIER), CURRENT_METRIC_WINDOW, BROKER_ENTITIES.get(0)); Collection<MetricAnomaly<BrokerEntity>> anomalies = slowBrokerFinder.metricAnomalies(history, currentMetrics); assertTrue("There should be exactly a single slow broker", anomalies.size() == 1); MetricAnomaly<BrokerEntity> anomaly = anomalies.iterator().next(); assertTrue(anomaly.entities().containsKey(BROKER_ENTITIES.get(0))); assertEquals(ANOMALY_DETECTION_TIME_MS, (long) anomaly.entities().get(BROKER_ENTITIES.get(0))); }
@Test public void testDetectingSlowBrokerFromPeer() { SlowBrokerFinder slowBrokerFinder = createSlowBrokerFinder(); Map<BrokerEntity, ValuesAndExtrapolations> currentMetrics = new HashMap<>(BROKER_ENTITIES.size()); Map<BrokerEntity, ValuesAndExtrapolations> history = new HashMap<>(BROKER_ENTITIES.size()); currentMetrics.putAll(createCurrentMetrics(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS * METRIC_ANOMALY_MULTIPLIER), CURRENT_METRIC_WINDOW, BROKER_ENTITIES.get(0))); history.putAll(createHistory(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS * METRIC_ANOMALY_MULTIPLIER), populateMetricValues(NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_LOG_FLUSH_TIME_MS * LOG_FLUSH_TIME_MS_VARIANCE_RATIO), METRIC_HISTORY_WINDOW_SIZE, BROKER_ENTITIES.get(0))); for (int i = 1; i < BROKER_ENTITIES.size(); i++) { currentMetrics.putAll(createCurrentMetrics(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), CURRENT_METRIC_WINDOW, BROKER_ENTITIES.get(i))); history.putAll(createHistory(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), populateMetricValues(NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_LOG_FLUSH_TIME_MS * LOG_FLUSH_TIME_MS_VARIANCE_RATIO), METRIC_HISTORY_WINDOW_SIZE, BROKER_ENTITIES.get(i))); } Collection<MetricAnomaly<BrokerEntity>> anomalies = slowBrokerFinder.metricAnomalies(history, currentMetrics); assertTrue("There should be exactly a single slow broker", anomalies.size() == 1); MetricAnomaly<BrokerEntity> anomaly = anomalies.iterator().next(); assertTrue(anomaly.entities().containsKey(BROKER_ENTITIES.get(0))); assertEquals(ANOMALY_DETECTION_TIME_MS, (long) anomaly.entities().get(BROKER_ENTITIES.get(0))); }
@Test public void testExcludingSmallTrafficBroker() { SlowBrokerFinder slowBrokerFinder = createSlowBrokerFinder(); Map<BrokerEntity, ValuesAndExtrapolations> currentMetrics = new HashMap<>(BROKER_ENTITIES.size()); Map<BrokerEntity, ValuesAndExtrapolations> history = new HashMap<>(BROKER_ENTITIES.size()); currentMetrics.putAll(createCurrentMetrics(populateMetricValues(SMALL_BYTES_IN_RATE, SMALL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), CURRENT_METRIC_WINDOW, BROKER_ENTITIES.get(0))); history.putAll(createHistory(populateMetricValues(SMALL_BYTES_IN_RATE, SMALL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), populateMetricValues(SMALL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, SMALL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_LOG_FLUSH_TIME_MS * LOG_FLUSH_TIME_MS_VARIANCE_RATIO), METRIC_HISTORY_WINDOW_SIZE, BROKER_ENTITIES.get(0))); for (int i = 1; i < BROKER_ENTITIES.size(); i++) { currentMetrics.putAll(createCurrentMetrics(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), CURRENT_METRIC_WINDOW, BROKER_ENTITIES.get(i))); history.putAll(createHistory(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), populateMetricValues(NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_LOG_FLUSH_TIME_MS * LOG_FLUSH_TIME_MS_VARIANCE_RATIO), METRIC_HISTORY_WINDOW_SIZE, BROKER_ENTITIES.get(0))); } Collection<MetricAnomaly<BrokerEntity>> anomalies = slowBrokerFinder.metricAnomalies(history, currentMetrics); assertTrue(anomalies.isEmpty()); }
@Test public void testInsufficientData() { SlowBrokerFinder slowBrokerFinder = createSlowBrokerFinder(); Map<BrokerEntity, ValuesAndExtrapolations> history = createHistory(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), populateMetricValues(NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_LOG_FLUSH_TIME_MS * LOG_FLUSH_TIME_MS_VARIANCE_RATIO), METRIC_HISTORY_WINDOW_SIZE / 2, BROKER_ENTITIES.get(0)); Map<BrokerEntity, ValuesAndExtrapolations> currentMetrics = createCurrentMetrics(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS * METRIC_ANOMALY_MULTIPLIER), METRIC_HISTORY_WINDOW_SIZE / 2 + 1, BROKER_ENTITIES.get(0)); Collection<MetricAnomaly<BrokerEntity>> anomalies = slowBrokerFinder.metricAnomalies(history, currentMetrics); assertTrue(anomalies.isEmpty()); }
@Test public void testNoFalsePositiveDetectionDueToTrafficFluctuation() { SlowBrokerFinder slowBrokerFinder = createSlowBrokerFinder(); Map<BrokerEntity, ValuesAndExtrapolations> history = createHistory(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), populateMetricValues(NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_LOG_FLUSH_TIME_MS * LOG_FLUSH_TIME_MS_VARIANCE_RATIO), METRIC_HISTORY_WINDOW_SIZE, BROKER_ENTITIES.get(0)); Map<BrokerEntity, ValuesAndExtrapolations> currentMetrics = createCurrentMetrics(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS), CURRENT_METRIC_WINDOW, BROKER_ENTITIES.get(0)); Collection<MetricAnomaly<BrokerEntity>> anomalies = slowBrokerFinder.metricAnomalies(history, currentMetrics); assertTrue(anomalies.isEmpty()); }
@Test public void testNoFalsePositiveDetectionOnSmallLogFlushTime() { SlowBrokerFinder slowBrokerFinder = createSlowBrokerFinder(); Map<BrokerEntity, ValuesAndExtrapolations> currentMetrics = new HashMap<>(BROKER_ENTITIES.size()); Map<BrokerEntity, ValuesAndExtrapolations> history = new HashMap<>(BROKER_ENTITIES.size()); currentMetrics.putAll(createCurrentMetrics(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS / 10 * METRIC_ANOMALY_MULTIPLIER), CURRENT_METRIC_WINDOW, BROKER_ENTITIES.get(0))); history.putAll(createHistory(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS / 10 * METRIC_ANOMALY_MULTIPLIER), populateMetricValues(NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_LOG_FLUSH_TIME_MS / 10 * LOG_FLUSH_TIME_MS_VARIANCE_RATIO), METRIC_HISTORY_WINDOW_SIZE, BROKER_ENTITIES.get(0))); for (int i = 1; i < BROKER_ENTITIES.size(); i++) { currentMetrics.putAll(createCurrentMetrics(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS / 10), CURRENT_METRIC_WINDOW, BROKER_ENTITIES.get(i))); history.putAll(createHistory(populateMetricValues(NORMAL_BYTES_IN_RATE, NORMAL_BYTES_IN_RATE, NORMAL_LOG_FLUSH_TIME_MS / 10), populateMetricValues(NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_BYTES_IN_RATE * BYTE_IN_RATE_VARIANCE_RATIO, NORMAL_LOG_FLUSH_TIME_MS / 10 * LOG_FLUSH_TIME_MS_VARIANCE_RATIO), METRIC_HISTORY_WINDOW_SIZE, BROKER_ENTITIES.get(i))); } Collection<MetricAnomaly<BrokerEntity>> anomalies = slowBrokerFinder.metricAnomalies(history, currentMetrics); assertEquals(0, anomalies.size()); } |
MaintenanceEventTopicReader implements MaintenanceEventReader { @Override public Set<MaintenanceEvent> readEvents(Duration timeout) throws SamplingException { LOG.debug("Reading maintenance events."); long eventReadPeriodEndMs = _kafkaCruiseControl.timeMs(); if (refreshPartitionAssignment()) { _lastEventReadPeriodEndTimeMs = eventReadPeriodEndMs; return Collections.emptySet(); } long timeoutEndMs = eventReadPeriodEndMs + timeout.toMillis(); Set<MaintenanceEvent> maintenanceEvents = new HashSet<>(); try { Map<TopicPartition, Long> endOffsets = seekToRelevantOffsets(); LOG.debug("Started to consume from maintenance event topic partitions {}.", _currentPartitionAssignment); _consumer.resume(_consumer.paused()); Set<TopicPartition> partitionsToPause = new HashSet<>(); do { ConsumerRecords<String, MaintenancePlan> records = _consumer.poll(timeout); for (ConsumerRecord<String, MaintenancePlan> record : records) { if (record == null) { LOG.warn("Cannot parse record, please update your Cruise Control version."); continue; } long planGenerationTimeMs = record.value().timeMs(); if (planGenerationTimeMs + _maintenancePlanExpirationMs < eventReadPeriodEndMs) { LOG.warn("Discarding the expired plan {}. (Expired: {} Evaluated: {}).", record.value(), planGenerationTimeMs + _maintenancePlanExpirationMs, eventReadPeriodEndMs); } else if (planGenerationTimeMs >= eventReadPeriodEndMs) { TopicPartition tp = new TopicPartition(record.topic(), record.partition()); LOG.debug("Saw plan {} generated after the end time of event read period {}. Pausing {} at offset {}.", record.value(), eventReadPeriodEndMs, tp, record.offset()); partitionsToPause.add(tp); } else { addMaintenancePlan(record.value(), maintenanceEvents); } } if (!partitionsToPause.isEmpty()) { _consumer.pause(partitionsToPause); partitionsToPause.clear(); } } while (!consumptionDone(_consumer, endOffsets) && _kafkaCruiseControl.timeMs() < timeoutEndMs); if (maintenanceEvents.size() > 0) { LOG.info("Retrieved {} maintenance plans from partitions {} (range [{},{}]).", maintenanceEvents.size(), _currentPartitionAssignment, _lastEventReadPeriodEndTimeMs, eventReadPeriodEndMs); } } finally { _lastEventReadPeriodEndTimeMs = eventReadPeriodEndMs; } return maintenanceEvents; } @Override Set<MaintenanceEvent> readEvents(Duration timeout); @Override void configure(Map<String, ?> configs); @Override void close(); static final String MAINTENANCE_PLAN_EXPIRATION_MS_CONFIG; static final long DEFAULT_MAINTENANCE_PLAN_EXPIRATION_MS; static final String MAINTENANCE_EVENT_TOPIC_CONFIG; static final String DEFAULT_MAINTENANCE_EVENT_TOPIC; static final String MAINTENANCE_EVENT_TOPIC_REPLICATION_FACTOR_CONFIG; static final short DEFAULT_MAINTENANCE_EVENT_TOPIC_REPLICATION_FACTOR; static final String MAINTENANCE_EVENT_TOPIC_PARTITION_COUNT_CONFIG; static final int DEFAULT_MAINTENANCE_EVENT_TOPIC_PARTITION_COUNT; static final String MAINTENANCE_EVENT_TOPIC_RETENTION_MS_CONFIG; static final long DEFAULT_MAINTENANCE_EVENT_TOPIC_RETENTION_TIME_MS; static final Duration CONSUMER_CLOSE_TIMEOUT; static final String CONSUMER_CLIENT_ID_PREFIX; static final long INIT_MAINTENANCE_HISTORY_MS; } | @Test public void testMaintenanceEventTopicCreationUpdateAndRead() throws ExecutionException, InterruptedException, SamplingException { verify(TEST_TOPIC_PARTITION_COUNT, TEST_TOPIC_REPLICATION_FACTOR, TEST_TOPIC_RETENTION_TIME_MS, false); String newPartitionCount = String.valueOf(Integer.parseInt(TEST_TOPIC_PARTITION_COUNT) * 2); String newRF = String.valueOf(Short.parseShort(TEST_TOPIC_REPLICATION_FACTOR) + 1); String newRetentionMs = String.valueOf(Long.MAX_VALUE); KafkaCruiseControl mockKafkaCruiseControl = EasyMock.mock(KafkaCruiseControl.class); Map<String, Object> parameterConfigOverrides = new HashMap<>(4); parameterConfigOverrides.put(KAFKA_CRUISE_CONTROL_OBJECT_CONFIG, mockKafkaCruiseControl); parameterConfigOverrides.put(MAINTENANCE_EVENT_TOPIC_REPLICATION_FACTOR_CONFIG, newRF); parameterConfigOverrides.put(MAINTENANCE_EVENT_TOPIC_PARTITION_COUNT_CONFIG, newPartitionCount); parameterConfigOverrides.put(MAINTENANCE_EVENT_TOPIC_RETENTION_MS_CONFIG, newRetentionMs); long currentMockTime = TEST_REBALANCE_PLAN_TIME + DEFAULT_MAINTENANCE_PLAN_EXPIRATION_MS; EasyMock.expect(mockKafkaCruiseControl.timeMs()).andReturn(currentMockTime).anyTimes(); EasyMock.expect(mockKafkaCruiseControl.config()).andReturn(_config).anyTimes(); EasyMock.replay(mockKafkaCruiseControl); MaintenanceEventReader maintenanceEventReader = _config.getConfiguredInstance(AnomalyDetectorConfig.MAINTENANCE_EVENT_READER_CLASS_CONFIG, MaintenanceEventTopicReader.class, parameterConfigOverrides); assertNotNull(maintenanceEventReader); verify(newPartitionCount, newRF, newRetentionMs, true); Set<MaintenanceEvent> events = maintenanceEventReader.readEvents(TEST_TIMEOUT); EasyMock.verify(mockKafkaCruiseControl); assertEquals(1, events.size()); MaintenanceEvent maintenanceEvent = events.iterator().next(); assertEquals(MAINTENANCE_EVENT, maintenanceEvent.anomalyType()); assertEquals(currentMockTime, maintenanceEvent.detectionTimeMs()); assertEquals(REBALANCE, maintenanceEvent.maintenanceEventType()); } |
AnomalyDetectorManager { public void shutdown() { LOG.info("Shutting down anomaly detector."); synchronized (_shutdownLock) { _shutdown = true; } _anomalies.add(SHUTDOWN_ANOMALY); _maintenanceEventDetector.shutdown(); _detectorScheduler.shutdown(); KafkaCruiseControlUtils.closeAdminClientWithTimeout(_adminClient); try { _detectorScheduler.awaitTermination(SCHEDULER_SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (!_detectorScheduler.isTerminated()) { LOG.warn("The sampling scheduler failed to shutdown in " + SCHEDULER_SHUTDOWN_TIMEOUT_MS + " ms."); } } catch (InterruptedException e) { LOG.warn("Interrupted while waiting for anomaly detector to shutdown."); } _brokerFailureDetector.shutdown(); _anomalyLoggerExecutor.shutdownNow(); LOG.info("Anomaly detector shutdown completed."); } AnomalyDetectorManager(KafkaCruiseControl kafkaCruiseControl, Time time, MetricRegistry dropwizardMetricRegistry); AnomalyDetectorManager(PriorityBlockingQueue<Anomaly> anomalies,
AdminClient adminClient,
long anomalyDetectionIntervalMs,
KafkaCruiseControl kafkaCruiseControl,
AnomalyNotifier anomalyNotifier,
GoalViolationDetector goalViolationDetector,
BrokerFailureDetector brokerFailureDetector,
MetricAnomalyDetector metricAnomalyDetector,
DiskFailureDetector diskFailureDetector,
TopicAnomalyDetector topicAnomalyDetector,
MaintenanceEventDetector maintenanceEventDetector,
ScheduledExecutorService detectorScheduler); void startDetection(); void shutdown(); synchronized AnomalyDetectorState anomalyDetectorState(); void maybeClearOngoingAnomalyDetectionTimeMs(); void resetHasUnfixableGoals(); boolean setSelfHealingFor(AnomalyType anomalyType, boolean isSelfHealingEnabled); long numCheckedWithDelay(); void markSelfHealingFinished(String anomalyId); } | @Test public void testShutdown() throws InterruptedException { PriorityBlockingQueue<Anomaly> anomalies = new PriorityBlockingQueue<>(ANOMALY_DETECTOR_INITIAL_QUEUE_SIZE, anomalyComparator()); AnomalyNotifier mockAnomalyNotifier = EasyMock.createNiceMock(AnomalyNotifier.class); AdminClient mockAdminClient = EasyMock.createNiceMock(AdminClient.class); BrokerFailureDetector mockBrokerFailureDetector = EasyMock.createNiceMock(BrokerFailureDetector.class); GoalViolationDetector mockGoalViolationDetector = EasyMock.createNiceMock(GoalViolationDetector.class); MetricAnomalyDetector mockMetricAnomalyDetector = EasyMock.createNiceMock(MetricAnomalyDetector.class); TopicAnomalyDetector mockTopicAnomalyDetector = EasyMock.createNiceMock(TopicAnomalyDetector.class); MaintenanceEventDetector mockMaintenanceEventDetector = EasyMock.createNiceMock(MaintenanceEventDetector.class); DiskFailureDetector mockDiskFailureDetector = EasyMock.createNiceMock(DiskFailureDetector.class); KafkaCruiseControl mockKafkaCruiseControl = EasyMock.createNiceMock(KafkaCruiseControl.class); ScheduledExecutorService detectorScheduler = Executors.newScheduledThreadPool(2, new KafkaCruiseControlThreadFactory("AnomalyDetector", false, null)); AnomalyDetectorManager anomalyDetectorManager = new AnomalyDetectorManager(anomalies, mockAdminClient, MOCK_ANOMALY_DETECTION_INTERVAL_MS, mockKafkaCruiseControl, mockAnomalyNotifier, mockGoalViolationDetector, mockBrokerFailureDetector, mockMetricAnomalyDetector, mockDiskFailureDetector, mockTopicAnomalyDetector, mockMaintenanceEventDetector, detectorScheduler); anomalyDetectorManager.shutdown(); Thread t = new Thread(anomalyDetectorManager::shutdown); t.start(); t.join(30000L); assertEquals(0, anomalyDetectorManager.numSelfHealingStarted()); assertEquals(0, anomalyDetectorManager.numCheckedWithDelay()); assertTrue(detectorScheduler.isTerminated()); } |
TopicReplicationFactorAnomalyFinder implements TopicAnomalyFinder { @Override public Set<TopicAnomaly> topicAnomalies() { LOG.info("Start to detect topic replication factor anomaly."); Cluster cluster = _kafkaCruiseControl.kafkaCluster(); Set<String> topicsToCheck = new HashSet<>(); for (String topic : cluster.topics()) { if (_topicExcludedFromCheck.matcher(topic).matches()) { continue; } for (PartitionInfo partition : cluster.partitionsForTopic(topic)) { if (partition.replicas().length != _targetReplicationFactor) { topicsToCheck.add(topic); break; } } } refreshTopicMinISRCache(); if (!topicsToCheck.isEmpty()) { maybeRetrieveAndCacheTopicMinISR(topicsToCheck); Map<Short, Set<TopicReplicationFactorAnomalyEntry>> badTopicsByReplicationFactor = populateBadTopicsByReplicationFactor(topicsToCheck, cluster); if (!badTopicsByReplicationFactor.isEmpty()) { return Collections.singleton(createTopicReplicationFactorAnomaly(badTopicsByReplicationFactor, _targetReplicationFactor)); } } return Collections.emptySet(); } TopicReplicationFactorAnomalyFinder(); TopicReplicationFactorAnomalyFinder(KafkaCruiseControl kafkaCruiseControl,
short targetReplicationFactor,
AdminClient adminClient); @Override Set<TopicAnomaly> topicAnomalies(); @Override void configure(Map<String, ?> configs); static final String SELF_HEALING_TARGET_TOPIC_REPLICATION_FACTOR_CONFIG; static final String TOPIC_EXCLUDED_FROM_REPLICATION_FACTOR_CHECK; static final String DEFAULT_TOPIC_EXCLUDED_FROM_REPLICATION_FACTOR_CHECK; static final String TOPIC_REPLICATION_FACTOR_ANOMALY_CLASS_CONFIG; static final Class<?> DEFAULT_TOPIC_REPLICATION_FACTOR_ANOMALY_CLASS; static final String BAD_TOPICS_BY_REPLICATION_FACTOR_CONFIG; static final String TOPIC_REPLICATION_FACTOR_MARGIN_CONFIG; static final short DEFAULT_TOPIC_REPLICATION_FACTOR_MARGIN; static final String TOPIC_MIN_ISR_RECORD_RETENTION_TIME_MS_CONFIG; static final long DEFAULT_TOPIC_MIN_ISR_RECORD_RETENTION_TIME_MS; static final long DESCRIBE_TOPIC_CONFIG_TIMEOUT_MS; } | @Test public void testAnomalyDetection() throws InterruptedException, ExecutionException, TimeoutException { KafkaCruiseControl mockKafkaCruiseControl = mockKafkaCruiseControl(); AdminClient mockAdminClient = mockAdminClient((short) 1); TopicReplicationFactorAnomalyFinder anomalyFinder = new TopicReplicationFactorAnomalyFinder(mockKafkaCruiseControl, TARGET_TOPIC_REPLICATION_FACTOR, mockAdminClient); Set<TopicAnomaly> topicAnomalies = anomalyFinder.topicAnomalies(); assertEquals(1, topicAnomalies.size()); EasyMock.verify(mockKafkaCruiseControl, mockAdminClient); }
@Test public void testSkipTopicWithLargeMinISR() throws InterruptedException, ExecutionException, TimeoutException { KafkaCruiseControl mockKafkaCruiseControl = mockKafkaCruiseControl(); AdminClient mockAdminClient = mockAdminClient((short) 2); TopicReplicationFactorAnomalyFinder anomalyFinder = new TopicReplicationFactorAnomalyFinder(mockKafkaCruiseControl, TARGET_TOPIC_REPLICATION_FACTOR, mockAdminClient); Set<TopicAnomaly> topicAnomalies = anomalyFinder.topicAnomalies(); assertTrue(topicAnomalies.isEmpty()); EasyMock.verify(mockKafkaCruiseControl, mockAdminClient); } |
MaintenanceEvent extends KafkaAnomaly { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("{Handling %s", _maintenanceEventType)); if (_topicsWithRFUpdate != null) { sb.append(String.format(" by desired RF: [%s]", _topicsWithRFUpdate)); } else if (_brokers != null) { sb.append(String.format(" for brokers: [%s]", _brokers)); } sb.append("}"); return sb.toString(); } @Override Supplier<String> reasonSupplier(); @Override AnomalyType anomalyType(); MaintenanceEventType maintenanceEventType(); @Override boolean fix(); @Override String toString(); @Override void configure(Map<String, ?> configs); static final String MAINTENANCE_EVENT_TYPE_CONFIG; static final String BROKERS_OBJECT_CONFIG; static final String TOPICS_WITH_RF_UPDATE_CONFIG; } | @Test public void testToStringBeforeConfiguration() { assertNotNull(new MaintenanceEvent().toString()); } |
AnomalyUtils { public static Pattern buildTopicRegex(Set<String> stringsToMatch) { StringJoiner sj = new StringJoiner("|"); stringsToMatch.forEach(sj::add); return Pattern.compile(sj.toString()); } private AnomalyUtils(); static KafkaCruiseControl extractKafkaCruiseControlObjectFromConfig(Map<String, ?> configs,
AnomalyType anomalyType); static boolean isLoadMonitorReady(LoadMonitorTaskRunner.LoadMonitorTaskRunnerState loadMonitorTaskRunnerState); static Pattern buildTopicRegex(Set<String> stringsToMatch); static int parseAndGetConfig(Map<String, Object> config,
String key,
int defaultValue,
Predicate<Integer> illegalValueCheck); static double parseAndGetConfig(Map<String, Object> config,
String key,
double defaultValue,
Predicate<Double> illegalValueCheck); } | @Test public void testBuildTopicRegex() { Set<String> topicsToMatch = new HashSet<>(2); topicsToMatch.add(TOPIC1); topicsToMatch.add(TOPIC2); Pattern pattern = buildTopicRegex(topicsToMatch); assertTrue(pattern.matcher(TOPIC1).matches()); assertTrue(pattern.matcher(TOPIC2).matches()); assertFalse(pattern.matcher(TOPIC3).matches()); } |
KafkaAssignerDiskUsageDistributionGoal implements Goal { boolean canSwap(Replica r1, Replica r2, ClusterModel clusterModel) { boolean inSameRack = r1.broker().rack() == r2.broker().rack() && r1.broker() != r2.broker(); boolean rackAware = !clusterModel.partition(r1.topicPartition()).partitionRacks().contains(r2.broker().rack()) && !clusterModel.partition(r2.topicPartition()).partitionRacks().contains(r1.broker().rack()); boolean sameRole = r1.isLeader() == r2.isLeader(); return (inSameRack || rackAware) && sameRole; } KafkaAssignerDiskUsageDistributionGoal(); KafkaAssignerDiskUsageDistributionGoal(BalancingConstraint constraint); @Override ClusterModelStatsComparator clusterModelStatsComparator(); @Override void configure(Map<String, ?> configs); @Override ModelCompletenessRequirements clusterModelCompletenessRequirements(); @Override boolean optimize(ClusterModel clusterModel, Set<Goal> optimizedGoals, OptimizationOptions optimizationOptions); @Override ActionAcceptance actionAcceptance(BalancingAction action, ClusterModel clusterModel); @Override String name(); @Override void finish(); @Override boolean isHardGoal(); } | @Test public void testCanSwap() { KafkaAssignerDiskUsageDistributionGoal goal = new KafkaAssignerDiskUsageDistributionGoal(); ClusterModel clusterModel = createClusterModel(); Replica r1 = clusterModel.broker(0).replica(T0P0); Replica r2 = clusterModel.broker(1).replica(T2P0); assertTrue("Replicas in the same rack should be good to swap", goal.canSwap(r1, r2, clusterModel)); assertTrue("Replicas in the same rack should be good to swap", goal.canSwap(r2, r1, clusterModel)); r2 = clusterModel.broker(1).replica(T1P0); assertFalse("Should not be able to swap replica with different roles.", goal.canSwap(r1, r2, clusterModel)); assertFalse("Should not be able to swap replica with different roles.", goal.canSwap(r2, r1, clusterModel)); r2 = clusterModel.broker(2).replica(T2P1); assertFalse("Should not be able to put two replicas in the same broker", goal.canSwap(r1, r2, clusterModel)); assertFalse("Should not be able to put two replicas in the same broker", goal.canSwap(r2, r1, clusterModel)); r2 = clusterModel.broker(3).replica(T2P2); assertFalse("Should not be able to put two replicas in the same rack", goal.canSwap(r1, r2, clusterModel)); assertFalse("Should not be able to put two replicas in the same rack", goal.canSwap(r2, r1, clusterModel)); r1 = clusterModel.broker(3).replica(T0P2); r2 = clusterModel.broker(4).replica(T1P2); assertTrue("Should be able to swap", goal.canSwap(r1, r2, clusterModel)); assertTrue("Should be able to swap", goal.canSwap(r2, r1, clusterModel)); } |
KafkaAssignerDiskUsageDistributionGoal implements Goal { Replica findReplicaToSwapWith(Replica replica, NavigableSet<ReplicaWrapper> sortedReplicasToSearch, double targetSize, double minSize, double maxSize, ClusterModel clusterModel) { if (minSize > maxSize) { return null; } NavigableSet<ReplicaWrapper> candidates = sortedReplicasToSearch.subSet(ReplicaWrapper.greaterThan(minSize), false, ReplicaWrapper.lessThan(maxSize), false); if (candidates.isEmpty()) { return null; } Iterator<ReplicaWrapper> ascendingLargerIter = null; Iterator<ReplicaWrapper> descendingLessIter = null; if (targetSize <= minSize) { ascendingLargerIter = candidates.iterator(); } else if (targetSize >= maxSize) { descendingLessIter = candidates.descendingIterator(); } else { ascendingLargerIter = candidates.tailSet(ReplicaWrapper.greaterThanOrEqualsTo(targetSize), true).iterator(); descendingLessIter = candidates.headSet(ReplicaWrapper.lessThanOrEqualsTo(targetSize), true).descendingIterator(); } ReplicaWrapper low = null; ReplicaWrapper high = null; ReplicaWrapper candidateReplica = null; while (true) { if (candidateReplica == high) { high = ascendingLargerIter != null && ascendingLargerIter.hasNext() ? ascendingLargerIter.next() : null; } if (candidateReplica == low) { low = descendingLessIter != null && descendingLessIter.hasNext() ? descendingLessIter.next() : null; } if (high == null && low == null) { return null; } else if (high == null) { candidateReplica = low; } else if (low == null) { candidateReplica = high; } else { double lowDiff = targetSize - low.size(); double highDiff = high.size() - targetSize; candidateReplica = lowDiff <= highDiff ? low : high; } if (canSwap(replica, candidateReplica.replica(), clusterModel)) { return candidateReplica.replica(); } } } KafkaAssignerDiskUsageDistributionGoal(); KafkaAssignerDiskUsageDistributionGoal(BalancingConstraint constraint); @Override ClusterModelStatsComparator clusterModelStatsComparator(); @Override void configure(Map<String, ?> configs); @Override ModelCompletenessRequirements clusterModelCompletenessRequirements(); @Override boolean optimize(ClusterModel clusterModel, Set<Goal> optimizedGoals, OptimizationOptions optimizationOptions); @Override ActionAcceptance actionAcceptance(BalancingAction action, ClusterModel clusterModel); @Override String name(); @Override void finish(); @Override boolean isHardGoal(); } | @Test public void testFindReplicaToSwapWith() { Properties props = KafkaCruiseControlUnitTestUtils.getKafkaCruiseControlProperties(); props.setProperty(AnalyzerConfig.MAX_REPLICAS_PER_BROKER_CONFIG, Long.toString(10L)); props.setProperty(AnalyzerConfig.DISK_BALANCE_THRESHOLD_CONFIG, "1.05"); BalancingConstraint balancingConstraint = new BalancingConstraint(new KafkaCruiseControlConfig(props)); KafkaAssignerDiskUsageDistributionGoal goal = new KafkaAssignerDiskUsageDistributionGoal(balancingConstraint); ClusterModel clusterModel = createClusterModel(); Broker b2 = clusterModel.broker(2); Replica r = b2.replica(T0P1); assertNull(goal.findReplicaToSwapWith(r, sortedReplicaAscend(clusterModel.broker(1)), 30, 10, 90, clusterModel)); findReplicaToSwapWithAndVerify(Arrays.asList(-1.0, 5.0, 10.0, 20.0, 21.0, 60.0, 100.0), Arrays.asList(T0P0, T0P0, T0P0, T0P0, T1P1, T1P1, T1P1), 9, 90, r, 3, clusterModel, goal); findReplicaToSwapWithAndVerify(Arrays.asList(-1.0, 5.0, 10.0, 20.0, 21.0, 60.0, 100.0), Arrays.asList(T1P1, T1P1, T1P1, T1P1, T1P1, T1P1, T1P1), 10, 31, r, 3, clusterModel, goal); findReplicaToSwapWithAndVerify(Arrays.asList(-1.0, 5.0, 10.0, 20.0, 21.0, 60.0, 100.0), Arrays.asList(T0P0, T0P0, T0P0, T0P0, T0P0, T0P0, T0P0), 9, 30, r, 3, clusterModel, goal); findReplicaToSwapWithAndVerify(Arrays.asList(-1.0, 5.0, 10.0, 20.0, 21.0, 60.0, 100.0), Arrays.asList(null, null, null, null, null, null, null), 10, 30, r, 3, clusterModel, goal); } |
KafkaAssignerDiskUsageDistributionGoal implements Goal { boolean swapReplicas(BrokerAndSortedReplicas toSwap, BrokerAndSortedReplicas toSwapWith, double meanDiskUsage, ClusterModel clusterModel, Set<String> excludedTopics) { if (LOG.isTraceEnabled()) { LOG.trace("Swapping replicas between broker {}({}) and broker {}({})", toSwap.broker().id(), dWrap(brokerSize(toSwap)), toSwapWith.broker().id(), dWrap(brokerSize(toSwapWith))); } double sizeToChange = toSwap.broker().capacityFor(DISK) * meanDiskUsage - brokerSize(toSwap); NavigableSet<ReplicaWrapper> sortedReplicasToSwap = sortReplicasAscend(toSwap, excludedTopics); NavigableSet<ReplicaWrapper> sortedLeadersToSwapWith = sortReplicasAscend(toSwapWith, excludedTopics); NavigableSet<ReplicaWrapper> sortedFollowersToSwapWith = sortedFollowerReplicas(toSwapWith, excludedTopics); Iterator<ReplicaWrapper> toSwapIter = sizeToChange > 0 ? sortedReplicasToSwap.iterator() : sortedReplicasToSwap.descendingIterator(); while (toSwapIter.hasNext()) { Replica replicaToSwap = toSwapIter.next().replica(); if (excludedTopics.contains(replicaToSwap.topicPartition().topic())) { continue; } if (!possibleToMove(replicaToSwap, toSwapWith.broker(), clusterModel)) { continue; } NavigableSet<ReplicaWrapper> sortedReplicasToSwapWith = replicaToSwap.isLeader() ? sortedLeadersToSwapWith : sortedFollowersToSwapWith; double sizeToSwap = replicaSize(replicaToSwap); if (sizeToChange < 0 && sizeToSwap == 0) { break; } double maxSize = Double.MAX_VALUE; double minSize = Double.MIN_VALUE; if (sizeToChange > 0) { minSize = sizeToSwap; double maxSizeOfBrokerToSwap = diskUsage(toSwapWith) * toSwap.broker().capacityFor(DISK); double currentSizeOfBrokerToSwap = brokerSize(toSwap); maxSize = Math.min(maxSize, maxSizeOfBrokerToSwap - (currentSizeOfBrokerToSwap - sizeToSwap)); double minSizeOfBrokerToSwapWith = diskUsage(toSwap) * toSwapWith.broker().capacityFor(DISK); double currentSizeOfBrokerToSwapWith = brokerSize(toSwapWith); maxSize = Math.min(maxSize, (currentSizeOfBrokerToSwapWith + sizeToSwap) - minSizeOfBrokerToSwapWith); } else { maxSize = sizeToSwap; double minSizeOfBrokerToSwap = diskUsage(toSwapWith) * toSwap.broker().capacityFor(DISK); double currentSizeOfBrokerToSwap = brokerSize(toSwap); minSize = Math.max(minSize, minSizeOfBrokerToSwap - (currentSizeOfBrokerToSwap - sizeToSwap)); double maxSizeOfBrokerToSwapWith = diskUsage(toSwap) * toSwapWith.broker().capacityFor(DISK); double currentSizeOfBrokerToSwapWith = brokerSize(toSwapWith); minSize = Math.max(minSize, (currentSizeOfBrokerToSwapWith + sizeToSwap) - maxSizeOfBrokerToSwapWith); } minSize += REPLICA_CONVERGENCE_DELTA; maxSize -= REPLICA_CONVERGENCE_DELTA; double targetSize = sizeToSwap + sizeToChange; if (LOG.isTraceEnabled()) { LOG.trace("replicaToSwap: {}(size={}), targetSize={}, minSize={}, maxSize={}", replicaToSwap, dWrap(replicaSize(replicaToSwap)), dWrap(targetSize), dWrap(minSize), dWrap(maxSize)); } Replica replicaToSwapWith = sortedReplicasToSwapWith.isEmpty() ? null : findReplicaToSwapWith(replicaToSwap, sortedReplicasToSwapWith, targetSize, minSize, maxSize, clusterModel); if (replicaToSwapWith != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found replica to swap. Swapping {}({}) on broker {}({}) and {}({}) on broker {}({})", replicaToSwap.topicPartition(), dWrap(replicaSize(replicaToSwap)), toSwap.broker().id(), dWrap(brokerSize(toSwap)), replicaToSwapWith.topicPartition(), dWrap(replicaSize(replicaToSwapWith)), toSwapWith.broker().id(), dWrap(brokerSize(toSwapWith))); } clusterModel.relocateReplica(replicaToSwapWith.topicPartition(), toSwapWith.broker().id(), toSwap.broker().id()); clusterModel.relocateReplica(replicaToSwap.topicPartition(), toSwap.broker().id(), toSwapWith.broker().id()); toSwap.sortedReplicas().remove(replicaToSwap); toSwap.sortedReplicas().add(replicaToSwapWith); toSwapWith.sortedReplicas().remove(replicaToSwapWith); toSwapWith.sortedReplicas().add(replicaToSwap); return true; } } LOG.trace("Nothing to swap between broker {} and broker {}", toSwap.broker().id(), toSwapWith.broker().id()); return false; } KafkaAssignerDiskUsageDistributionGoal(); KafkaAssignerDiskUsageDistributionGoal(BalancingConstraint constraint); @Override ClusterModelStatsComparator clusterModelStatsComparator(); @Override void configure(Map<String, ?> configs); @Override ModelCompletenessRequirements clusterModelCompletenessRequirements(); @Override boolean optimize(ClusterModel clusterModel, Set<Goal> optimizedGoals, OptimizationOptions optimizationOptions); @Override ActionAcceptance actionAcceptance(BalancingAction action, ClusterModel clusterModel); @Override String name(); @Override void finish(); @Override boolean isHardGoal(); } | @Test public void testSwapReplicas() { Properties props = KafkaCruiseControlUnitTestUtils.getKafkaCruiseControlProperties(); props.setProperty(AnalyzerConfig.MAX_REPLICAS_PER_BROKER_CONFIG, Long.toString(10L)); props.setProperty(AnalyzerConfig.DISK_BALANCE_THRESHOLD_CONFIG, "1.05"); BalancingConstraint balancingConstraint = new BalancingConstraint(new KafkaCruiseControlConfig(props)); KafkaAssignerDiskUsageDistributionGoal goal = new KafkaAssignerDiskUsageDistributionGoal(balancingConstraint); ClusterModel clusterModel = createClusterModel(); Comparator<Replica> replicaComparator = Comparator.comparingDouble((Replica r) -> r.load().expectedUtilizationFor(DISK)) .thenComparing(r -> r); double meanDiskUsage = clusterModel.load().expectedUtilizationFor(DISK) / clusterModel.capacityFor(DISK); assertTrue(goal.swapReplicas(new BrokerAndSortedReplicas(clusterModel.broker(0), replicaComparator), new BrokerAndSortedReplicas(clusterModel.broker(1), replicaComparator), meanDiskUsage, clusterModel, Collections.emptySet())); assertFalse(goal.swapReplicas(new BrokerAndSortedReplicas(clusterModel.broker(0), replicaComparator), new BrokerAndSortedReplicas(clusterModel.broker(2), replicaComparator), meanDiskUsage, clusterModel, Collections.emptySet())); assertTrue(goal.swapReplicas(new BrokerAndSortedReplicas(clusterModel.broker(2), replicaComparator), new BrokerAndSortedReplicas(clusterModel.broker(3), replicaComparator), meanDiskUsage, clusterModel, Collections.emptySet())); } |
GoalOptimizer implements Runnable { @Override public void run() { _proposalPrecomputingSchedulerThread = Thread.currentThread(); LOG.info("Starting proposal candidate computation."); while (!_shutdown && _numPrecomputingThreads > 0) { LoadMonitorTaskRunner.LoadMonitorTaskRunnerState loadMonitorTaskRunnerState = _loadMonitor.taskRunnerState(); long sleepTime = _proposalExpirationMs; if (loadMonitorTaskRunnerState == LOADING || loadMonitorTaskRunnerState == BOOTSTRAPPING) { LOG.info("Skipping proposal precomputing because load monitor is in " + loadMonitorTaskRunnerState + " state."); sleepTime = 30000L; } else if (!_loadMonitor.meetCompletenessRequirements(_requirementsWithAvailableValidWindows)) { LOG.info("Skipping proposal precomputing because load monitor does not have enough snapshots."); sleepTime = 30000L; } else { try { if (!validCachedProposal()) { if (LOG.isDebugEnabled()) { LOG.debug("Invalidated cache. Model generation (cached: {}, current: {}).{}", _cachedProposals == null ? null : _cachedProposals.modelGeneration(), _loadMonitor.clusterModelGeneration(), _cachedProposals == null ? "" : String.format(" Cached was excluding default topics: %s.", _cachedProposals.excludedTopics())); } clearCachedProposal(); long start = System.nanoTime(); computeCachedProposal(_allowCapacityEstimationOnProposalPrecompute); _proposalComputationTimer.update(System.nanoTime() - start, TimeUnit.NANOSECONDS); } else { LOG.debug("Skipping proposal precomputing because the cached proposal result is still valid. " + "Cached generation: {}", _cachedProposals.modelGeneration()); } } catch (KafkaCruiseControlException e) { sleepTime = 30000L; LOG.debug("Skipping proposal precomputing because there is an ongoing execution.", e); } } long deadline = _time.milliseconds() + sleepTime; if (!_shutdown && _time.milliseconds() < deadline) { try { Thread.sleep(deadline - _time.milliseconds()); } catch (InterruptedException e) { } } } } GoalOptimizer(KafkaCruiseControlConfig config,
LoadMonitor loadMonitor,
Time time,
MetricRegistry dropwizardMetricRegistry,
Executor executor); @Override void run(); void shutdown(); ModelCompletenessRequirements defaultModelCompletenessRequirements(); ModelCompletenessRequirements modelCompletenessRequirementsForPrecomputing(); AnalyzerState state(Cluster cluster); OptimizerResult optimizations(OperationProgress operationProgress, boolean allowCapacityEstimation); OptimizerResult optimizations(ClusterModel clusterModel, OperationProgress operationProgress); OptimizerResult optimizations(ClusterModel clusterModel,
List<Goal> goalsByPriority,
OperationProgress operationProgress); OptimizerResult optimizations(ClusterModel clusterModel,
List<Goal> goalsByPriority,
OperationProgress operationProgress,
Map<TopicPartition, List<ReplicaPlacementInfo>> initReplicaDistributionForProposalGeneration,
OptimizationOptions optimizationOptions); Set<String> excludedTopics(ClusterModel clusterModel, Pattern requestedExcludedTopics); } | @Test public void testNoPreComputingThread() { Properties props = new Properties(); props.setProperty(MonitorConfig.BOOTSTRAP_SERVERS_CONFIG, "bootstrap.servers"); props.setProperty(ExecutorConfig.ZOOKEEPER_CONNECT_CONFIG, "connect:1234"); props.setProperty(AnalyzerConfig.NUM_PROPOSAL_PRECOMPUTE_THREADS_CONFIG, "0"); props.setProperty(AnalyzerConfig.DEFAULT_GOALS_CONFIG, TestConstants.DEFAULT_GOALS_VALUES); KafkaCruiseControlConfig config = new KafkaCruiseControlConfig(props); GoalOptimizer goalOptimizer = new GoalOptimizer(config, EasyMock.mock(LoadMonitor.class), new SystemTime(), new MetricRegistry(), EasyMock.mock(Executor.class)); goalOptimizer.run(); } |
ContainerMetricUtils { public static double getContainerProcessCpuLoad(double cpuUtil) throws IOException { int logicalProcessorsOfNode = getAvailableProcessors(); double cpuQuota = getCpuQuota(); if (cpuQuota == NO_CPU_QUOTA) { return cpuUtil; } double cpuLimit = cpuQuota / getCpuPeriod(); double cpus = cpuUtil * logicalProcessorsOfNode; return cpus / cpuLimit; } private ContainerMetricUtils(); static double getContainerProcessCpuLoad(double cpuUtil); static final int NO_CPU_QUOTA; } | @Test public void testGetContainerProcessCpuLoad() throws Exception { mockGetContainerProcessCpuLoad(1, 100000.0, 100000.0, 1.0, 1.0); mockGetContainerProcessCpuLoad(1, 100000.0, 100000.0, 0.5, 0.5); mockGetContainerProcessCpuLoad(1, 50000.0, 100000.0, 0.5, 1.0); mockGetContainerProcessCpuLoad(1, 75000.0, 100000.0, 0.5, 0.66); mockGetContainerProcessCpuLoad(2, 100000.0, 100000.0, 0.5, 1.0); mockGetContainerProcessCpuLoad(2, 200000.0, 100000.0, 1.0, 1.0); mockGetContainerProcessCpuLoad(2, 25000.0, 100000.0, 0.125, 1.0); mockGetContainerProcessCpuLoad(2, 2500.0, 100000.0, 0.0125, 1.0); mockGetContainerProcessCpuLoad(2, ContainerMetricUtils.NO_CPU_QUOTA, 100000.0, 0.125, 0.125); } |
RichTextElementConverter { public RichTextElement convert(RichTextElement orig) { if (orig.getValue() == null) { return orig; } orig.setValue(resolveLinks(orig)); orig.setValue(resolveLinkedItems(orig)); if (richTextElementResolver != null) { orig.setValue(richTextElementResolver.resolve(orig.getValue())); } return orig; } RichTextElementConverter(
ContentLinkUrlResolver contentLinkUrlResolver,
BrokenLinkUrlResolver brokenLinkUrlResolver,
RichTextElementResolver richTextElementResolver,
TemplateEngineConfig templateEngineConfig,
StronglyTypedContentItemConverter stronglyTypedContentItemConverter); void process(List<ContentItem> orig); void process(ContentItem orig); RichTextElement convert(RichTextElement orig); } | @Test public void testLinkReplacement() { RichTextElementConverter converter = new RichTextElementConverter( Link::getUrlSlug, () -> "/404", content -> content, null, null); RichTextElement original = new RichTextElement(); original.setValue("<p>Each AeroPress comes with a <a href=\"\" data-item-id=\"65832c4e-8e9c-445f-a001-b9528d13dac8\">pack of filters</a> included in the <a href=\"\" data-item-id=\"not-found\">box</a>. See <a href=\"https: Link link = new Link(); link.setUrlSlug("/test me/\"<>&\u0080"); HashMap<String, Link> links = new HashMap<>(); links.put("65832c4e-8e9c-445f-a001-b9528d13dac8", link); original.setLinks(links); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p>Each AeroPress comes with a <a href=\"/test me/"<>&€\" data-item-id=\"65832c4e-8e9c-445f-a001-b9528d13dac8\">pack of filters</a> included in the <a href=\"/404\" data-item-id=\"not-found\">box</a>. See <a href=\"https: converted.getValue()); }
@Test public void testRecursiveResolverHaltsWithCycle() throws RenderingEngineMissingException { ThymeleafInlineContentItemsResolver resolver = new ThymeleafInlineContentItemsResolver(); ViewResolverConfiguration configuration = new ViewResolverConfiguration() .addPrefixes("customTemplateLocation/") .setSuffix(".template"); resolver.getTemplateEngine().setViewResolverConfiguration(configuration); TemplateEngineConfig templateEngineConfig = new TemplateEngineConfig(); templateEngineConfig.setResolvers(Collections.singletonList(resolver)); StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); stronglyTypedContentItemConverter.registerType(CustomItem.class); RichTextElementConverter converter = new RichTextElementConverter( null, null, null, templateEngineConfig, stronglyTypedContentItemConverter); RichTextElement original = new RichTextElement(); original.setLinkedItems(Collections.singletonList("donate_with_us")); ContentItem contentItem = new ContentItem(); contentItem.setLinkedItemProvider(() -> { ContentItem parentDonateWithUs = new ContentItem(); System parentSystem = new System(); parentSystem.setType("item"); parentDonateWithUs.setSystem(parentSystem); RichTextElement parentTextElement = new RichTextElement(); parentTextElement.setValue("<object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"donate_with_us\"></object>"); HashMap<String, Element> parentElements = new HashMap<>(); parentElements.put("message_text", parentTextElement); parentDonateWithUs.setElements(parentElements); parentDonateWithUs.setLinkedItemProvider(HashMap::new); parentDonateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); ContentItem donateWithUs = new ContentItem(); System system = new System(); system.setType("item"); donateWithUs.setSystem(system); TextElement textElement = new TextElement(); textElement.setValue("<object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"parent_donate_with_us\"></object>"); HashMap<String, Element> elements = new HashMap<>(); elements.put("message_text", textElement); donateWithUs.setElements(elements); donateWithUs.setLinkedItemProvider(HashMap::new); donateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); HashMap<String, ContentItem> linkedItems = new HashMap<>(); linkedItems.put("parent_donate_with_us", parentDonateWithUs); linkedItems.put("donate_with_us", donateWithUs); return linkedItems; }); contentItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); original.parent = contentItem; original.setValue( "<p><object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"parent_donate_with_us\"></object></p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p><custom><custom><object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"parent_donate_with_us\"></object></custom></custom></p>", converted.getValue()); }
@Test public void testLinkedItemsReplacement() { StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); stronglyTypedContentItemConverter.registerType(CustomItem.class); stronglyTypedContentItemConverter.registerInlineContentItemsResolver(new InlineContentItemsResolver<CustomItem>() { @Override public String resolve(CustomItem data) { return data.getMessageText(); } }); RichTextElementConverter converter = new RichTextElementConverter( null, null, null, null, stronglyTypedContentItemConverter); RichTextElement original = new RichTextElement(); original.setLinkedItems(Collections.singletonList("donate_with_us")); ContentItem contentItem = new ContentItem(); contentItem.setLinkedItemProvider(() -> { ContentItem donateWithUs = new ContentItem(); System system = new System(); system.setType("item"); donateWithUs.setSystem(system); TextElement textElement = new TextElement(); textElement.setValue("Please donate with us."); HashMap<String, Element> elements = new HashMap<>(); elements.put("message_text", textElement); donateWithUs.setElements(elements); donateWithUs.setLinkedItemProvider(HashMap::new); donateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); HashMap<String, ContentItem> linkedItems = new HashMap<>(); linkedItems.put("donate_with_us", donateWithUs); return linkedItems; }); contentItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); original.parent = contentItem; original.setValue( "<p><object type=\"application/kenticocloud\" data-type=\"item\" data-rel=\"link\" data-codename=\"donate_with_us\"></object></p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p>Please donate with us.</p>", converted.getValue()); }
@Test public void testModularContentReplacementWithUnexpectedDataAttributesAndOrder() { StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); stronglyTypedContentItemConverter.registerType(CustomItem.class); stronglyTypedContentItemConverter.registerInlineContentItemsResolver(new InlineContentItemsResolver<CustomItem>() { @Override public String resolve(CustomItem data) { return data.getMessageText(); } }); RichTextElementConverter converter = new RichTextElementConverter( null, null, null, null, stronglyTypedContentItemConverter); RichTextElement original = new RichTextElement(); original.setLinkedItems(Collections.singletonList("donate_with_us")); ContentItem contentItem = new ContentItem(); contentItem.setLinkedItemProvider(() -> { ContentItem donateWithUs = new ContentItem(); System system = new System(); system.setType("item"); donateWithUs.setSystem(system); TextElement textElement = new TextElement(); textElement.setValue("Please donate with us."); HashMap<String, Element> elements = new HashMap<>(); elements.put("message_text", textElement); donateWithUs.setElements(elements); donateWithUs.setLinkedItemProvider(HashMap::new); donateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); HashMap<String, ContentItem> modularContent = new HashMap<>(); modularContent.put("donate_with_us", donateWithUs); return modularContent; }); contentItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); original.parent = contentItem; original.setValue( "<p><object type=\"application/kenticocloud\" data-codename=\"donate_with_us\" new-value=\"unexpected\" data-new=\"unexpected\" data-type=\"item\" data-rel=\"link\"></object></p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p>Please donate with us.</p>", converted.getValue()); }
@Test public void testLinkedItemsReplacementWithDollarSign() { StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); stronglyTypedContentItemConverter.registerType(CustomItem.class); stronglyTypedContentItemConverter.registerInlineContentItemsResolver(new InlineContentItemsResolver<CustomItem>() { @Override public String resolve(CustomItem data) { return data.getMessageText(); } }); RichTextElementConverter converter = new RichTextElementConverter( null, null, null, null, stronglyTypedContentItemConverter); RichTextElement original = new RichTextElement(); original.setLinkedItems(Collections.singletonList("customer_winner")); ContentItem contentItem = new ContentItem(); contentItem.setLinkedItemProvider(() -> { ContentItem customerWinner = new ContentItem(); System system = new System(); system.setType("item"); customerWinner.setSystem(system); TextElement textElement = new TextElement(); textElement.setValue("You are our 1 millionth customer. Click here to claim your $1,000,000!"); HashMap<String, Element> elements = new HashMap<>(); elements.put("message_text", textElement); customerWinner.setElements(elements); customerWinner.setLinkedItemProvider(HashMap::new); customerWinner.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); HashMap<String, ContentItem> linkedItems = new HashMap<>(); linkedItems.put("customer_winner", customerWinner); return linkedItems; }); contentItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); original.parent = contentItem; original.setValue( "<p><object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"customer_winner\"></object></p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p>You are our 1 millionth customer. Click here to claim your $1,000,000!</p>", converted.getValue()); }
@Test public void testRecursiveLinkedItemsReplacement() { StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); stronglyTypedContentItemConverter.registerType(CustomItem.class); stronglyTypedContentItemConverter.registerInlineContentItemsResolver(new InlineContentItemsResolver<CustomItem>() { @Override public String resolve(CustomItem data) { return data.getMessageText(); } }); RichTextElementConverter converter = new RichTextElementConverter( null, null, null, null, stronglyTypedContentItemConverter); RichTextElement original = new RichTextElement(); original.setLinkedItems(Collections.singletonList("donate_with_us")); ContentItem contentItem = new ContentItem(); contentItem.setLinkedItemProvider(() -> { ContentItem parentDonateWithUs = new ContentItem(); System parentSystem = new System(); parentSystem.setType("item"); parentDonateWithUs.setSystem(parentSystem); RichTextElement parentTextElement = new RichTextElement(); parentTextElement.setValue("<object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"donate_with_us\"></object>"); HashMap<String, Element> parentElements = new HashMap<>(); parentElements.put("message_text", parentTextElement); parentDonateWithUs.setElements(parentElements); parentDonateWithUs.setLinkedItemProvider(HashMap::new); parentDonateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); ContentItem donateWithUs = new ContentItem(); System system = new System(); system.setType("item"); donateWithUs.setSystem(system); TextElement textElement = new TextElement(); textElement.setValue("Please donate with us."); HashMap<String, Element> elements = new HashMap<>(); elements.put("message_text", textElement); donateWithUs.setElements(elements); donateWithUs.setLinkedItemProvider(HashMap::new); donateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); HashMap<String, ContentItem> linkedItems = new HashMap<>(); linkedItems.put("parent_donate_with_us", parentDonateWithUs); linkedItems.put("donate_with_us", donateWithUs); return linkedItems; }); contentItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); original.parent = contentItem; original.setValue( "<p><object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"parent_donate_with_us\"></object></p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p>Please donate with us.</p>", converted.getValue()); }
@Test public void testRecursiveLinkedItemsReplacementWithLinks() { StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); stronglyTypedContentItemConverter.registerType(CustomItem.class); stronglyTypedContentItemConverter.registerInlineContentItemsResolver(new InlineContentItemsResolver<CustomItem>() { @Override public String resolve(CustomItem data) { return data.getMessageText(); } }); RichTextElementConverter converter = new RichTextElementConverter( Link::getUrlSlug, () -> "/404", content -> content, null, stronglyTypedContentItemConverter); RichTextElement original = new RichTextElement(); original.setLinkedItems(Collections.singletonList("donate_with_us")); ContentItem contentItem = new ContentItem(); contentItem.setLinkedItemProvider(() -> { ContentItem parentDonateWithUs = new ContentItem(); System parentSystem = new System(); parentSystem.setType("item"); parentDonateWithUs.setSystem(parentSystem); RichTextElement parentTextElement = new RichTextElement(); parentTextElement.setValue("<object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"donate_with_us\"></object>"); HashMap<String, Element> parentElements = new HashMap<>(); parentElements.put("message_text", parentTextElement); parentDonateWithUs.setElements(parentElements); parentDonateWithUs.setLinkedItemProvider(HashMap::new); parentDonateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); ContentItem donateWithUs = new ContentItem(); System system = new System(); system.setType("item"); donateWithUs.setSystem(system); RichTextElement richTextElement = new RichTextElement(); richTextElement.setValue("<p>Each AeroPress comes with a <a href=\"\" data-item-id=\"65832c4e-8e9c-445f-a001-b9528d13dac8\">pack of filters</a> included in the <a href=\"\" data-item-id=\"not-found\">box</a>.</p>"); Link link = new Link(); link.setUrlSlug("/test me/\"<>&\u0080"); HashMap<String, Link> links = new HashMap<>(); links.put("65832c4e-8e9c-445f-a001-b9528d13dac8", link); richTextElement.setLinks(links); HashMap<String, Element> elements = new HashMap<>(); elements.put("message_text", richTextElement); donateWithUs.setElements(elements); donateWithUs.setLinkedItemProvider(HashMap::new); donateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); HashMap<String, ContentItem> linkedItems = new HashMap<>(); linkedItems.put("parent_donate_with_us", parentDonateWithUs); linkedItems.put("donate_with_us", donateWithUs); return linkedItems; }); contentItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); original.parent = contentItem; original.setValue( "<p><object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"parent_donate_with_us\"></object></p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p><p>Each AeroPress comes with a <a href=\"/test me/"<>&€\" data-item-id=\"65832c4e-8e9c-445f-a001-b9528d13dac8\">pack of filters</a> included in the <a href=\"/404\" data-item-id=\"not-found\">box</a>.</p></p>", converted.getValue()); }
@Test public void testLinkedItemsReplacementSkippedIfNotThere() { StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); stronglyTypedContentItemConverter.registerType(CustomItem.class); stronglyTypedContentItemConverter.registerInlineContentItemsResolver(new InlineContentItemsResolver<CustomItem>() { @Override public String resolve(CustomItem data) { return data.getMessageText(); } }); RichTextElementConverter converter = new RichTextElementConverter( null, null, null, null, stronglyTypedContentItemConverter); RichTextElement original = new RichTextElement(); original.setLinkedItems(Collections.singletonList("donate_with_us")); ContentItem contentItem = new ContentItem(); contentItem.setLinkedItemProvider(HashMap::new); contentItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); original.parent = contentItem; original.setValue( "<p><object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"donate_with_us\"></object></p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p><object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"donate_with_us\"></object></p>", converted.getValue()); }
@Test public void testRichTextElementResolver() { RichTextElementConverter converter = new RichTextElementConverter( Link::getUrlSlug, () -> "/404", content -> "<p>replaced</p>", null, null); RichTextElement original = new RichTextElement(); original.setValue("<p>Each AeroPress comes with a <a href=\"\" data-item-id=\"65832c4e-8e9c-445f-a001-b9528d13dac8\">pack of filters</a> included in the <a href=\"\" data-item-id=\"not-found\">box</a>.</p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals("<p>replaced</p>", converted.getValue()); }
@Test public void testTemplateResolver() throws RenderingEngineMissingException { ThymeleafInlineContentItemsResolver resolver = new ThymeleafInlineContentItemsResolver(); ViewResolverConfiguration configuration = new ViewResolverConfiguration() .addPrefixes("customTemplateLocation/") .setSuffix(".template"); resolver.getTemplateEngine().setViewResolverConfiguration(configuration); TemplateEngineConfig templateEngineConfig = new TemplateEngineConfig(); templateEngineConfig.setResolvers(Collections.singletonList(resolver)); StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); stronglyTypedContentItemConverter.registerType(CustomItem.class); RichTextElementConverter converter = new RichTextElementConverter( null, null, null, templateEngineConfig, stronglyTypedContentItemConverter); RichTextElement original = new RichTextElement(); original.setLinkedItems(Collections.singletonList("donate_with_us")); ContentItem contentItem = new ContentItem(); contentItem.setLinkedItemProvider(() -> { ContentItem donateWithUs = new ContentItem(); System system = new System(); system.setType("item"); donateWithUs.setSystem(system); TextElement textElement = new TextElement(); textElement.setValue("Please donate with us."); HashMap<String, Element> elements = new HashMap<>(); elements.put("message_text", textElement); donateWithUs.setElements(elements); donateWithUs.setLinkedItemProvider(HashMap::new); donateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); HashMap<String, ContentItem> linkedItems = new HashMap<>(); linkedItems.put("donate_with_us", donateWithUs); return linkedItems; }); contentItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); original.parent = contentItem; original.setValue( "<p><object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"donate_with_us\"></object></p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p><custom>Please donate with us.</custom></p>", converted.getValue()); }
@Test public void testRecursiveTemplateResolver() throws RenderingEngineMissingException { ThymeleafInlineContentItemsResolver resolver = new ThymeleafInlineContentItemsResolver(); ViewResolverConfiguration configuration = new ViewResolverConfiguration() .addPrefixes("customTemplateLocation/") .setSuffix(".template"); resolver.getTemplateEngine().setViewResolverConfiguration(configuration); TemplateEngineConfig templateEngineConfig = new TemplateEngineConfig(); templateEngineConfig.setResolvers(Collections.singletonList(resolver)); StronglyTypedContentItemConverter stronglyTypedContentItemConverter = new StronglyTypedContentItemConverter(); stronglyTypedContentItemConverter.registerType(CustomItem.class); RichTextElementConverter converter = new RichTextElementConverter( null, null, null, templateEngineConfig, stronglyTypedContentItemConverter); RichTextElement original = new RichTextElement(); original.setLinkedItems(Collections.singletonList("donate_with_us")); ContentItem contentItem = new ContentItem(); contentItem.setLinkedItemProvider(() -> { ContentItem parentDonateWithUs = new ContentItem(); System parentSystem = new System(); parentSystem.setType("item"); parentDonateWithUs.setSystem(parentSystem); RichTextElement parentTextElement = new RichTextElement(); parentTextElement.setValue("<object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"donate_with_us\"></object>"); HashMap<String, Element> parentElements = new HashMap<>(); parentElements.put("message_text", parentTextElement); parentDonateWithUs.setElements(parentElements); parentDonateWithUs.setLinkedItemProvider(HashMap::new); parentDonateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); ContentItem donateWithUs = new ContentItem(); System system = new System(); system.setType("item"); donateWithUs.setSystem(system); TextElement textElement = new TextElement(); textElement.setValue("Please donate with us."); HashMap<String, Element> elements = new HashMap<>(); elements.put("message_text", textElement); donateWithUs.setElements(elements); donateWithUs.setLinkedItemProvider(HashMap::new); donateWithUs.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); HashMap<String, ContentItem> linkedItems = new HashMap<>(); linkedItems.put("parent_donate_with_us", parentDonateWithUs); linkedItems.put("donate_with_us", donateWithUs); return linkedItems; }); contentItem.setStronglyTypedContentItemConverter(stronglyTypedContentItemConverter); original.parent = contentItem; original.setValue( "<p><object type=\"application/kenticocloud\" data-type=\"item\" data-codename=\"parent_donate_with_us\"></object></p>"); RichTextElement converted = converter.convert(original); Assert.assertEquals( "<p><custom><custom>Please donate with us.</custom></custom></p>", converted.getValue()); } |
DeliveryParameterBuilder { public DeliveryParameterBuilder projection(String... elements) { if (elements != null) { nameValuePairs.add(new NameValuePair(ELEMENTS, String.join(",", elements))); } return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); } | @Test public void testProjection() { List<NameValuePair> params = DeliveryParameterBuilder.params().projection("foo", "bar").build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("elements", params.get(0).getName()); Assert.assertEquals("foo,bar", params.get(0).getValue()); } |
DeliveryParameterBuilder { public DeliveryParameterBuilder linkedItemsDepth(Integer depth) { if (depth != null) { nameValuePairs.add(new NameValuePair(DEPTH, depth.toString())); } return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); } | @Test public void testLinkedItemsDepth() { List<NameValuePair> params = DeliveryParameterBuilder.params().linkedItemsDepth(3).build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("depth", params.get(0).getName()); Assert.assertEquals("3", params.get(0).getValue()); } |
DeliveryParameterBuilder { public DeliveryParameterBuilder excludeLinkedItems() { nameValuePairs.add(new NameValuePair(DEPTH, "0")); return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); } | @Test public void testExcludeLinkedItems() { List<NameValuePair> params = DeliveryParameterBuilder.params().excludeLinkedItems().build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("depth", params.get(0).getName()); Assert.assertEquals("0", params.get(0).getValue()); } |
DeliveryParameterBuilder { public DeliveryParameterBuilder language(String language) { if (language != null) { nameValuePairs.add(new NameValuePair(LANGUAGE, language)); } return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); } | @Test public void testLanguage() { List<NameValuePair> params = DeliveryParameterBuilder.params().language(Locale.US.toLanguageTag()).build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("language", params.get(0).getName()); Assert.assertEquals("en-US", params.get(0).getValue()); } |
DeliveryParameterBuilder { public DeliveryParameterBuilder includeTotalCount() { nameValuePairs.add(new NameValuePair(INCLUDE_TOTAL_COUNT, "true")); return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); } | @Test public void testIncludeTotalCount() { List<NameValuePair> params = DeliveryParameterBuilder.params().includeTotalCount().build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("includeTotalCount", params.get(0).getName()); Assert.assertEquals("true", params.get(0).getValue()); } |
DeliveryClient { @SuppressWarnings("unused") public CompletionStage<ContentItemResponse> getItem(String contentItemCodename) { return getItem(contentItemCodename, Collections.emptyList()); } @SuppressWarnings("WeakerAccess") DeliveryClient(DeliveryOptions deliveryOptions); @SuppressWarnings({"ResultOfMethodCallIgnored", "WeakerAccess"}) DeliveryClient(DeliveryOptions deliveryOptions, TemplateEngineConfig templateEngineConfig); @SuppressWarnings("unused") DeliveryClient(String projectId); @SuppressWarnings("unused") DeliveryClient(String projectId, String previewApiKey); CompletionStage<ContentItemsListingResponse> getItems(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemsListingResponse> getItems(List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<List<T>> getItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<ContentItemResponse> getItem(String contentItemCodename); @SuppressWarnings("unused") CompletionStage<List<T>> getItems(Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getPageOfItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getNextPage(Page<T> currentPage); @SuppressWarnings("unused") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemResponse> getItem(String contentItemCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass, List<NameValuePair> params); CompletionStage<ContentTypesListingResponse> getTypes(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentTypesListingResponse> getTypes(List<NameValuePair> params); CompletionStage<ContentType> getType(String contentTypeCodeName); @SuppressWarnings("unused") CompletionStage<Element> getContentTypeElement(String contentTypeCodeName, String elementCodeName); @SuppressWarnings("WeakerAccess") CompletionStage<Element> getContentTypeElement(
String contentTypeCodeName, String elementCodeName, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") ContentLinkUrlResolver getContentLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setContentLinkUrlResolver(ContentLinkUrlResolver contentLinkUrlResolver); @SuppressWarnings("WeakerAccess") BrokenLinkUrlResolver getBrokenLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setBrokenLinkUrlResolver(BrokenLinkUrlResolver brokenLinkUrlResolver); @SuppressWarnings("WeakerAccess") RichTextElementResolver getRichTextElementResolver(); @SuppressWarnings("WeakerAccess") void setRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void addRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void registerType(String contentType, Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerType(Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerInlineContentItemsResolver(InlineContentItemsResolver resolver); @SuppressWarnings("WeakerAccess") void scanClasspathForMappings(String basePackage); @SuppressWarnings("WeakerAccess") void setCacheManager(AsyncCacheManager cacheManager); void setCacheManager(final CacheManager cacheManager); } | @Test public void testRetryWorksForRetryStatusCode() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; final AtomicBoolean sentError = new AtomicBoolean(false); this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items/on_roasts"), (request, response, context) -> { if (sentError.get()) { response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentItem.json") ) ); } else { response.setStatusCode(500); response.setEntity(new StringEntity("Response Error!")); sentError.set(true); } }); HttpHost httpHost = this.start(); String testServerUri = httpHost.toURI(); DeliveryOptions deliveryOptions = new DeliveryOptions(); deliveryOptions.setProjectId(projectId); deliveryOptions.setProductionEndpoint(testServerUri); deliveryOptions.setRetryAttempts(1); DeliveryClient client = new DeliveryClient(deliveryOptions); ContentItemResponse item = client.getItem("on_roasts").toCompletableFuture().get(); Assert.assertNotNull(item); Assert.assertTrue(sentError.get()); }
@Test public void testRetryStopsForJsonParseError() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; final int retryAttempts = 2; final AtomicInteger sentErrorCount = new AtomicInteger(0); this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items/on_roasts"), (request, response, context) -> { response.setEntity(new StringEntity("Response Error!")); sentErrorCount.getAndIncrement(); }); HttpHost httpHost = this.start(); String testServerUri = httpHost.toURI(); DeliveryOptions deliveryOptions = DeliveryOptions.builder() .projectId(projectId) .productionEndpoint(testServerUri) .retryAttempts(3) .build(); deliveryOptions.setProjectId(projectId); deliveryOptions.setProductionEndpoint(testServerUri); deliveryOptions.setRetryAttempts(retryAttempts); try { DeliveryClient client = new DeliveryClient(deliveryOptions); client.getItem("on_roasts") .toCompletableFuture() .get(); Assert.fail("Expected a failure exception"); } catch (ExecutionException e) { Assert.assertTrue(e.getCause() instanceof JsonParseException); } Assert.assertEquals(1, sentErrorCount.get()); }
@Test public void testRetryStopsOnNonRetryStatus() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; final int[] sentErrorCount = {0}; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items/error"), (request, response, context) -> { response.setStatusCode(404); response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleKenticoError.json") ) ); sentErrorCount[0] = sentErrorCount[0] + 1; }); HttpHost httpHost = this.start(); String testServerUri = httpHost.toURI(); DeliveryOptions deliveryOptions = new DeliveryOptions(); deliveryOptions.setProjectId(projectId); deliveryOptions.setProductionEndpoint(testServerUri); deliveryOptions.setRetryAttempts(1); try { DeliveryClient client = new DeliveryClient(deliveryOptions); client.getItem("error") .toCompletableFuture() .get(); Assert.fail("Expected KenticoErrorException"); } catch (ExecutionException e) { Assert.assertTrue(e.getCause() instanceof KenticoErrorException); KenticoErrorException error = (KenticoErrorException) e.getCause(); Assert.assertEquals("The requested content item 'error' was not found.", error.getMessage()); Assert.assertEquals("The requested content item 'error' was not found.", error.getKenticoError().getMessage()); } Assert.assertEquals(1, sentErrorCount[0]); }
@Test public void testGetItem() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items/on_roasts"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentItem.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); String testServerUri = httpHost.toURI(); client.getDeliveryOptions().setProductionEndpoint(testServerUri); client.getDeliveryOptions().retryAttempts = -1; ContentItemResponse item = client.getItem("on_roasts") .toCompletableFuture() .get(); Assert.assertNotNull(item); }
@Test public void testGetProductionKey() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; String productionApiKey = "production_api_key"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items/on_roasts"), (request, response, context) -> { Assert.assertEquals( "Bearer production_api_key", request.getHeaders("Authorization")[0].getValue()); response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentItem.json") ) ); }); HttpHost httpHost = this.start(); String testServerUri = httpHost.toURI(); DeliveryOptions options = new DeliveryOptions(); options.setProjectId(projectId); options.setProductionEndpoint(testServerUri); options.setProductionApiKey(productionApiKey); DeliveryClient client = new DeliveryClient(options); ContentItemResponse item = client.getItem("on_roasts") .toCompletableFuture() .get(); Assert.assertNotNull(item); }
@Test public void testWaitForLoadingNewContentHeader() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items/on_roasts"), (request, response, context) -> { Assert.assertEquals( "true", request.getHeaders("X-KC-Wait-For-Loading-New-Content")[0].getValue()); response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentItem.json") ) ); }); HttpHost httpHost = this.start(); String testServerUri = httpHost.toURI(); DeliveryOptions deliveryOptions = new DeliveryOptions(); deliveryOptions.setProjectId(projectId); deliveryOptions.setProductionEndpoint(testServerUri); deliveryOptions.setWaitForLoadingNewContent(true); DeliveryClient client = new DeliveryClient(deliveryOptions); ContentItemResponse item = client.getItem("on_roasts") .toCompletableFuture() .get(); Assert.assertNotNull(item); } |
DeliveryClient { public CompletionStage<ContentItemsListingResponse> getItems() { return getItems(Collections.emptyList()); } @SuppressWarnings("WeakerAccess") DeliveryClient(DeliveryOptions deliveryOptions); @SuppressWarnings({"ResultOfMethodCallIgnored", "WeakerAccess"}) DeliveryClient(DeliveryOptions deliveryOptions, TemplateEngineConfig templateEngineConfig); @SuppressWarnings("unused") DeliveryClient(String projectId); @SuppressWarnings("unused") DeliveryClient(String projectId, String previewApiKey); CompletionStage<ContentItemsListingResponse> getItems(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemsListingResponse> getItems(List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<List<T>> getItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<ContentItemResponse> getItem(String contentItemCodename); @SuppressWarnings("unused") CompletionStage<List<T>> getItems(Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getPageOfItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getNextPage(Page<T> currentPage); @SuppressWarnings("unused") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemResponse> getItem(String contentItemCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass, List<NameValuePair> params); CompletionStage<ContentTypesListingResponse> getTypes(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentTypesListingResponse> getTypes(List<NameValuePair> params); CompletionStage<ContentType> getType(String contentTypeCodeName); @SuppressWarnings("unused") CompletionStage<Element> getContentTypeElement(String contentTypeCodeName, String elementCodeName); @SuppressWarnings("WeakerAccess") CompletionStage<Element> getContentTypeElement(
String contentTypeCodeName, String elementCodeName, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") ContentLinkUrlResolver getContentLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setContentLinkUrlResolver(ContentLinkUrlResolver contentLinkUrlResolver); @SuppressWarnings("WeakerAccess") BrokenLinkUrlResolver getBrokenLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setBrokenLinkUrlResolver(BrokenLinkUrlResolver brokenLinkUrlResolver); @SuppressWarnings("WeakerAccess") RichTextElementResolver getRichTextElementResolver(); @SuppressWarnings("WeakerAccess") void setRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void addRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void registerType(String contentType, Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerType(Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerInlineContentItemsResolver(InlineContentItemsResolver resolver); @SuppressWarnings("WeakerAccess") void scanClasspathForMappings(String basePackage); @SuppressWarnings("WeakerAccess") void setCacheManager(AsyncCacheManager cacheManager); void setCacheManager(final CacheManager cacheManager); } | @Test public void testGetItems() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items"), (request, response, context) -> { String uri = String.format("http: List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(URI.create(uri), Charset.defaultCharset()); Map<String, String> params = convertNameValuePairsToMap(nameValuePairs); Assert.assertEquals(1, params.size()); Assert.assertEquals("/path1/path2/test-article", params.get("elements.url_pattern")); response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentItemList.json") ) ); }); HttpHost httpHost = this.start(); String testServerUri = httpHost.toURI(); DeliveryOptions deliveryOptions = new DeliveryOptions(); deliveryOptions.setProjectId(projectId); deliveryOptions.setProductionEndpoint(testServerUri); DeliveryClient client = new DeliveryClient(deliveryOptions, null); client.setContentLinkUrlResolver(Link::getUrlSlug); client.setBrokenLinkUrlResolver(() -> "/404"); client.addRichTextElementResolver(content -> String.format("%s%s", "<p>test</p>", content)); List<kentico.kontent.delivery.NameValuePair> urlPattern = DeliveryParameterBuilder.params().filterEquals("elements.url_pattern", "/path1/path2/test-article").build(); ContentItemsListingResponse items = client.getItems(urlPattern) .toCompletableFuture() .get(); Assert.assertNotNull(items); Assert.assertTrue(((RichTextElement) items.getItems().get(1).getElements().get("description")).getValue().contains("href=\"/on roasts\"")); Assert.assertTrue(((RichTextElement) items.getItems().get(1).getElements().get("description")).getValue().contains("<p>test</p>")); }
@Test public void testGetAllItems() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentItemList.json") ) )); HttpHost httpHost = this.start(); DeliveryOptions deliveryOptions = new DeliveryOptions(); deliveryOptions.setProductionEndpoint(httpHost.toURI()); deliveryOptions.setProjectId(projectId); DeliveryClient client = new DeliveryClient(deliveryOptions, null); ContentItemsListingResponse items = client.getItems() .toCompletableFuture() .get(); Assert.assertNotNull(items); } |
DeliveryClient { @SuppressWarnings("unused") public CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename) { return getTaxonomyGroup(taxonomyGroupCodename, Collections.emptyList()); } @SuppressWarnings("WeakerAccess") DeliveryClient(DeliveryOptions deliveryOptions); @SuppressWarnings({"ResultOfMethodCallIgnored", "WeakerAccess"}) DeliveryClient(DeliveryOptions deliveryOptions, TemplateEngineConfig templateEngineConfig); @SuppressWarnings("unused") DeliveryClient(String projectId); @SuppressWarnings("unused") DeliveryClient(String projectId, String previewApiKey); CompletionStage<ContentItemsListingResponse> getItems(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemsListingResponse> getItems(List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<List<T>> getItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<ContentItemResponse> getItem(String contentItemCodename); @SuppressWarnings("unused") CompletionStage<List<T>> getItems(Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getPageOfItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getNextPage(Page<T> currentPage); @SuppressWarnings("unused") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemResponse> getItem(String contentItemCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass, List<NameValuePair> params); CompletionStage<ContentTypesListingResponse> getTypes(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentTypesListingResponse> getTypes(List<NameValuePair> params); CompletionStage<ContentType> getType(String contentTypeCodeName); @SuppressWarnings("unused") CompletionStage<Element> getContentTypeElement(String contentTypeCodeName, String elementCodeName); @SuppressWarnings("WeakerAccess") CompletionStage<Element> getContentTypeElement(
String contentTypeCodeName, String elementCodeName, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") ContentLinkUrlResolver getContentLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setContentLinkUrlResolver(ContentLinkUrlResolver contentLinkUrlResolver); @SuppressWarnings("WeakerAccess") BrokenLinkUrlResolver getBrokenLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setBrokenLinkUrlResolver(BrokenLinkUrlResolver brokenLinkUrlResolver); @SuppressWarnings("WeakerAccess") RichTextElementResolver getRichTextElementResolver(); @SuppressWarnings("WeakerAccess") void setRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void addRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void registerType(String contentType, Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerType(Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerInlineContentItemsResolver(InlineContentItemsResolver resolver); @SuppressWarnings("WeakerAccess") void scanClasspathForMappings(String basePackage); @SuppressWarnings("WeakerAccess") void setCacheManager(AsyncCacheManager cacheManager); void setCacheManager(final CacheManager cacheManager); } | @Test @SuppressWarnings("all") public void testGetTaxonomyGroup() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "taxonomies/personas"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleTaxonomyGroup.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); String testServerUri = httpHost.toURI(); client.getDeliveryOptions().setProductionEndpoint(testServerUri); TaxonomyGroup taxonomyGroup = client.getTaxonomyGroup("personas") .toCompletableFuture() .get(); Assert.assertNotNull(taxonomyGroup); } |
DeliveryClient { public CompletionStage<ContentTypesListingResponse> getTypes() { return getTypes(Collections.emptyList()); } @SuppressWarnings("WeakerAccess") DeliveryClient(DeliveryOptions deliveryOptions); @SuppressWarnings({"ResultOfMethodCallIgnored", "WeakerAccess"}) DeliveryClient(DeliveryOptions deliveryOptions, TemplateEngineConfig templateEngineConfig); @SuppressWarnings("unused") DeliveryClient(String projectId); @SuppressWarnings("unused") DeliveryClient(String projectId, String previewApiKey); CompletionStage<ContentItemsListingResponse> getItems(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemsListingResponse> getItems(List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<List<T>> getItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<ContentItemResponse> getItem(String contentItemCodename); @SuppressWarnings("unused") CompletionStage<List<T>> getItems(Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getPageOfItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getNextPage(Page<T> currentPage); @SuppressWarnings("unused") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemResponse> getItem(String contentItemCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass, List<NameValuePair> params); CompletionStage<ContentTypesListingResponse> getTypes(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentTypesListingResponse> getTypes(List<NameValuePair> params); CompletionStage<ContentType> getType(String contentTypeCodeName); @SuppressWarnings("unused") CompletionStage<Element> getContentTypeElement(String contentTypeCodeName, String elementCodeName); @SuppressWarnings("WeakerAccess") CompletionStage<Element> getContentTypeElement(
String contentTypeCodeName, String elementCodeName, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") ContentLinkUrlResolver getContentLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setContentLinkUrlResolver(ContentLinkUrlResolver contentLinkUrlResolver); @SuppressWarnings("WeakerAccess") BrokenLinkUrlResolver getBrokenLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setBrokenLinkUrlResolver(BrokenLinkUrlResolver brokenLinkUrlResolver); @SuppressWarnings("WeakerAccess") RichTextElementResolver getRichTextElementResolver(); @SuppressWarnings("WeakerAccess") void setRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void addRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void registerType(String contentType, Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerType(Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerInlineContentItemsResolver(InlineContentItemsResolver resolver); @SuppressWarnings("WeakerAccess") void scanClasspathForMappings(String basePackage); @SuppressWarnings("WeakerAccess") void setCacheManager(AsyncCacheManager cacheManager); void setCacheManager(final CacheManager cacheManager); } | @Test public void testGetTypes() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "types"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentTypeList.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); String testServerUri = httpHost.toURI(); client.getDeliveryOptions().setProductionEndpoint(testServerUri); ContentTypesListingResponse types = client.getTypes() .toCompletableFuture() .get(); Assert.assertNotNull(types); } |
DeliveryClient { public CompletionStage<ContentType> getType(String contentTypeCodeName) { final String apiCall = String.format(URL_CONCAT, TYPES, contentTypeCodeName); return executeRequest(apiCall, Collections.emptyList(), ContentType.class); } @SuppressWarnings("WeakerAccess") DeliveryClient(DeliveryOptions deliveryOptions); @SuppressWarnings({"ResultOfMethodCallIgnored", "WeakerAccess"}) DeliveryClient(DeliveryOptions deliveryOptions, TemplateEngineConfig templateEngineConfig); @SuppressWarnings("unused") DeliveryClient(String projectId); @SuppressWarnings("unused") DeliveryClient(String projectId, String previewApiKey); CompletionStage<ContentItemsListingResponse> getItems(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemsListingResponse> getItems(List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<List<T>> getItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<ContentItemResponse> getItem(String contentItemCodename); @SuppressWarnings("unused") CompletionStage<List<T>> getItems(Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getPageOfItems(Class<T> tClass, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<Page<T>> getNextPage(Page<T> currentPage); @SuppressWarnings("unused") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass); @SuppressWarnings("WeakerAccess") CompletionStage<ContentItemResponse> getItem(String contentItemCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") CompletionStage<T> getItem(String contentItemCodename, Class<T> tClass, List<NameValuePair> params); CompletionStage<ContentTypesListingResponse> getTypes(); @SuppressWarnings("WeakerAccess") CompletionStage<ContentTypesListingResponse> getTypes(List<NameValuePair> params); CompletionStage<ContentType> getType(String contentTypeCodeName); @SuppressWarnings("unused") CompletionStage<Element> getContentTypeElement(String contentTypeCodeName, String elementCodeName); @SuppressWarnings("WeakerAccess") CompletionStage<Element> getContentTypeElement(
String contentTypeCodeName, String elementCodeName, List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroupListingResponse> getTaxonomyGroups(List<NameValuePair> params); @SuppressWarnings("unused") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename); @SuppressWarnings("WeakerAccess") CompletionStage<TaxonomyGroup> getTaxonomyGroup(String taxonomyGroupCodename, List<NameValuePair> params); @SuppressWarnings("WeakerAccess") ContentLinkUrlResolver getContentLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setContentLinkUrlResolver(ContentLinkUrlResolver contentLinkUrlResolver); @SuppressWarnings("WeakerAccess") BrokenLinkUrlResolver getBrokenLinkUrlResolver(); @SuppressWarnings("WeakerAccess") void setBrokenLinkUrlResolver(BrokenLinkUrlResolver brokenLinkUrlResolver); @SuppressWarnings("WeakerAccess") RichTextElementResolver getRichTextElementResolver(); @SuppressWarnings("WeakerAccess") void setRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void addRichTextElementResolver(RichTextElementResolver richTextElementResolver); @SuppressWarnings("WeakerAccess") void registerType(String contentType, Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerType(Class<?> clazz); @SuppressWarnings("WeakerAccess") void registerInlineContentItemsResolver(InlineContentItemsResolver resolver); @SuppressWarnings("WeakerAccess") void scanClasspathForMappings(String basePackage); @SuppressWarnings("WeakerAccess") void setCacheManager(AsyncCacheManager cacheManager); void setCacheManager(final CacheManager cacheManager); } | @Test @SuppressWarnings("all") public void testGetType() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "types/coffee"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentType.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); String testServerUri = httpHost.toURI(); client.getDeliveryOptions().setProductionEndpoint(testServerUri); ContentType type = client.getType("coffee") .toCompletableFuture() .get(); Assert.assertNotNull(type); } |
ThymeleafTemplateEngine implements TemplateEngine { protected boolean supports(TemplateEngineModel data) { if (!configured) { return false; } String contentType = getContentTypeFromModel(data.getInlineContentItem()); if (contentType == null) { return false; } Set<ITemplateResolver> templateResolvers = templateEngine.getTemplateResolvers(); for (ITemplateResolver resolver : templateResolvers) { if (resolver instanceof AbstractTemplateResolver) { TemplateResolution templateResolution = resolver.resolveTemplate(templateEngine.getConfiguration(), null, contentType, null); if (templateResolution != null && templateResolution.getTemplateResource().exists()) { return true; } } } return false; } @Override void setViewResolverConfiguration(ViewResolverConfiguration viewResolverConfiguration); @Override String process(TemplateEngineModel data); } | @Test public void testIllegalStateException() throws RenderingEngineMissingException { ThymeleafInlineContentItemsResolver resolver = new ThymeleafInlineContentItemsResolver(); ArticleItem articleItem = new ArticleItem(); articleItem.setTitle("Test"); TemplateEngineModel templateEngineModel = new TemplateEngineModel(); templateEngineModel.setInlineContentItem(articleItem); Assert.assertFalse(resolver.supports(templateEngineModel)); try { resolver.resolve(templateEngineModel); Assert.fail("Expected IllegalStateException"); } catch (IllegalStateException e) { Assert.assertEquals("Engine not configured. Did you call setViewResolverConfiguration()?", e.getMessage()); } } |
RegisterImageBackedByEbsOptions extends RegisterImageOptions { @Override public RegisterImageBackedByEbsOptions withDescription(String info) { return (RegisterImageBackedByEbsOptions) super.withDescription(info); } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName,
int volumeSize,
boolean deleteOnTermination,
@Nullable String volumeType,
@Nullable Integer iops,
boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); } | @Test public void testWithDescription() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.withDescription("test"); assertEquals(options.buildFormParameters().get("Description"), ImmutableList.of("test")); }
@Test public void testWithDescriptionStatic() { RegisterImageBackedByEbsOptions options = withDescription("test"); assertEquals(options.buildFormParameters().get("Description"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithDescriptionNPE() { withDescription(null); } |
RegisterImageBackedByEbsOptions extends RegisterImageOptions { @Override public RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture) { return (RegisterImageBackedByEbsOptions) super.asArchitecture(architecture); } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName,
int volumeSize,
boolean deleteOnTermination,
@Nullable String volumeType,
@Nullable Integer iops,
boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); } | @Test public void testWithArchitecture() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.asArchitecture(Architecture.I386); assertEquals(options.buildFormParameters().get("Architecture"), ImmutableList.of("i386")); }
@Test public void testWithArchitectureStatic() { RegisterImageBackedByEbsOptions options = asArchitecture(Architecture.I386); assertEquals(options.buildFormParameters().get("Architecture"), ImmutableList.of("i386")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithArchitectureNPE() { asArchitecture(null); } |
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled) { this.backupsEnabled = backupsEnabled; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); } | @Test public void testBackupsEnabled() { TemplateOptions options = new DigitalOcean2TemplateOptions().backupsEnabled(true); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getBackupsEnabled(), true); } |
RegisterImageBackedByEbsOptions extends RegisterImageOptions { @Override public RegisterImageBackedByEbsOptions withKernelId(String kernelId) { return (RegisterImageBackedByEbsOptions) super.withKernelId(kernelId); } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName,
int volumeSize,
boolean deleteOnTermination,
@Nullable String volumeType,
@Nullable Integer iops,
boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); } | @Test public void testWithKernelId() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); }
@Test public void testWithKernelIdStatic() { RegisterImageBackedByEbsOptions options = withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithKernelIdNPE() { withKernelId(null); } |
RegisterImageBackedByEbsOptions extends RegisterImageOptions { @Override public RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId) { return (RegisterImageBackedByEbsOptions) super.withRamdisk(ramDiskId); } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName,
int volumeSize,
boolean deleteOnTermination,
@Nullable String volumeType,
@Nullable Integer iops,
boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); } | @Test public void testWithRamdisk() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); }
@Test public void testWithRamdiskStatic() { RegisterImageBackedByEbsOptions options = withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithRamdiskNPE() { withRamdisk(null); } |
RegisterImageBackedByEbsOptions extends RegisterImageOptions { public RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted) { addAdvancedEbsOptions(deleteOnTermination, volumeType, iops, encrypted); addEphemeralBlockDeviceFromSnapshot(deviceName, virtualName, snapshotId); return this; } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName,
int volumeSize,
boolean deleteOnTermination,
@Nullable String volumeType,
@Nullable Integer iops,
boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); } | @Test public void testAddBlockDeviceFromSnapshot() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addBlockDeviceFromSnapshot("deviceName", "virtualName", "snapshotId"); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.Ebs.DeleteOnTermination", "false", "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId").entries()); }
@Test public void testAddBlockDeviceFromSnapshotNullVirtualName() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addBlockDeviceFromSnapshot("deviceName", null, "snapshotId"); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.Ebs.DeleteOnTermination", "false", "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId").entries()); }
@Test public void testAddBlockDeviceFromSnapshotStatic() { RegisterImageBackedByEbsOptions options = addBlockDeviceFromSnapshot("deviceName", "virtualName", "snapshotId"); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.Ebs.DeleteOnTermination", "false", "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId").entries()); }
@Test(expectedExceptions = NullPointerException.class) public void testAddBlockDeviceFromSnapshotNPE() { addBlockDeviceFromSnapshot(null, null, null); }
@Test public void testAdvancedAddBlockDeviceFromSnapshot() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addBlockDeviceFromSnapshot("deviceName", "virtualName", "snapshotId", true, "gp2", 0, false); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.builder() .put("BlockDeviceMapping.1.Ebs.DeleteOnTermination", "true") .put("BlockDeviceMapping.1.Ebs.VolumeType", "gp2") .put("BlockDeviceMapping.1.Ebs.Iops", "0") .put("BlockDeviceMapping.1.DeviceName", "deviceName") .put("BlockDeviceMapping.1.VirtualName", "virtualName") .put("BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId") .build() .entries()); }
@Test public void testAdvancedAddBlockDeviceFromSnapshotStatic() { RegisterImageBackedByEbsOptions options = addBlockDeviceFromSnapshot("deviceName", "virtualName", "snapshotId", true, "gp2", 0, true); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.builder() .put("BlockDeviceMapping.1.Ebs.DeleteOnTermination", "true") .put("BlockDeviceMapping.1.Ebs.VolumeType", "gp2") .put("BlockDeviceMapping.1.Ebs.Iops", "0") .put("BlockDeviceMapping.1.Ebs.Encrypted", "true") .put("BlockDeviceMapping.1.DeviceName", "deviceName") .put("BlockDeviceMapping.1.VirtualName", "virtualName") .put("BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId") .build() .entries()); }
@Test(expectedExceptions = NullPointerException.class) public void testAdvancedAddBlockDeviceFromSnapshotNPE() { addBlockDeviceFromSnapshot(null, null, null, false, null, null, false); } |
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair) { this.autoCreateKeyPair = autoCreateKeyPair; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); } | @Test public void testAutoCreateKeyPair() { TemplateOptions options = new DigitalOcean2TemplateOptions().autoCreateKeyPair(false); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getAutoCreateKeyPair(), false); } |
RegisterImageBackedByEbsOptions extends RegisterImageOptions { public RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId) { formParameters.put("BlockDeviceMapping." + deviceIndex + ".DeviceName", checkNotNull( deviceName, "deviceName")); if (virtualName != null) formParameters.put("BlockDeviceMapping." + deviceIndex + ".VirtualName", checkNotNull( virtualName, "virtualName")); formParameters.put("BlockDeviceMapping." + deviceIndex + ".Ebs.SnapshotId", checkNotNull( snapshotId, "snapshotId")); deviceIndex++; return this; } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName,
int volumeSize,
boolean deleteOnTermination,
@Nullable String volumeType,
@Nullable Integer iops,
boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); } | @Test public void testAddEphemeralBlockDeviceFromSnapshot() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addEphemeralBlockDeviceFromSnapshot("deviceName", "virtualName", "snapshotId"); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId").entries()); }
@Test public void testAddEphemeralBlockDeviceFromSnapshotNullVirtualName() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addEphemeralBlockDeviceFromSnapshot("deviceName", null, "snapshotId"); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId").entries()); }
@Test public void testAddEphemeralBlockDeviceFromSnapshotStatic() { RegisterImageBackedByEbsOptions options = addEphemeralBlockDeviceFromSnapshot("deviceName", "virtualName", "snapshotId"); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId").entries()); }
@Test(expectedExceptions = NullPointerException.class) public void testAddEphemeralBlockDeviceFromSnapshotNPE() { addEphemeralBlockDeviceFromSnapshot(null, null, null); } |
RegisterImageBackedByEbsOptions extends RegisterImageOptions { public RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted) { addAdvancedEbsOptions(deleteOnTermination, volumeType, iops, encrypted); addNewEphemeralBlockDevice(deviceName, virtualName, volumeSize); return this; } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName,
int volumeSize,
boolean deleteOnTermination,
@Nullable String volumeType,
@Nullable Integer iops,
boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); } | @Test public void testAddNewBlockDevice() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addNewBlockDevice("deviceName", "virtualName", 1); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.Ebs.DeleteOnTermination", "false", "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.VolumeSize", "1").entries()); }
@Test public void testAddNewBlockDeviceNullVirtualName() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addNewBlockDevice("deviceName", null, 1); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.Ebs.DeleteOnTermination", "false", "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.Ebs.VolumeSize", "1").entries()); }
@Test public void testAddNewBlockDeviceStatic() { RegisterImageBackedByEbsOptions options = addNewBlockDevice("deviceName", "virtualName", 1); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.Ebs.DeleteOnTermination", "false", "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.VolumeSize", "1").entries()); }
@Test(expectedExceptions = NullPointerException.class) public void testAddNewBlockDeviceNPE() { addNewBlockDevice(null, null, 1); }
@Test public void testAdvancedAddNewBlockDevice() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addNewBlockDevice("deviceName", "virtualName", 5, true, "gp2", 0, true); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.builder() .put("BlockDeviceMapping.1.Ebs.DeleteOnTermination", "true") .put("BlockDeviceMapping.1.Ebs.VolumeType", "gp2") .put("BlockDeviceMapping.1.Ebs.Iops", "0") .put("BlockDeviceMapping.1.Ebs.Encrypted", "true") .put("BlockDeviceMapping.1.DeviceName", "deviceName") .put("BlockDeviceMapping.1.VirtualName", "virtualName") .put("BlockDeviceMapping.1.Ebs.VolumeSize", "5") .build() .entries()); }
@Test public void testAdvancedAddNewBlockDeviceStatic() { RegisterImageBackedByEbsOptions options = addNewBlockDevice("deviceName", "virtualName", 5, true, "gp2", 0, false); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.builder() .put("BlockDeviceMapping.1.Ebs.DeleteOnTermination", "true") .put("BlockDeviceMapping.1.Ebs.VolumeType", "gp2") .put("BlockDeviceMapping.1.Ebs.Iops", "0") .put("BlockDeviceMapping.1.DeviceName", "deviceName") .put("BlockDeviceMapping.1.VirtualName", "virtualName") .put("BlockDeviceMapping.1.Ebs.VolumeSize", "5") .build() .entries()); }
@Test(expectedExceptions = NullPointerException.class) public void testAdvancedAddNewBlockDeviceNPE() { addNewBlockDevice(null, null, 5, false, null, null, false); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testAddNewBlockDeviceTooBig() { addNewBlockDevice("deviceName", "virtualName", 1025); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testAddNewBlockDeviceTooSmall() { addNewBlockDevice("deviceName", "virtualName", 0); } |
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions userData(byte[] userData) { this.userData = userData; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); } | @Test public void testUserData() { byte[] userData = "Lorem ipsum".getBytes(); TemplateOptions options = new DigitalOcean2TemplateOptions().userData(userData); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getUserData(), userData); } |
RegisterImageBackedByEbsOptions extends RegisterImageOptions { public RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize) { checkArgument(volumeSize > 0 && volumeSize < 1025, "volumeSize must be between 1 and 1024 gb"); formParameters.put("BlockDeviceMapping." + deviceIndex + ".DeviceName", checkNotNull( deviceName, "deviceName")); if (virtualName != null) formParameters.put("BlockDeviceMapping." + deviceIndex + ".VirtualName", checkNotNull( virtualName, "virtualName")); formParameters.put("BlockDeviceMapping." + deviceIndex + ".Ebs.VolumeSize", volumeSize + ""); deviceIndex++; return this; } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName,
int volumeSize,
boolean deleteOnTermination,
@Nullable String volumeType,
@Nullable Integer iops,
boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,
@Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,
@Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); } | @Test public void testAddNewEphemeralBlockDevice() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addNewEphemeralBlockDevice("deviceName", "virtualName", 1); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.VolumeSize", "1").entries()); }
@Test public void testAddNewEphemeralBlockDeviceNullVirtualName() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addNewEphemeralBlockDevice("deviceName", null, 1); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.Ebs.VolumeSize", "1").entries()); }
@Test public void testAddNewEphemeralBlockDeviceStatic() { RegisterImageBackedByEbsOptions options = addNewEphemeralBlockDevice("deviceName", "virtualName", 1); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.VolumeSize", "1").entries()); }
@Test(expectedExceptions = NullPointerException.class) public void testAddNewEphemeralBlockDeviceNPE() { addNewEphemeralBlockDevice(null, null, 1); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testAddNewEphemeralBlockDeviceTooBig() { addNewEphemeralBlockDevice("deviceName", "virtualName", 1025); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testAddNewEphemeralBlockDeviceTooSmall() { addNewEphemeralBlockDevice("deviceName", "virtualName", 0); } |
DropletStatusToStatus implements Function<Droplet.Status, Status> { @Override public Status apply(final Droplet.Status input) { return toPortableStatus.apply(input); } @Override Status apply(final Droplet.Status input); } | @Test public void testAllStatesHaveMapping() { DropletStatusToStatus function = new DropletStatusToStatus(); for (Status status : Status.values()) { assertNotEquals(function.apply(status), UNRECOGNIZED); } } |
SizeToHardware implements Function<Size, Hardware> { @Override public Hardware apply(Size input) { HardwareBuilder builder = new HardwareBuilder(); builder.id(input.slug()); builder.providerId(input.slug()); builder.name(input.slug()); builder.ram(input.memory()); builder.processor(new Processor(input.vcpus(), input.vcpus())); builder.volume(new VolumeBuilder() .size(Float.valueOf(input.disk())) .type(Type.LOCAL) .build()); ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("costPerHour", String.valueOf(input.priceHourly())); metadata.put("costPerMonth", String.valueOf(input.priceMonthly())); builder.userMetadata(metadata.build()); return builder.build(); } @Override Hardware apply(Size input); } | @Test public void testConvertSize() { Size size = Size.create("2gb", true, 1.0f, 10f, 0.05f, 2048, 1, 20, ImmutableList.<String> of()); Hardware expected = new HardwareBuilder().id("2gb").providerId("2gb").name("2gb") .processor(new Processor(1.0, 1.0)).ram(2048) .volume(new VolumeBuilder().size(20f).type(Type.LOCAL).build()) .userMetadata(ImmutableMap.of("costPerHour", "0.05", "costPerMonth", "10")).build(); SizeToHardware function = new SizeToHardware(); assertEquals(function.apply(size), expected); } |
DropletToNodeMetadata implements Function<Droplet, NodeMetadata> { @Override public NodeMetadata apply(Droplet input) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(String.valueOf(input.id())); builder.name(input.name()); builder.hostname(input.name()); builder.group(groupNamingConvention.extractGroup(input.name())); builder.hardware(getHardware(input.sizeSlug())); builder.location(getLocation(input.region())); Optional<? extends Image> image = findImage(input.image(), input.region().slug()); if (image.isPresent()) { builder.imageId(image.get().getId()); builder.operatingSystem(image.get().getOperatingSystem()); } else { logger.info(">> image with id %s for droplet %s was not found. " + "This might be because the image that was used to create the droplet has a new id.", input.image().id(), input.id()); } builder.status(toPortableStatus.apply(input.status())); builder.backendStatus(input.status().name()); if (!input.getPublicAddresses().isEmpty()) { builder.publicAddresses(FluentIterable .from(input.getPublicAddresses()) .transform(new Function<Networks.Address, String>() { @Override public String apply(final Networks.Address input) { return input.ip(); } }) ); } if (!input.getPrivateAddresses().isEmpty()) { builder.privateAddresses(FluentIterable .from(input.getPrivateAddresses()) .transform(new Function<Networks.Address, String>() { @Override public String apply(final Networks.Address input) { return input.ip(); } }) ); } Credentials credentials = credentialStore.get("node#" + input.id()); if (credentials instanceof LoginCredentials) { builder.credentials(LoginCredentials.class.cast(credentials)); } return builder.build(); } @Inject DropletToNodeMetadata(Supplier<Map<String, ? extends Image>> images,
Supplier<Map<String, ? extends Hardware>> hardwares, @Memoized Supplier<Set<? extends Location>> locations,
Function<Droplet.Status, Status> toPortableStatus, GroupNamingConvention.Factory groupNamingConvention,
Map<String, Credentials> credentialStore); @Override NodeMetadata apply(Droplet input); } | @Test public void testConvertDroplet() throws ParseException { Droplet droplet = Droplet.create( 1, "mock-droplet", 1, 1, 1, false, new Date(), Droplet.Status.ACTIVE, ImmutableList.<Integer> of(), ImmutableList.<Integer> of(), ImmutableList.<String> of(), region, image, null, "2gb", Networks.create( ImmutableList.of(Address.create("84.45.69.3", "255.255.255.0", "84.45.69.1", "public"), Address.create("192.168.2.5", "255.255.255.0", "192.168.2.1", "private")), ImmutableList.<Networks.Address> of()), null); NodeMetadata expected = new NodeMetadataBuilder().ids("1").hardware(getOnlyElement(hardwares)) .imageId("sfo1/ubuntu-1404-x86").status(RUNNING).location(getOnlyElement(locations)).name("mock-droplet") .hostname("mock-droplet").group("mock").credentials(credentials) .publicAddresses(ImmutableSet.of("84.45.69.3")).privateAddresses(ImmutableSet.of("192.168.2.5")) .providerId("1").backendStatus(ACTIVE.name()).operatingSystem(getOnlyElement(images).getOperatingSystem()) .build(); NodeMetadata actual = function.apply(droplet); assertNodeEquals(actual, expected); }
@Test public void testConvertDropletOldImage() throws ParseException { org.jclouds.digitalocean2.domain.Image image = org.jclouds.digitalocean2.domain.Image.create(2, "14.04 x64", "distribution", "Ubuntu", "ubuntu2-1404-x86", true, ImmutableList.of("sfo1"), new Date(), 20, 20); Droplet droplet = Droplet.create( 1, "mock-droplet", 1, 1, 1, false, new Date(), Droplet.Status.ACTIVE, ImmutableList.<Integer> of(), ImmutableList.<Integer> of(), ImmutableList.<String> of(), region, image, null, "2gb", Networks.create( ImmutableList.of(Address.create("84.45.69.3", "255.255.255.0", "84.45.69.1", "public"), Address.create("192.168.2.5", "255.255.255.0", "192.168.2.1", "private")), ImmutableList.<Networks.Address> of()), null); NodeMetadata expected = new NodeMetadataBuilder().ids("1").hardware(getOnlyElement(hardwares)).imageId(null) .status(RUNNING).location(getOnlyElement(locations)).name("mock-droplet").hostname("mock-droplet") .group("mock").credentials(credentials).publicAddresses(ImmutableSet.of("84.45.69.3")) .privateAddresses(ImmutableSet.of("192.168.2.5")).providerId("1").backendStatus(ACTIVE.name()) .operatingSystem(null).build(); NodeMetadata actual = function.apply(droplet); assertNodeEquals(actual, expected); } |
RegionToLocation implements Function<Region, Location> { @Override public Location apply(Region input) { LocationBuilder builder = new LocationBuilder(); builder.id(input.slug()); builder.description(input.name()); builder.scope(LocationScope.REGION); builder.parent(getOnlyElement(justProvider.get())); builder.iso3166Codes(ImmutableSet.<String> of()); builder.metadata(ImmutableMap.<String, Object> of("available", input.available(), "features", input.features())); return builder.build(); } @Inject RegionToLocation(JustProvider justProvider); @Override Location apply(Region input); } | @Test public void testConvertRegion() { DigitalOcean2ProviderMetadata metadata = new DigitalOcean2ProviderMetadata(); JustProvider locationsSupplier = new JustProvider(metadata.getId(), Suppliers.<URI> ofInstance(URI .create(metadata.getEndpoint())), ImmutableSet.<String> of()); Region region = Region.create("reg1", "Region1", ImmutableList.<String> of(), true, ImmutableList.<String> of("virtio", "metadata")); Location expected = new LocationBuilder().id("reg1").description("reg1/Region 1") .parent(getOnlyElement(locationsSupplier.get())).scope(LocationScope.REGION).build(); Location location = new RegionToLocation(locationsSupplier).apply(region); assertEquals(location, expected); assertEquals(location.getMetadata().get("available"), true); assertEquals(location.getMetadata().get("features"), ImmutableList.of("virtio", "metadata")); } |
ECDSAKeys { public static String fingerprintPublicKey(String publicKeyOpenSSH) throws IOException { ECPublicKeySpec publicKeySpec = publicKeySpecFromOpenSSH(publicKeyOpenSSH); String fingerprint = null; try { ECPublicKey pk = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(publicKeySpec); fingerprint = fingerprint(pk); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return fingerprint; } static String encodeAsOpenSSH(ECPublicKey key); static ECPublicKeySpec publicKeySpecFromOpenSSH(String ecDsaPub); static ECPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(ECPublicKey publicKey); static byte[] encodeECPoint(ECPoint group, EllipticCurve curve); static ECPoint decodeECPoint(byte[] M, EllipticCurve curve); static final String ECDSA_SHA2_PREFIX; } | @Test public void testCanReadRsaAndCompareFingerprintOnPublicECDSAKey() throws IOException { String ecdsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-ecdsa.pub")); String fingerPrint = ECDSAKeys.fingerprintPublicKey(ecdsa); assertEquals(fingerPrint, expectedFingerPrint); } |
BindS3UploadPolicyAndSignature implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { String encodedJson = base64().encode(checkNotNull(input, "json").toString().getBytes(UTF_8)); Builder<String, String> builder = ImmutableMultimap.builder(); builder.put("Storage.S3.UploadPolicy", encodedJson); String signature = signer.sign(encodedJson); builder.put("Storage.S3.UploadPolicySignature", signature); return (R) request.toBuilder().replaceFormParams(builder.build()).build(); } @Inject BindS3UploadPolicyAndSignature(FormSignerV2 signer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | @Test(expectedExceptions = NullPointerException.class) public void testNullIsBad() { HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); } |
ECDSAKeys { public static String encodeAsOpenSSH(ECPublicKey key) { String curveName = null; try { curveName = getCurveName(key.getParams()); } catch (IOException e) { propagate(e); } String keyFormat = ECDSA_SHA2_PREFIX + curveName; byte[] keyBlob = keyBlob(key); return keyFormat + " " + base64().encode(keyBlob); } static String encodeAsOpenSSH(ECPublicKey key); static ECPublicKeySpec publicKeySpecFromOpenSSH(String ecDsaPub); static ECPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(ECPublicKey publicKey); static byte[] encodeECPoint(ECPoint group, EllipticCurve curve); static ECPoint decodeECPoint(byte[] M, EllipticCurve curve); static final String ECDSA_SHA2_PREFIX; } | @Test public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { String ecdsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-ecdsa.pub")); ECPublicKeySpec spec = ECDSAKeys.publicKeySpecFromOpenSSH(ecdsa); ECPublicKey key = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(spec); assertTrue(ecdsa.startsWith(ECDSAKeys.encodeAsOpenSSH(key))); } |
VolumeDetached implements Predicate<Attachment> { public boolean apply(Attachment attachment) { logger.trace("looking for volume %s", attachment.getVolumeId()); Volume volume = Iterables.getOnlyElement(client.describeVolumesInRegion(attachment .getRegion(), attachment.getVolumeId())); if (volume.getAttachments().isEmpty()) { return true; } Attachment lastAttachment = getLast(volume.getAttachments()); logger.trace("%s: looking for status %s: currently: %s", lastAttachment, Attachment.Status.DETACHED, lastAttachment.getStatus()); return lastAttachment.getStatus() == Attachment.Status.DETACHED; } @Inject VolumeDetached(ElasticBlockStoreApi client); boolean apply(Attachment attachment); } | @Test public void testVolumeWithEmptyListOfAttachments() { Attachment attachment = newAttachmentWithStatus(Status.ATTACHED); Set<Volume> volumes = newHashSet(newVolumeWithAttachments()); expect(client.describeVolumesInRegion(attachment.getRegion(), attachment.getVolumeId())).andReturn(volumes); replay(client); assertTrue(volumeDetached.apply(attachment)); verify(client); }
@Test(dataProvider = "notDetachedStatuses") public void testWithDifferentStatus(Status attachmentStatus) { Attachment attachment = newAttachmentWithStatus(attachmentStatus); Set<Volume> volumes = newHashSet(newVolumeWithAttachments(attachment)); expect(client.describeVolumesInRegion(attachment.getRegion(), attachment.getVolumeId())).andReturn(volumes); replay(client); assertFalse(volumeDetached.apply(attachment)); verify(client); }
@Test public void testWithStatusDetached() { Attachment attachment = newAttachmentWithStatus(Status.DETACHED); Set<Volume> volumes = newHashSet(newVolumeWithAttachments(attachment)); expect(client.describeVolumesInRegion(attachment.getRegion(), attachment.getVolumeId())).andReturn(volumes); replay(client); assertTrue(volumeDetached.apply(attachment)); verify(client); } |
EC2DestroyNodeStrategy implements DestroyNodeStrategy { @Override public NodeMetadata destroyNode(String id) { String[] parts = AWSUtils.parseHandle(id); String region = parts[0]; String instanceId = parts[1]; releaseAnyPublicIpForInstanceInRegion(instanceId, region); destroyInstanceInRegion(instanceId, region); return getNode.getNode(id); } @Inject protected EC2DestroyNodeStrategy(EC2Api client, GetNodeMetadataStrategy getNode,
@Named("ELASTICIP") LoadingCache<RegionAndName, String> elasticIpCache); @Override NodeMetadata destroyNode(String id); } | @SuppressWarnings("unchecked") @Test public void testDestroyNodeTerminatesInstanceAndReturnsRefreshedNode() throws Exception { EC2Api client = createMock(EC2Api.class); InstanceApi instanceClient = createMock(InstanceApi.class); GetNodeMetadataStrategy getNode = createMock(GetNodeMetadataStrategy.class); LoadingCache<RegionAndName, String> elasticIpCache = createMock(LoadingCache.class); NodeMetadata node = createMock(NodeMetadata.class); expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce(); expect(instanceClient.terminateInstancesInRegion("region", "i-blah")).andReturn(null); expect(getNode.getNode("region/i-blah")).andReturn(node); replay(client); replay(getNode); replay(instanceClient); replay(elasticIpCache); EC2DestroyNodeStrategy destroyer = new EC2DestroyNodeStrategy(client, getNode, elasticIpCache); assertEquals(destroyer.destroyNode("region/i-blah"), node); verify(client); verify(getNode); verify(instanceClient); verify(elasticIpCache); }
@SuppressWarnings("unchecked") @Test public void testDestroyNodeDisassociatesAndReleasesIpThenTerminatesInstanceAndReturnsRefreshedNode() throws Exception { EC2Api client = createMock(EC2Api.class); GetNodeMetadataStrategy getNode = createMock(GetNodeMetadataStrategy.class); LoadingCache<RegionAndName, String> elasticIpCache = createMock(LoadingCache.class); ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class); InstanceApi instanceClient = createMock(InstanceApi.class); NodeMetadata node = createMock(NodeMetadata.class); expect(elasticIpCache.get(new RegionAndName("region", "i-blah"))).andReturn("1.1.1.1"); expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce(); ipClient.disassociateAddressInRegion("region", "1.1.1.1"); ipClient.releaseAddressInRegion("region", "1.1.1.1"); elasticIpCache.invalidate(new RegionAndName("region", "i-blah")); expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce(); expect(instanceClient.terminateInstancesInRegion("region", "i-blah")).andReturn(null); expect(getNode.getNode("region/i-blah")).andReturn(node); replay(client); replay(getNode); replay(elasticIpCache); replay(instanceClient); replay(ipClient); EC2DestroyNodeStrategy destroyer = new EC2DestroyNodeStrategy(client, getNode, elasticIpCache); destroyer.autoAllocateElasticIps = true; assertEquals(destroyer.destroyNode("region/i-blah"), node); verify(client); verify(getNode); verify(elasticIpCache); verify(instanceClient); verify(ipClient); }
@SuppressWarnings("unchecked") @Test public void testDestroyNodeSafeOnCacheMissThenTerminatesInstanceAndReturnsRefreshedNode() throws Exception { EC2Api client = createMock(EC2Api.class); GetNodeMetadataStrategy getNode = createMock(GetNodeMetadataStrategy.class); LoadingCache<RegionAndName, String> elasticIpCache = createMock(LoadingCache.class); ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class); InstanceApi instanceClient = createMock(InstanceApi.class); NodeMetadata node = createMock(NodeMetadata.class); expect(elasticIpCache.get(new RegionAndName("region", "i-blah"))).andThrow(new CacheLoader.InvalidCacheLoadException(null)); expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce(); expect(instanceClient.terminateInstancesInRegion("region", "i-blah")).andReturn(null); expect(getNode.getNode("region/i-blah")).andReturn(node); replay(client); replay(getNode); replay(elasticIpCache); replay(instanceClient); replay(ipClient); EC2DestroyNodeStrategy destroyer = new EC2DestroyNodeStrategy(client, getNode, elasticIpCache); destroyer.autoAllocateElasticIps = true; assertEquals(destroyer.destroyNode("region/i-blah"), node); verify(client); verify(getNode); verify(elasticIpCache); verify(instanceClient); verify(ipClient); }
@SuppressWarnings("unchecked") @Test public void testDestroyNodeSafeOnCacheExecutionExceptionThenTerminatesInstanceAndReturnsRefreshedNode() throws Exception { EC2Api client = createMock(EC2Api.class); GetNodeMetadataStrategy getNode = createMock(GetNodeMetadataStrategy.class); LoadingCache<RegionAndName, String> elasticIpCache = createMock(LoadingCache.class); ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class); InstanceApi instanceClient = createMock(InstanceApi.class); NodeMetadata node = createMock(NodeMetadata.class); expect(elasticIpCache.get(new RegionAndName("region", "i-blah"))).andThrow(new ExecutionException(null)); expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce(); expect(instanceClient.terminateInstancesInRegion("region", "i-blah")).andReturn(null); expect(getNode.getNode("region/i-blah")).andReturn(node); replay(client); replay(getNode); replay(elasticIpCache); replay(instanceClient); replay(ipClient); EC2DestroyNodeStrategy destroyer = new EC2DestroyNodeStrategy(client, getNode, elasticIpCache); destroyer.autoAllocateElasticIps = true; assertEquals(destroyer.destroyNode("region/i-blah"), node); verify(client); verify(getNode); verify(elasticIpCache); verify(instanceClient); verify(ipClient); } |
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions { @VisibleForTesting public String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) { String keyPairName = null; boolean shouldAutomaticallyCreateKeyPair = true; if (options instanceof EC2TemplateOptions) { keyPairName = EC2TemplateOptions.class.cast(options).getKeyPair(); if (keyPairName == null) shouldAutomaticallyCreateKeyPair = EC2TemplateOptions.class.cast(options) .shouldAutomaticallyCreateKeyPair(); } if (keyPairName == null && shouldAutomaticallyCreateKeyPair) { keyPairName = createOrImportKeyPair(region, group, options); } else if (keyPairName != null) { if (options.getLoginPrivateKey() != null) { String pem = options.getLoginPrivateKey(); KeyPair keyPair = KeyPair.builder().region(region).keyName(keyPairName).fingerprint( fingerprintPrivateKey(pem)).sha1OfPrivateKey(sha1PrivateKey(pem)).keyMaterial(pem).build(); RegionAndName key = new RegionAndName(region, keyPairName); credentialsMap.put(key, keyPair); } } if (options.getRunScript() != null) { RegionAndName regionAndName = new RegionAndName(region, keyPairName); checkArgument( credentialsMap.containsKey(regionAndName), "no private key configured for: %s; please use options.overrideLoginCredentialWith(rsa_private_text)", regionAndName); } return keyPairName; } @Inject CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions(Function<RegionAndName, KeyPair> makeKeyPair,
ConcurrentMap<RegionAndName, KeyPair> credentialsMap,
@Named("SECURITY") LoadingCache<RegionAndName, String> securityGroupMap,
Provider<RunInstancesOptions> optionsProvider,
GroupNamingConvention.Factory namingConvention); RunInstancesOptions execute(String region, String group, Template template); @VisibleForTesting String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options); @VisibleForTesting Set<String> getSecurityGroupsForTagAndOptions(String region, @Nullable String group, @Nullable String vpcId, TemplateOptions options); @VisibleForTesting javax.inject.Provider<RunInstancesOptions> getOptionsProvider(); @VisibleForTesting
public Function<RegionAndName, KeyPair> makeKeyPair; @VisibleForTesting
final ConcurrentMap<RegionAndName, KeyPair> credentialsMap; @VisibleForTesting
final LoadingCache<RegionAndName, String> securityGroupMap; @VisibleForTesting
final Provider<RunInstancesOptions> optionsProvider; } | @Test(expectedExceptions = IllegalArgumentException.class) public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptButNoCredentials() { String region = Region.AP_SOUTHEAST_1; String group = "group"; String userSuppliedKeyPair = "myKeyPair"; CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy(); EC2TemplateOptions options = createMock(EC2TemplateOptions.class); KeyPair keyPair = createMock(KeyPair.class); expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); expect(options.getLoginUser()).andReturn(null); expect(options.getLoginPassword()).andReturn(null); expect(options.getLoginPrivateKey()).andReturn(null); expect(options.shouldAuthenticateSudo()).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(false); replay(options); replay(keyPair); replayStrategy(strategy); assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair); verify(options); verify(keyPair); verifyStrategy(strategy); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { public EC2TemplateOptions securityGroups(String... groupNames) { return securityGroups(ImmutableSet.copyOf(groupNames)); } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "all security groups must be non-empty") public void testsecurityGroupsIterableBadFormat() { EC2TemplateOptions options = new EC2TemplateOptions(); options.securityGroups(ImmutableSet.of("group1", "")); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testsecurityGroupsIterableEmptyNotOk() { EC2TemplateOptions options = new EC2TemplateOptions(); options.securityGroups(ImmutableSet.<String> of()); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "all security groups must be non-empty") public void testsecurityGroupsVarArgsBadFormat() { EC2TemplateOptions options = new EC2TemplateOptions(); options.securityGroups("mygroup", ""); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testsecurityGroupsVarArgsEmptyNotOk() { EC2TemplateOptions options = new EC2TemplateOptions(); options.securityGroups(); } |
DSAKeys { public static String fingerprintPublicKey(String publicKeyOpenSSH) { DSAPublicKeySpec publicKeySpec = publicKeySpecFromOpenSSH(publicKeyOpenSSH); return fingerprint(publicKeySpec.getP(), publicKeySpec.getQ(), publicKeySpec.getG(), publicKeySpec.getY()); } static String encodeAsOpenSSH(DSAPublicKey key); static DSAPublicKeySpec publicKeySpecFromOpenSSH(String idDsaPub); static DSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(BigInteger p, BigInteger q, BigInteger g, BigInteger y); } | @Test public void testCanReadRsaAndCompareFingerprintOnPublicRSAKey() throws IOException { String dsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-dsa.pub")); String fingerPrint = DSAKeys.fingerprintPublicKey(dsa); assertEquals(fingerPrint, expectedFingerPrint); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { public Set<String> getGroups() { return groupNames; } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test public void testDefaultGroupsVarArgsEmpty() { EC2TemplateOptions options = new EC2TemplateOptions(); assertEquals(options.getGroups(), ImmutableSet.of()); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { public EC2TemplateOptions keyPair(String keyPair) { checkState(!noKeyPair, "you cannot specify both options keyPair and noKeyPair"); this.keyPair = checkNotNull(emptyToNull(keyPair), "use noKeyPair option to request boot without a keypair"); return this; } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "use noKeyPair option to request boot without a keypair") public void testkeyPairBadFormat() { EC2TemplateOptions options = new EC2TemplateOptions(); options.keyPair(""); }
@Test public void testkeyPair() { EC2TemplateOptions options = new EC2TemplateOptions(); options.keyPair("mykeypair"); assertEquals(options.getKeyPair(), "mykeypair"); }
@Test(expectedExceptions = NullPointerException.class) public void testkeyPairNPE() { keyPair(null); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { public String getKeyPair() { return keyPair; } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test public void testNullkeyPair() { EC2TemplateOptions options = new EC2TemplateOptions(); assertEquals(options.getKeyPair(), null); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { public EC2TemplateOptions noKeyPair() { checkState(keyPair == null, "you cannot specify both options keyPair and noKeyPair"); this.noKeyPair = true; return this; } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test public void testnoKeyPair() { EC2TemplateOptions options = new EC2TemplateOptions(); options.noKeyPair(); assertEquals(options.getKeyPair(), null); assert !options.shouldAutomaticallyCreateKeyPair(); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { @Override public EC2TemplateOptions installPrivateKey(String privateKey) { return EC2TemplateOptions.class.cast(super.installPrivateKey(privateKey)); } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test(expectedExceptions = IllegalArgumentException.class) public void testinstallPrivateKeyBadFormat() { EC2TemplateOptions options = new EC2TemplateOptions(); options.installPrivateKey("whompy"); }
@Test public void testinstallPrivateKey() throws IOException { EC2TemplateOptions options = new EC2TemplateOptions(); options.installPrivateKey("-----BEGIN RSA PRIVATE KEY-----"); assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----"); }
@Test public void testinstallPrivateKeyStatic() throws IOException { EC2TemplateOptions options = installPrivateKey("-----BEGIN RSA PRIVATE KEY-----"); assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----"); }
@Test(expectedExceptions = NullPointerException.class) public void testinstallPrivateKeyNPE() { installPrivateKey(null); } |
DSAKeys { public static String encodeAsOpenSSH(DSAPublicKey key) { DSAParams params = key.getParams(); byte[] keyBlob = keyBlob(params.getP(), params.getQ(), params.getG(), key.getY()); return "ssh-dss " + base64().encode(keyBlob); } static String encodeAsOpenSSH(DSAPublicKey key); static DSAPublicKeySpec publicKeySpecFromOpenSSH(String idDsaPub); static DSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(BigInteger p, BigInteger q, BigInteger g, BigInteger y); } | @Test public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { String dsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-dsa.pub")); DSAPublicKeySpec spec = DSAKeys.publicKeySpecFromOpenSSH(dsa); DSAPublicKey key = (DSAPublicKey) KeyFactory.getInstance("DSA").generatePublic(spec); assertEquals(DSAKeys.encodeAsOpenSSH(key), dsa); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { @Override public EC2TemplateOptions authorizePublicKey(String publicKey) { return EC2TemplateOptions.class.cast(super.authorizePublicKey(publicKey)); } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test(expectedExceptions = IllegalArgumentException.class) public void testauthorizePublicKeyBadFormat() { EC2TemplateOptions options = new EC2TemplateOptions(); options.authorizePublicKey("whompy"); }
@Test public void testauthorizePublicKey() throws IOException { EC2TemplateOptions options = new EC2TemplateOptions(); options.authorizePublicKey("ssh-rsa"); assertEquals(options.getPublicKey(), "ssh-rsa"); }
@Test public void testauthorizePublicKeyStatic() throws IOException { EC2TemplateOptions options = authorizePublicKey("ssh-rsa"); assertEquals(options.getPublicKey(), "ssh-rsa"); }
@Test(expectedExceptions = NullPointerException.class) public void testauthorizePublicKeyNPE() { authorizePublicKey(null); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { @Override public EC2TemplateOptions blockOnPort(int port, int seconds) { return EC2TemplateOptions.class.cast(super.blockOnPort(port, seconds)); } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test(expectedExceptions = IllegalArgumentException.class) public void testblockOnPortBadFormat() { EC2TemplateOptions options = new EC2TemplateOptions(); options.blockOnPort(-1, -1); }
@Test public void testblockOnPort() { EC2TemplateOptions options = new EC2TemplateOptions(); options.blockOnPort(22, 30); assertEquals(options.getPort(), 22); assertEquals(options.getSeconds(), 30); }
@Test public void testblockOnPortStatic() { EC2TemplateOptions options = blockOnPort(22, 30); assertEquals(options.getPort(), 22); assertEquals(options.getSeconds(), 30); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { @Override public EC2TemplateOptions inboundPorts(int... ports) { return EC2TemplateOptions.class.cast(super.inboundPorts(ports)); } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test(expectedExceptions = IllegalArgumentException.class) public void testinboundPortsBadFormat() { EC2TemplateOptions options = new EC2TemplateOptions(); options.inboundPorts(-1, -1); }
@Test public void testinboundPorts() { EC2TemplateOptions options = new EC2TemplateOptions(); options.inboundPorts(22, 30); assertEquals(options.getInboundPorts()[0], 22); assertEquals(options.getInboundPorts()[1], 30); }
@Test public void testinboundPortsStatic() { EC2TemplateOptions options = inboundPorts(22, 30); assertEquals(options.getInboundPorts()[0], 22); assertEquals(options.getInboundPorts()[1], 30); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { public int getMaxCount() { return maxCount != null ? maxCount.intValue() : 0; } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test public void testMaxCountDefault() { EC2TemplateOptions options = new EC2TemplateOptions(); assertEquals(options.getMaxCount(), 0); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { public EC2TemplateOptions maxCount(Integer maxCount) { this.maxCount = maxCount; return this; } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test public void testMaxCount() { EC2TemplateOptions options = new EC2TemplateOptions(); options.maxCount(2); assertEquals(options.getMaxCount(), 2); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { public String getClientToken() { return clientToken; } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test public void testClientTokenDefault() { EC2TemplateOptions options = new EC2TemplateOptions(); assertNull(options.getClientToken()); } |
EC2TemplateOptions extends TemplateOptions implements Cloneable { public EC2TemplateOptions clientToken(String clientToken) { this.clientToken = checkNotNull(clientToken, "clientToken"); return this; } @Override EC2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); EC2TemplateOptions securityGroups(String... groupNames); EC2TemplateOptions securityGroups(Iterable<String> groupNames); EC2TemplateOptions userData(byte[] unencodedData); EC2TemplateOptions keyPair(String keyPair); EC2TemplateOptions noKeyPair(); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,
@Nullable Integer sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination); EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,
@Nullable String volumeType, @Nullable Integer iops,
boolean encrypted); EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName); EC2TemplateOptions unmapDeviceNamed(String deviceName); EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings); EC2TemplateOptions maxCount(Integer maxCount); EC2TemplateOptions clientToken(String clientToken); @Override EC2TemplateOptions blockOnPort(int port, int seconds); @Override EC2TemplateOptions inboundPorts(int... ports); @Override EC2TemplateOptions authorizePublicKey(String publicKey); @Override EC2TemplateOptions installPrivateKey(String privateKey); @Override EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override EC2TemplateOptions dontAuthorizePublicKey(); @Override EC2TemplateOptions nameTask(String name); @Override EC2TemplateOptions runAsRoot(boolean runAsRoot); @Override EC2TemplateOptions runScript(Statement script); @Override EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override EC2TemplateOptions overrideLoginPassword(String password); @Override EC2TemplateOptions overrideLoginPrivateKey(String privateKey); @Override EC2TemplateOptions overrideLoginUser(String loginUser); @Override EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override EC2TemplateOptions userMetadata(Map<String, String> userMetadata); @Override EC2TemplateOptions userMetadata(String key, String value); @Override EC2TemplateOptions nodeNames(Iterable<String> nodeNames); @Override EC2TemplateOptions networks(Iterable<String> networks); @Override EC2TemplateOptions runScript(String script); @Override EC2TemplateOptions tags(Iterable<String> tags); @Override EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override EC2TemplateOptions blockOnComplete(boolean blockOnComplete); Set<String> getGroups(); String getKeyPair(); boolean shouldAutomaticallyCreateKeyPair(); byte[] getUserData(); Set<BlockDeviceMapping> getBlockDeviceMappings(); int getMaxCount(); String getClientToken(); static final EC2TemplateOptions NONE; } | @Test public void testClientToken() { EC2TemplateOptions options = new EC2TemplateOptions(); options.clientToken("some-token"); assertEquals(options.getClientToken(), "some-token"); }
@Test(expectedExceptions = NullPointerException.class) public void testClientTokenNPE() { EC2TemplateOptions options = new EC2TemplateOptions(); options.clientToken(null); } |
EC2ComputeServiceContextModule extends BaseComputeServiceContextModule { protected Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader( final RegionAndIdToImage delegate) { return Suppliers.<CacheLoader<RegionAndName, Image>>ofInstance(new CacheLoader<RegionAndName, Image>() { private final AtomicReference<AuthorizationException> authException = Atomics.newReference(); @Override public Image load(final RegionAndName key) throws Exception { Supplier<Image> rawSupplier = new Supplier<Image>() { @Override public Image get() { try { return delegate.load(key); } catch (ExecutionException e) { throw Throwables.propagate(e); } } }; return new SetAndThrowAuthorizationExceptionSupplier<Image>(rawSupplier, authException).get(); } }); } } | @Test public void testCacheLoaderDoesNotReloadAfterAuthorizationException() throws Exception { EC2ComputeServiceContextModule module = new EC2ComputeServiceContextModule() { public Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(RegionAndIdToImage delegate) { return super.provideRegionAndNameToImageSupplierCacheLoader(delegate); } }; RegionAndName regionAndName = new RegionAndName("myregion", "myname"); AuthorizationException authException = new AuthorizationException(); RegionAndIdToImage mockRegionAndIdToImage = createMock(RegionAndIdToImage.class); expect(mockRegionAndIdToImage.load(regionAndName)).andThrow(authException).once(); replay(mockRegionAndIdToImage); CacheLoader<RegionAndName, Image> cacheLoader = module.provideRegionAndNameToImageSupplierCacheLoader(mockRegionAndIdToImage).get(); for (int i = 0; i < 2; i++) { try { Image image = cacheLoader.load(regionAndName); fail("Expected Authorization exception, but got " + image); } catch (AuthorizationException e) { } } } |
EC2SecurityGroupToSecurityGroup implements Function<org.jclouds.ec2.domain.SecurityGroup, SecurityGroup> { @Override public SecurityGroup apply(org.jclouds.ec2.domain.SecurityGroup group) { SecurityGroupBuilder builder = new SecurityGroupBuilder(); Location location = findLocationWithId(group.getRegion()); builder.location(location); builder.id(group.getRegion() + "/" + idOrName(group)); builder.providerId(group.getId()); builder.name(group.getName()); builder.ipPermissions(group); builder.ownerId(group.getOwnerId()); return builder.build(); } @Inject EC2SecurityGroupToSecurityGroup(@Memoized Supplier<Set<? extends Location>> locations); @Override SecurityGroup apply(org.jclouds.ec2.domain.SecurityGroup group); } | @Test public void testApply() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); org.jclouds.ec2.domain.SecurityGroup origGroup = org.jclouds.ec2.domain.SecurityGroup.builder() .region("us-east-1") .id("some-id") .name("some-group") .ownerId("some-owner") .description("some-description") .ipPermission(authorization) .build(); EC2SecurityGroupToSecurityGroup parser = createGroupParser(ImmutableSet.of(provider)); SecurityGroup group = parser.apply(origGroup); assertEquals(group.getLocation(), provider); assertEquals(group.getId(), provider.getId() + "/" + origGroup.getName()); assertEquals(group.getProviderId(), origGroup.getId()); assertEquals(group.getName(), origGroup.getName()); assertEquals(group.getIpPermissions(), (Set<IpPermission>)origGroup); assertEquals(group.getOwnerId(), origGroup.getOwnerId()); } |
CreateUniqueKeyPair implements Function<RegionAndName, KeyPair> { @Override public KeyPair apply(RegionAndName from) { return createNewKeyPairInRegion(from.getRegion(), from.getName()); } @Inject CreateUniqueKeyPair(EC2Api ec2Api, GroupNamingConvention.Factory namingConvention); @Override KeyPair apply(RegionAndName from); } | @Test public void testApply() throws UnknownHostException { final EC2Api client = createMock(EC2Api.class); KeyPairApi keyClient = createMock(KeyPairApi.class); KeyPair pair = createMock(KeyPair.class); expect(client.getKeyPairApi()).andReturn((Optional) Optional.of(keyClient)).atLeastOnce(); expect(keyClient.createKeyPairInRegion("region", "jclouds#group#1")).andReturn(pair); replay(client); replay(keyClient); CreateUniqueKeyPair parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), new EC2ApiMetadata().getDefaultProperties()); bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(EC2Api.class).toInstance(client); } }).getInstance(CreateUniqueKeyPair.class); assertEquals(parser.createNewKeyPairInRegion("region", "group"), pair); verify(client); verify(keyClient); } |
CreateUniqueKeyPair implements Function<RegionAndName, KeyPair> { @VisibleForTesting KeyPair createNewKeyPairInRegion(String region, String group) { checkNotNull(region, "region"); checkNotNull(group, "group"); logger.debug(">> creating keyPair region(%s) group(%s)", region, group); KeyPair keyPair = null; String prefix = group; while (keyPair == null) { String keyName = namingConvention.create().uniqueNameForGroup(prefix); try { keyPair = ec2Api.getKeyPairApi().get().createKeyPairInRegion(region, keyName); } catch (IllegalStateException e) { logger.trace(" invalid keyname (%s in %s); retrying", keyName, region); } } logger.debug("<< created keyPair(%s)", keyPair); return keyPair; } @Inject CreateUniqueKeyPair(EC2Api ec2Api, GroupNamingConvention.Factory namingConvention); @Override KeyPair apply(RegionAndName from); } | @SuppressWarnings( { "unchecked" }) @Test public void testApplyWithIllegalStateException() throws UnknownHostException { final EC2Api client = createMock(EC2Api.class); KeyPairApi keyClient = createMock(KeyPairApi.class); final Supplier<String> uniqueIdSupplier = createMock(Supplier.class); KeyPair pair = createMock(KeyPair.class); expect(client.getKeyPairApi()).andReturn((Optional) Optional.of(keyClient)).atLeastOnce(); expect(uniqueIdSupplier.get()).andReturn("1"); expect(keyClient.createKeyPairInRegion("region", "jclouds#group#1")).andThrow(new IllegalStateException()); expect(uniqueIdSupplier.get()).andReturn("2"); expect(keyClient.createKeyPairInRegion("region", "jclouds#group#2")).andReturn(pair); replay(client); replay(keyClient); replay(uniqueIdSupplier); CreateUniqueKeyPair parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), new EC2ApiMetadata().getDefaultProperties()); bind(new TypeLiteral<Supplier<String>>() { }).toInstance(uniqueIdSupplier); bind(EC2Api.class).toInstance(client); } }).getInstance(CreateUniqueKeyPair.class); assertEquals(parser.createNewKeyPairInRegion("region", "group"), pair); verify(client); verify(keyClient); verify(uniqueIdSupplier); } |
PresentInstances implements Function<Set<RegionAndName>, Set<RunningInstance>> { @Override public Set<RunningInstance> apply(Set<RegionAndName> regionAndIds) { if (checkNotNull(regionAndIds, "regionAndIds").isEmpty()) return ImmutableSet.of(); Builder<RunningInstance> builder = ImmutableSet.<RunningInstance> builder(); Multimap<String, String> regionToInstanceIds = transformValues(index(regionAndIds, regionFunction()), nameFunction()); for (Map.Entry<String, Collection<String>> entry : regionToInstanceIds.asMap().entrySet()) { String region = entry.getKey(); Collection<String> instanceIds = entry.getValue(); logger.trace("looking for instances %s in region %s", instanceIds, region); builder.addAll(concat(client.getInstanceApi().get().describeInstancesInRegion(region, toArray(instanceIds, String.class)))); } return builder.build(); } @Inject PresentInstances(EC2Api client); @Override Set<RunningInstance> apply(Set<RegionAndName> regionAndIds); @Override String toString(); } | @SuppressWarnings("unchecked") @Test public void testWhenInstancesPresentSingleCall() { EC2Api client = createMock(EC2Api.class); InstanceApi instanceClient = createMock(InstanceApi.class); expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)); expect(instanceClient.describeInstancesInRegion("us-east-1", "i-aaaa", "i-bbbb")).andReturn( Set.class.cast(ImmutableSet.of(Reservation.builder().region("us-east-1") .instances(ImmutableSet.of(instance1, instance2)).build()))); replay(client, instanceClient); PresentInstances fn = new PresentInstances(client); assertEquals(fn.apply(ImmutableSet.of(new RegionAndName("us-east-1", "i-aaaa"), new RegionAndName("us-east-1", "i-bbbb"))), ImmutableSet.of(instance1, instance2)); verify(client, instanceClient); } |
WindowsLoginCredentialsFromEncryptedData implements Function<PasswordDataAndPrivateKey, LoginCredentials> { @Override public LoginCredentials apply(@Nullable PasswordDataAndPrivateKey dataAndKey) { if (dataAndKey == null) return null; try { KeySpec keySpec = Pems.privateKeySpec(dataAndKey.getPrivateKey()); KeyFactory kf = crypto.rsaKeyFactory(); PrivateKey privKey = kf.generatePrivate(keySpec); Cipher cipher = crypto.cipher("RSA"); cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] cipherText = base64().decode(dataAndKey.getPasswordData().getPasswordData()); byte[] plainText = cipher.doFinal(cipherText); String password = new String(plainText, Charsets.US_ASCII); return LoginCredentials.builder() .user("Administrator") .password(password) .noPrivateKey() .build(); } catch (Exception e) { throw Throwables.propagate(e); } } @Inject WindowsLoginCredentialsFromEncryptedData(Crypto crypto); @Override LoginCredentials apply(@Nullable PasswordDataAndPrivateKey dataAndKey); } | @Test public void testApply() throws Exception { WindowsLoginCredentialsFromEncryptedData f = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto()); PasswordData passwordData = PasswordData.builder() .instanceId("i-2574e22a") .timestamp(dateService.iso8601DateParse("2012-07-30T07:27:23.000+0000")) .passwordData(ENCRYPTED_PASSWORD).build(); LoginCredentials credentials = f.apply(new PasswordDataAndPrivateKey(passwordData, PRIVATE_KEY)); assertEquals(credentials.getUser(), "Administrator"); assertEquals(credentials.getOptionalPassword().get(), "u4.y9mb;nR."); assertFalse(credentials.getOptionalPrivateKey().isPresent()); } |
RegionAndIdToImage extends CacheLoader<RegionAndName, Image> { @Override public Image load(RegionAndName key) throws ExecutionException { try { org.jclouds.ec2.domain.Image image = Iterables.getOnlyElement(sync.getAMIApi().get() .describeImagesInRegion(key.getRegion(), imageIds(key.getName()))); return parser.apply(image); } catch (Exception e) { throw new ExecutionException(message(key, e), e); } } @Inject RegionAndIdToImage(EC2ImageParser parser, EC2Api sync); @Override Image load(RegionAndName key); static String message(RegionAndName key, Exception e); } | @SuppressWarnings("unchecked") @Test public void testApply() throws ExecutionException { EC2ImageParser parser = createMock(EC2ImageParser.class); EC2Api caller = createMock(EC2Api.class); AMIApi client = createMock(AMIApi.class); org.jclouds.ec2.domain.Image ec2Image = createMock(org.jclouds.ec2.domain.Image.class); Image image = createNiceMock(Image.class); Set<? extends org.jclouds.ec2.domain.Image> images = ImmutableSet.<org.jclouds.ec2.domain.Image> of(ec2Image); expect(caller.getAMIApi()).andReturn((Optional) Optional.of(client)).atLeastOnce(); expect(client.describeImagesInRegion("region", imageIds("ami"))).andReturn(Set.class.cast(images)); expect(parser.apply(ec2Image)).andReturn(image); replay(caller); replay(image); replay(parser); replay(client); RegionAndIdToImage function = new RegionAndIdToImage(parser, caller); assertEquals(function.load(new RegionAndName("region", "ami")), image); verify(caller); verify(image); verify(image); verify(client); }
@SuppressWarnings("unchecked") @Test(expectedExceptions = ExecutionException.class) public void testApplyNotFoundMakesExecutionException() throws ExecutionException { EC2ImageParser parser = createMock(EC2ImageParser.class); EC2Api caller = createMock(EC2Api.class); AMIApi client = createMock(AMIApi.class); org.jclouds.ec2.domain.Image ec2Image = createMock(org.jclouds.ec2.domain.Image.class); Image image = createNiceMock(Image.class); Set<? extends org.jclouds.ec2.domain.Image> images = ImmutableSet.<org.jclouds.ec2.domain.Image> of(ec2Image); expect(caller.getAMIApi()).andReturn((Optional) Optional.of(client)).atLeastOnce(); expect(client.describeImagesInRegion("region", imageIds("ami"))).andReturn(Set.class.cast(images)); expect(parser.apply(ec2Image)).andThrow(new ResourceNotFoundException()); replay(caller); replay(image); replay(parser); replay(client); RegionAndIdToImage function = new RegionAndIdToImage(parser, caller); assertEquals(function.load(new RegionAndName("region", "ami")), null); verify(caller); verify(image); verify(parser); verify(client); }
@SuppressWarnings("unchecked") @Test(expectedExceptions = ExecutionException.class) public void testApplyNoSuchElementExceptionMakesExecutionException() throws ExecutionException { EC2ImageParser parser = createMock(EC2ImageParser.class); EC2Api caller = createMock(EC2Api.class); AMIApi client = createMock(AMIApi.class); org.jclouds.ec2.domain.Image ec2Image = createMock(org.jclouds.ec2.domain.Image.class); Image image = createNiceMock(Image.class); Set<? extends org.jclouds.ec2.domain.Image> images = ImmutableSet.<org.jclouds.ec2.domain.Image> of(ec2Image); expect(caller.getAMIApi()).andReturn((Optional) Optional.of(client)).atLeastOnce(); expect(client.describeImagesInRegion("region", imageIds("ami"))).andReturn(Set.class.cast(images)); expect(parser.apply(ec2Image)).andThrow(new NoSuchElementException()); replay(caller); replay(image); replay(parser); replay(client); RegionAndIdToImage function = new RegionAndIdToImage(parser, caller); assertEquals(function.load(new RegionAndName("region", "ami")), null); verify(caller); verify(image); verify(parser); verify(client); } |
LoadPublicIpForInstanceOrNull extends CacheLoader<RegionAndName, String> { @Override public String load(final RegionAndName key) throws Exception { try { return Iterables.find(client.getElasticIPAddressApi().get().describeAddressesInRegion(key.getRegion()), new Predicate<PublicIpInstanceIdPair>() { @Override public boolean apply(PublicIpInstanceIdPair input) { return key.getName().equals(input.getInstanceId()); } }).getPublicIp(); } catch (NoSuchElementException e) { return null; } } @Inject LoadPublicIpForInstanceOrNull(EC2Api client); @Override String load(final RegionAndName key); } | @Test public void testReturnsPublicIpOnMatch() throws Exception { EC2Api client = createMock(EC2Api.class); ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class); expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce(); expect(ipClient.describeAddressesInRegion("region")).andReturn( ImmutableSet.<PublicIpInstanceIdPair> of(new PublicIpInstanceIdPair("region", "1.1.1.1", "i-blah", null))) .atLeastOnce(); replay(client); replay(ipClient); LoadPublicIpForInstanceOrNull parser = new LoadPublicIpForInstanceOrNull(client); assertEquals(parser.load(new RegionAndName("region", "i-blah")), "1.1.1.1"); verify(client); verify(ipClient); }
@Test public void testReturnsNullWhenNotFound() throws Exception { EC2Api client = createMock(EC2Api.class); ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class); expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce(); expect(ipClient.describeAddressesInRegion("region")).andReturn(ImmutableSet.<PublicIpInstanceIdPair> of()) .atLeastOnce(); replay(client); replay(ipClient); LoadPublicIpForInstanceOrNull parser = new LoadPublicIpForInstanceOrNull(client); assertEquals(parser.load(new RegionAndName("region", "i-blah")), null); verify(client); verify(ipClient); }
@Test public void testReturnsNullWhenNotAssigned() throws Exception { EC2Api client = createMock(EC2Api.class); ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class); expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce(); expect(ipClient.describeAddressesInRegion("region")).andReturn( ImmutableSet.<PublicIpInstanceIdPair> of(new PublicIpInstanceIdPair("region", "1.1.1.1", null, null))) .atLeastOnce(); replay(client); replay(ipClient); LoadPublicIpForInstanceOrNull parser = new LoadPublicIpForInstanceOrNull(client); assertEquals(parser.load(new RegionAndName("region", "i-blah")), null); verify(client); verify(ipClient); } |
PrivateKeySupplier implements Supplier<PrivateKey> { @Override public PrivateKey get() { try { return keyCache.getUnchecked(checkNotNull(creds.get(), "credential supplier returned null")); } catch (UncheckedExecutionException e) { AuthorizationException authorizationException = getFirstThrowableOfType(e, AuthorizationException.class); if (authorizationException != null) { throw authorizationException; } throw e; } } @Inject PrivateKeySupplier(@Provider Supplier<Credentials> creds, PrivateKeyForCredentials loader); @Override PrivateKey get(); } | @Test(expectedExceptions = AuthorizationException.class) public void testAuthorizationExceptionIsThrownOnBadKeys() { PrivateKeySupplier supplier = new PrivateKeySupplier( Suppliers.ofInstance(new Credentials("MOMMA", "FileNotFoundCredential")), new PrivateKeyForCredentials()); supplier.get(); } |
AtmosServerErrorRetryHandler implements HttpRetryHandler { public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { if (command.getFailureCount() > retryCountLimit) { return false; } if (response.getStatusCode() == 500) { byte[] content = HttpUtils.closeClientButKeepContentStream(response); if (content != null) { try { AtmosError error = utils.parseAtmosErrorFromContent(command, response, new String(content)); if (error.getCode() == AtmosErrorCode.SERVER_BUSY.getCode()) { return backoffHandler.shouldRetryRequest(command, response); } command.incrementFailureCount(); } catch (HttpException e) { logger.warn(e, "error parsing response: %s", new String(content)); } } else { command.incrementFailureCount(); } return false; } return false; } @Inject AtmosServerErrorRetryHandler(BackoffLimitedRetryHandler backoffHandler,
AtmosUtils utils); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); } | @Test public void testGet500WithoutError() { AtmosUtils utils = createMock(AtmosUtils.class); BackoffLimitedRetryHandler backoffLimitedRetryHandler = createMock(BackoffLimitedRetryHandler.class); HttpCommand command = createMock(HttpCommand.class); expect(command.getFailureCount()).andReturn(0).once(); expect(command.incrementFailureCount()).andReturn(1).once(); replay(utils, backoffLimitedRetryHandler, command); AtmosServerErrorRetryHandler retry = new AtmosServerErrorRetryHandler(backoffLimitedRetryHandler, utils); assertFalse(retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(500).build())); verify(utils, backoffLimitedRetryHandler, command); }
@Test public void testGet500WithError1040() { AtmosUtils utils = createMock(AtmosUtils.class); BackoffLimitedRetryHandler backoffLimitedRetryHandler = createMock(BackoffLimitedRetryHandler.class); HttpCommand command = createMock(HttpCommand.class); String content = String.format(HTTP_MESSAGE_FORMAT, 1040, "The server is busy. Please try again"); HttpResponse response = HttpResponse.builder().statusCode(500).payload(content).build(); expect(command.getFailureCount()).andReturn(0).once(); expect(utils.parseAtmosErrorFromContent(command, response, content)).andReturn(new AtmosError(1040, "The server is busy. Please try again")).once(); expect(backoffLimitedRetryHandler.shouldRetryRequest(command, response)).andReturn(true).once(); replay(utils, backoffLimitedRetryHandler, command); AtmosServerErrorRetryHandler retry = new AtmosServerErrorRetryHandler(backoffLimitedRetryHandler, utils); assertTrue(retry.shouldRetryRequest(command, response)); verify(utils, backoffLimitedRetryHandler, command); } |
BindMetadataToHeaders implements Binder { @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof AtmosObject, "this binder is only valid for AtmosObject!"); checkNotNull(request, "request"); AtmosObject object = AtmosObject.class.cast(input); checkNotNull(object.getPayload(), "object payload"); checkArgument(object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); byte[] contentMD5 = object.getContentMetadata().getContentMD5(); if (contentMD5 != null) { request = (R) request.toBuilder() .addHeader(AtmosHeaders.CHECKSUM, "MD5/0/" + BaseEncoding.base16().encode(contentMD5)) .build(); } return metaBinder.bindToRequest(request, object.getUserMetadata()); } @Inject protected BindMetadataToHeaders(BindUserMetadataToHeaders metaBinder); @Override R bindToRequest(R request, Object input); } | @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeAtmosObject() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: binder.bindToRequest(request, new File("foo")); }
@Test(expectedExceptions = NullPointerException.class) public void testNullIsBad() { HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); }
@Test(expectedExceptions = NullPointerException.class) public void testNullPayloadIsBad() { AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, object); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testNullContentLengthIllegal() { AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(null); object.setPayload(payload); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, object); } |
EndpointIfAlreadyExists implements Fallback<URI>, InvocationContext<EndpointIfAlreadyExists> { @Override public URI createOrPropagate(Throwable t) throws Exception { if (checkNotNull(t, "throwable") instanceof KeyAlreadyExistsException) { return endpoint; } throw propagate(t); } @Override URI createOrPropagate(Throwable t); @Override EndpointIfAlreadyExists setContext(HttpRequest request); } | @Test public void testFoundIsNullWhenEndpointNotSet() throws Exception { assertNull(new EndpointIfAlreadyExists().createOrPropagate(new KeyAlreadyExistsException())); }
@Test(expectedExceptions = RuntimeException.class) public void testNotFoundPropagates() throws Exception { new EndpointIfAlreadyExists().createOrPropagate(new RuntimeException()); }
@Test(expectedExceptions = NullPointerException.class) public void testNullIsBad() throws Exception { new EndpointIfAlreadyExists().createOrPropagate(null); } |
SignRequest implements HttpRequestFilter { public String createStringToSign(HttpRequest request) { utils.logRequest(signatureLog, request, ">>"); StringBuilder buffer = new StringBuilder(); appendMethod(request, buffer); appendPayloadMetadata(request, buffer); appendHttpHeaders(request, buffer); appendCanonicalizedResource(request, buffer); appendCanonicalizedHeaders(request, buffer); if (signatureWire.enabled()) signatureWire.output(buffer.toString()); return buffer.toString(); } @Inject SignRequest(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils); @Override HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String calculateSignature(String toSign); String signString(String toSign); } | @Test void testCreateStringToSign() throws IOException { String expects = Strings2.toStringAndClose(getClass().getResourceAsStream("/hashstring.txt")); HttpRequest request = newRequest(preconstructedHeaders().build()); String toSign = filter.createStringToSign(request); assertEquals(toSign, expects); } |
SignRequest implements HttpRequestFilter { public String signString(String toSign) { try { ByteProcessor<byte[]> hmacSHA1 = asByteProcessor(crypto.hmacSHA1(base64().decode(creds.get().credential))); return base64().encode(readBytes(toInputStream(toSign), hmacSHA1)); } catch (Exception e) { throw new HttpException("error signing request", e); } } @Inject SignRequest(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils); @Override HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String calculateSignature(String toSign); String signString(String toSign); } | @Test void testSignString() throws IOException, NoSuchAlgorithmException, InvalidKeyException { HttpRequest request = newRequest(preconstructedHeaders().build()); String toSign = filter.createStringToSign(request); String signature = filter.signString(toSign); assertEquals(signature, EXPECTED_SIGNATURE); } |
SignRequest implements HttpRequestFilter { @Override public HttpRequest filter(HttpRequest request) throws HttpException { Builder<String, String> builder = ImmutableMap.builder(); builder.put(AtmosHeaders.UID, creds.get().identity); String date = timeStampProvider.get(); builder.put(HttpHeaders.DATE, date); if (request.getHeaders().containsKey(AtmosHeaders.DATE)) builder.put(AtmosHeaders.DATE, date); request = request.toBuilder().replaceHeaders(Multimaps.forMap(builder.build())).build(); String signature = calculateSignature(createStringToSign(request)); request = request.toBuilder().replaceHeader(AtmosHeaders.SIGNATURE, signature).build(); utils.logRequest(signatureLog, request, "<<"); return request; } @Inject SignRequest(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils); @Override HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String calculateSignature(String toSign); String signString(String toSign); } | @Test void testFilter() throws IOException, NoSuchAlgorithmException, InvalidKeyException { HttpRequest request = newRequest(inputHeaders().build()); request = filter.filter(request); assertEquals(request.getFirstHeaderOrNull(AtmosHeaders.SIGNATURE), EXPECTED_SIGNATURE); }
@Test void testFilterReplacesOldValues() throws IOException, NoSuchAlgorithmException, InvalidKeyException { HttpRequest request = newRequest(inputHeaders().put(AtmosHeaders.SIGNATURE, "foo") .put(HttpHeaders.DATE, "foo").put(AtmosHeaders.DATE, "foo").put(AtmosHeaders.UID, "foo") .build()); request = filter.filter(request); assertEquals(request.getFirstHeaderOrNull(AtmosHeaders.SIGNATURE), EXPECTED_SIGNATURE); } |
ElasticStackComputeServiceAdapter implements
ComputeServiceAdapter<ServerInfo, Hardware, DriveInfo, Location> { @Override public NodeAndInitialCredentials<ServerInfo> createNodeWithGroupEncodedIntoName(String tag, String name, Template template) { long bootSize = (long) (template.getHardware().getVolumes().get(0).getSize() * 1024 * 1024 * 1024L); logger.debug(">> creating boot drive bytes(%d)", bootSize); DriveInfo drive = client .createDrive(new Drive.Builder().name(template.getImage().getId()).size(bootSize).build()); logger.debug("<< drive (%s)", drive); boolean success = driveNotClaimed.apply(drive); if (!success) { client.destroyDrive(drive.getUuid()); throw new IllegalStateException(String.format("could not create drive %s in time!", drive)); } logger.debug(">> imaging boot drive source(%s)", template.getImage().getId()); try { client.imageDrive(template.getImage().getId(), drive.getUuid(), ImageConversionType.GUNZIP); } catch (IllegalStateException ex) { logger.debug(">> could not image drive(%s). Cleaning up resources. [%s]", drive.getUuid(), ex.getMessage()); client.destroyDrive(drive.getUuid()); throw ex; } boolean ready = driveNotClaimed.apply(drive); if (!ready) { client.destroyDrive(drive.getUuid()); throw new IllegalStateException(String.format("could not image drive %s in time!", drive)); } logger.debug("<< imaged (%s)", drive); template.getOptions().userMetadata(ComputeServiceConstants.NODE_GROUP_KEY, tag); Server toCreate = small(name, drive.getUuid(), defaultVncPassword).mem(template.getHardware().getRam()) .cpu((int) (template.getHardware().getProcessors().get(0).getSpeed())) .tags(template.getOptions().getTags()).userMetadata(template.getOptions().getUserMetadata()).build(); ServerInfo from = client.createServer(toCreate); client.startServer(from.getUuid()); from = client.getServerInfo(from.getUuid()); return new NodeAndInitialCredentials<ServerInfo>(from, from.getUuid(), LoginCredentials.builder() .password(defaultVncPassword).build()); } @Inject ElasticStackComputeServiceAdapter(ElasticStackApi client, Predicate<DriveInfo> driveNotClaimed,
@Memoized Supplier<Map<String, WellKnownImage>> preinstalledImages, LoadingCache<String, DriveInfo> cache,
@Named(ElasticStackConstants.PROPERTY_VNC_PASSWORD) String defaultVncPassword,
@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override NodeAndInitialCredentials<ServerInfo> createNodeWithGroupEncodedIntoName(String tag, String name, Template template); @Override Iterable<Hardware> listHardwareProfiles(); @Override Iterable<DriveInfo> listImages(); @Override Iterable<ServerInfo> listNodes(); @Override Iterable<ServerInfo> listNodesByIds(final Iterable<String> ids); @Override Iterable<Location> listLocations(); @Override ServerInfo getNode(String id); @Override DriveInfo getImage(String id); @Override void destroyNode(String id); @Override void rebootNode(String id); @Override void resumeNode(String id); @Override void suspendNode(String id); } | @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "imageDrive call failed") public void testDiskIsDestroyedIfImageFails() { Supplier<Map<String, WellKnownImage>> preInstalledImageSupplier = Suppliers.ofInstance(Maps .<String, WellKnownImage> newHashMap()); LoadingCache<String, DriveInfo> driveCache = CacheBuilder.newBuilder().build( new CacheLoader<String, DriveInfo>() { @Override public DriveInfo load(String key) throws Exception { throw new IllegalStateException("cache should not be used"); } }); ElasticStackApi api = EasyMock.createMock(ElasticStackApi.class); Predicate<DriveInfo> driveNotClaimed = Predicates.alwaysTrue(); DriveInfo mockDrive = new DriveInfo.Builder().uuid(UUID.randomUUID().toString()).name("mock") .metrics(new DriveMetrics.Builder().build()).build(); expect(api.createDrive(anyObject(DriveInfo.class))).andReturn(mockDrive); api.imageDrive(image.getId(), mockDrive.getUuid(), ImageConversionType.GUNZIP); expectLastCall().andThrow(new IllegalStateException("imageDrive call failed")); api.destroyDrive(mockDrive.getUuid()); expectLastCall(); replay(api); ElasticStackComputeServiceAdapter adapter = new ElasticStackComputeServiceAdapter(api, driveNotClaimed, preInstalledImageSupplier, driveCache, "12345678", MoreExecutors.newDirectExecutorService()); try { adapter.createNodeWithGroupEncodedIntoName("mock-group", "mock-name", template); } catch (IllegalStateException ex) { verify(api); throw ex; } } |
RetryOnRenew implements HttpRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { boolean retry = false; switch (response.getStatusCode()) { case 401: Multimap<String, String> headers = command.getCurrentRequest().getHeaders(); if (headers != null && headers.containsKey(AuthHeaders.AUTH_USER) && headers.containsKey(AuthHeaders.AUTH_KEY) && !headers.containsKey(AuthHeaders.AUTH_TOKEN)) { retry = false; } else { Integer count = retryCountMap.getIfPresent(command); if (count == null) { logger.debug("invalidating authentication token - first time for %s", command); retryCountMap.put(command, 1); authenticationResponseCache.invalidateAll(); retry = true; } else { if (count + 1 >= NUM_RETRIES) { logger.debug("too many 401s - giving up after: %s for %s", count, command); retry = false; } else { logger.debug("invalidating authentication token - retry %s for %s", count, command); retryCountMap.put(command, count + 1); authenticationResponseCache.invalidateAll(); Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS); retry = true; } } } break; case 408: return backoffHandler.shouldRetryRequest(command, response); } return retry; } @Inject RetryOnRenew(LoadingCache<Credentials, AuthInfo> authenticationResponseCache,
BackoffLimitedRetryHandler backoffHandler); @Override boolean shouldRetryRequest(HttpCommand command, HttpResponse response); } | @Test public void test401ShouldRetry() { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = createMock(HttpRequest.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, AuthInfo> cache = createMock(LoadingCache.class); BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class); expect(command.getCurrentRequest()).andReturn(request); cache.invalidateAll(); expectLastCall(); expect(response.getPayload()).andReturn(Payloads.newStringPayload("")).anyTimes(); expect(response.getStatusCode()).andReturn(401).atLeastOnce(); replay(command); replay(response); replay(cache); replay(backoffHandler); RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler); assertTrue(retry.shouldRetryRequest(command, response)); verify(command); verify(response); verify(cache); }
@Test public void test401ShouldRetry4Times() { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = createMock(HttpRequest.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, AuthInfo> cache = createMock(LoadingCache.class); BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class); expect(command.getCurrentRequest()).andReturn(request).anyTimes(); expect(request.getHeaders()).andStubReturn(null); cache.invalidateAll(); expectLastCall().anyTimes(); expect(response.getPayload()).andReturn(Payloads.newStringPayload("")).anyTimes(); expect(response.getStatusCode()).andReturn(401).anyTimes(); replay(command, request, response, cache); RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler); for (int i = 0; i < RetryOnRenew.NUM_RETRIES - 1; ++i) { assertTrue(retry.shouldRetryRequest(command, response), "Expected retry to succeed"); } assertFalse(retry.shouldRetryRequest(command, response), "Expected retry to fail on attempt " + RetryOnRenew.NUM_RETRIES); verify(command, response, cache); }
@Test public void test408ShouldRetry() { HttpCommand command = createMock(HttpCommand.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, AuthInfo> cache = createMock(LoadingCache.class); BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class); expect(backoffHandler.shouldRetryRequest(command, response)).andReturn(true).once(); expect(response.getStatusCode()).andReturn(408).once(); replay(command); replay(response); replay(cache); replay(backoffHandler); RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler); assertTrue(retry.shouldRetryRequest(command, response)); verify(command); verify(response); verify(cache); verify(backoffHandler); } |
CredentialTypes { public static <T> String credentialTypeOf(T input) { Class<?> authenticationType = input.getClass(); CredentialType credentialType = findCredentialType(authenticationType); checkArgument(credentialType != null, "programming error: %s should have annotation %s", authenticationType, CredentialType.class.getName()); return credentialType.value(); } static String credentialTypeOf(T input); static Map<String, T> indexByCredentialType(Iterable<T> iterable); static CredentialType findCredentialType(Class<?> input); static final String API_ACCESS_KEY_CREDENTIALS; static final String PASSWORD_CREDENTIALS; static final String TOKEN_CREDENTIALS; } | @Test(expectedExceptions = IllegalArgumentException.class) public void testCredentialTypeOfWithoutAnnotation() { CredentialTypes.credentialTypeOf(""); } |
CredentialTypes { public static <T> Map<String, T> indexByCredentialType(Iterable<T> iterable) { return Maps.uniqueIndex(iterable, new Function<T, String>() { @Override public String apply(T input) { return credentialTypeOf(input); } }); } static String credentialTypeOf(T input); static Map<String, T> indexByCredentialType(Iterable<T> iterable); static CredentialType findCredentialType(Class<?> input); static final String API_ACCESS_KEY_CREDENTIALS; static final String PASSWORD_CREDENTIALS; static final String TOKEN_CREDENTIALS; } | @Test(expectedExceptions = IllegalArgumentException.class) public void testIndexByCredentialTypeWithoutAnnotation() { CredentialTypes.indexByCredentialType(ImmutableSet.of("")); } |
AWSServerErrorRetryHandler extends BackoffLimitedRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { switch (response.getStatusCode()) { case 500: case 503: if (response.getPayload() != null) { closeClientButKeepContentStream(response); AWSError error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response); if (error != null) { return shouldRetryRequestOnError(command, response, error); } } break; case 504: return super.shouldRetryRequest(command, response); } return false; } @Inject AWSServerErrorRetryHandler(AWSUtils utils,
@ServerError Set<String> retryableServerCodes); @Override boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); } | @Test public void testUnknown500DoesNotRetry() { AWSUtils utils = createMock(AWSUtils.class); HttpCommand command = createMock(HttpCommand.class); replay(utils, command); AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils, ImmutableSet.<String> of()); assertFalse(retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode()).build())); verify(utils, command); }
@Test(dataProvider = "codes") public void testDoesBackoffAndRetryForHttpStatusCodeAndErrorCode(int httpStatusCode, String errorCode) { AWSUtils utils = createMock(AWSUtils.class); HttpCommand command = createMock(HttpCommand.class); HttpRequest putBucket = HttpRequest.builder().method(PUT) .endpoint("https: HttpResponse response = HttpResponse.builder().statusCode(httpStatusCode) .payload(Payloads.newStringPayload(String.format("<Error><Code>%s</Code></Error>", errorCode))).build(); expect(command.getCurrentRequest()).andReturn(putBucket); final AtomicInteger counter = new AtomicInteger(); expect(command.incrementFailureCount()).andAnswer(new IAnswer<Integer>() { @Override public Integer answer() throws Throwable { return counter.incrementAndGet(); } }).anyTimes(); expect(command.isReplayable()).andReturn(true).anyTimes(); expect(command.getFailureCount()).andAnswer(new IAnswer<Integer>() { @Override public Integer answer() throws Throwable { return counter.get(); } }).anyTimes(); AWSError error = new AWSError(); error.setCode(errorCode); expect(utils.parseAWSErrorFromContent(putBucket, response)).andReturn(error); replay(utils, command); AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils, ImmutableSet.of("RequestLimitExceeded", "InternalError")); assert retry.shouldRetryRequest(command, response); verify(utils, command); }
@Test public void test504DoesRetry() { AWSUtils utils = createMock(AWSUtils.class); HttpCommand command = createMock(HttpCommand.class); expect(command.getFailureCount()).andReturn(1).anyTimes(); expect(command.incrementFailureCount()).andReturn(1); expect(command.isReplayable()).andReturn(true); replay(utils, command); AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils, ImmutableSet.<String> of()); assertTrue(retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(504).build())); verify(utils, command); } |
UpdateCDNContainerOptions extends BaseHttpRequestOptions { public UpdateCDNContainerOptions ttl(int ttl) { checkState(ttl >= Integer.valueOf(CDN_TTL_MIN), "ttl must be >= " + CDN_TTL_MIN); checkState(ttl <= Integer.valueOf(CDN_TTL_MAX), "ttl must be <= " + CDN_TTL_MAX); headers.put(CDN_TTL, Integer.toString(ttl)); return this; } UpdateCDNContainerOptions ttl(int ttl); UpdateCDNContainerOptions logRetention(boolean logRetention); UpdateCDNContainerOptions enabled(boolean enabled); UpdateCDNContainerOptions staticWebsiteDirectoryType(MediaType directoryType); UpdateCDNContainerOptions staticWebsiteErrorPage(String errorPage); UpdateCDNContainerOptions staticWebsiteIndexPage(String indexPage); UpdateCDNContainerOptions staticWebsiteListings(boolean listings); UpdateCDNContainerOptions staticWebsiteListingsCSS(String listingsCSS); static final UpdateCDNContainerOptions NONE; } | @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void testTTLLessThanMin() { UpdateCDNContainerOptions options = new UpdateCDNContainerOptions().ttl(CDN_TTL_MIN - 1); options.buildRequestHeaders().get(CDN_TTL); }
@SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void testTTLGreaterThanMax() { UpdateCDNContainerOptions options = new UpdateCDNContainerOptions().ttl(CDN_TTL_MAX + 1); options.buildRequestHeaders().get(CDN_TTL); } |
NestSlashKeys implements Function<Multimap<String, Supplier<JsonBall>>, Map<String, JsonBall>> { @Override public Map<String, JsonBall> apply(Multimap<String, Supplier<JsonBall>> from) { Map<String, JsonBall> autoAttrs = mergeSameKeys(from); Map<String, JsonBall> modifiableFlatMap = Maps.newLinkedHashMap(Maps.filterKeys(autoAttrs, new Predicate<String>() { @Override public boolean apply(String input) { return input.indexOf('/') == -1; } })); Map<String, JsonBall> withSlashesMap = Maps.difference(autoAttrs, modifiableFlatMap).entriesOnlyOnLeft(); for (Entry<String, JsonBall> entry : withSlashesMap.entrySet()) { List<String> keyParts = Lists.newArrayList(Splitter.on('/').split(entry.getKey())); JsonBall toInsert = entry.getValue(); try { putUnderContext(keyParts, toInsert, modifiableFlatMap); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("error inserting value in entry: " + entry.getKey(), e); } } return modifiableFlatMap; } @Inject NestSlashKeys(Json json); @Override Map<String, JsonBall> apply(Multimap<String, Supplier<JsonBall>> from); } | @Test public void testBase() { assertEquals( json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("java"))))), "{\"java\":\"java\"}"); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testIllegal() { json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("java")), "java/system", Suppliers.ofInstance(new JsonBall("system"))))); }
@Test public void testOne() { assertEquals( json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":\"time\"}")), "java/system", Suppliers.ofInstance(new JsonBall("system"))))), "{\"java\":{\"time\":\"time\",\"system\":\"system\"}}"); }
@Test public void testOneDuplicate() { assertEquals( json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":\"time\"}")), "java", Suppliers.ofInstance(new JsonBall("{\"system\":\"system\"}"))))), "{\"java\":{\"time\":\"time\",\"system\":\"system\"}}"); }
@Test public void testMerge() { assertEquals( json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java/time", Suppliers.ofInstance(new JsonBall("{\"2\":\"goodbye\"}"))))), "{\"java\":{\"time\":{\"1\":\"hello\",\"2\":\"goodbye\"}}}"); }
@Test public void testMergeNestedTwice() { assertEquals( json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java", Suppliers.ofInstance(new JsonBall("{\"time\":{\"2\":\"goodbye\"}}"))))), "{\"java\":{\"time\":{\"1\":\"hello\",\"2\":\"goodbye\"}}}"); }
@Test public void testReplaceList() { assertEquals( json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":{\"1\":[\"hello\"]}}")), "java/time", Suppliers.ofInstance(new JsonBall("{\"1\":[\"goodbye\"]}"))))), "{\"java\":{\"time\":{\"1\":[\"goodbye\"]}}}"); }
@Test public void testBase() { assertEquals( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("java"))))), "{\"java\":\"java\"}"); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testIllegal() { json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("java")), "java/system", Suppliers.ofInstance(new JsonBall("system"))))); }
@Test public void testOne() { assertEquals( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":\"time\"}")), "java/system", Suppliers.ofInstance(new JsonBall("system"))))), "{\"java\":{\"system\":\"system\",\"time\":\"time\"}}"); }
@Test public void testOneDuplicate() { assertEquals( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":\"time\"}")), "java", Suppliers.ofInstance(new JsonBall("{\"system\":\"system\"}"))))), "{\"java\":{\"system\":\"system\",\"time\":\"time\"}}"); }
@Test public void testMerge() { assertEquals( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java/time", Suppliers.ofInstance(new JsonBall("{\"2\":\"goodbye\"}"))))), "{\"java\":{\"time\":{\"2\":\"goodbye\",\"1\":\"hello\"}}}"); }
@Test public void testMergeNestedTwice() { assertEquals( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java", Suppliers.ofInstance(new JsonBall("{\"time\":{\"2\":\"goodbye\"}}"))))), "{\"java\":{\"time\":{\"2\":\"goodbye\",\"1\":\"hello\"}}}"); }
@Test public void testReplaceList() { assertEquals( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers.ofInstance(new JsonBall("{\"time\":{\"1\":[\"hello\"]}}")), "java/time", Suppliers.ofInstance(new JsonBall("{\"1\":[\"goodbye\"]}"))))), "{\"java\":{\"time\":{\"1\":[\"goodbye\"]}}}"); } |
CreateNodeAndPopulateAutomaticAttributesImpl implements CreateNodeAndPopulateAutomaticAttributes { @Override public Node execute(Node node) { logger.trace("creating node %s", node.getName()); Node withAutomatic = Node.builder() .name(node.getName()) .normalAttributes(node.getNormalAttributes()) .overrideAttributes(node.getOverrideAttributes()) .defaultAttributes(node.getDefaultAttributes()) .automaticAttributes(node.getAutomaticAttributes()) .automaticAttributes(automaticSupplier.get()) .runList(node.getRunList()) .environment(node.getEnvironment()) .build(); chef.createNode(withAutomatic); logger.debug("created node %s", withAutomatic.getName()); return node; } @Inject CreateNodeAndPopulateAutomaticAttributesImpl(ChefApi chef,
@Automatic Supplier<Map<String, JsonBall>> automaticSupplier); @Override Node execute(Node node); @Override Node execute(String nodeName, Iterable<String> runList); } | @Test public void testWithNoRunlist() { ChefApi chef = createMock(ChefApi.class); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(ImmutableMap.<String, JsonBall> of()); Node nodeWithAutomatic = Node.builder().name("name").environment("_default") .automaticAttributes(automaticSupplier.get()).build(); chef.createNode(nodeWithAutomatic); replay(chef); CreateNodeAndPopulateAutomaticAttributesImpl updater = new CreateNodeAndPopulateAutomaticAttributesImpl(chef, automaticSupplier); updater.execute("name", ImmutableSet.<String> of()); verify(chef); } |
UpdateAutomaticAttributesOnNodeImpl implements UpdateAutomaticAttributesOnNode { @Override public void execute(String nodeName) { logger.trace("updating node %s", nodeName); Node node = chef.getNode(nodeName); Node updated = Node.builder() .name(node.getName()) .normalAttributes(node.getNormalAttributes()) .overrideAttributes(node.getOverrideAttributes()) .defaultAttributes(node.getDefaultAttributes()) .automaticAttributes(automaticSupplier.get()) .runList(node.getRunList()) .environment(node.getEnvironment()) .build(); chef.updateNode(updated); logger.debug("updated node %s", nodeName); } @Inject UpdateAutomaticAttributesOnNodeImpl(ChefApi chef, @Automatic Supplier<Map<String, JsonBall>> automaticSupplier); @Override void execute(String nodeName); } | @Test public void test() { ChefApi chef = createMock(ChefApi.class); Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall> of(); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic); Node node = Node.builder().name("name").environment("_default").build(); Node nodeWithAutomatic = Node.builder().name("name").environment("_default").automaticAttributes(automatic) .build(); expect(chef.getNode("name")).andReturn(node); expect(chef.updateNode(nodeWithAutomatic)).andReturn(null); replay(chef); UpdateAutomaticAttributesOnNodeImpl updater = new UpdateAutomaticAttributesOnNodeImpl(chef, automaticSupplier); updater.execute("name"); verify(chef); } |
GroupToBootScript { public Statement apply(String group, @Nullable String nodeName) { BootstrapConfig config = null; try { config = bootstrapConfigForGroup.load(checkNotNull(group, "group")); } catch (Exception ex) { throw Throwables.propagate(ex); } String chefConfigDir = "{root}etc{fs}chef"; String chefBootFile = chefConfigDir + "{fs}first-boot.json"; ImmutableList.Builder<Statement> statements = ImmutableList.builder(); statements.add(new ExitInsteadOfReturn(installChef)); statements.add(exec("{md} " + chefConfigDir)); if (config.getSslCAFile() != null) { statements.add(createOrOverwriteFile(chefConfigDir + "{fs}chef-server.crt", Splitter.on(newLinePattern).split(config.getSslCAFile()))); } statements.add(createClientRbFile(chefConfigDir + "{fs}client.rb", group, nodeName, config)); statements.add(createOrOverwriteFile(chefConfigDir + "{fs}validation.pem", Splitter.on(newLinePattern).split(Pems.pem(validatorCredential.get())))); statements.add(createAttributesFile(chefBootFile, config)); statements.add(exec("chef-client -j " + chefBootFile)); return new StatementList(statements.build()); } @Inject GroupToBootScript(@Provider Supplier<URI> endpoint, CacheLoader<String, BootstrapConfig> bootstrapConfigForGroup,
@InstallChef Statement installChef, @Validator Optional<String> validatorName,
@Validator Optional<PrivateKey> validatorCredential); Statement apply(String group, @Nullable String nodeName); } | @Test(expectedExceptions = IllegalStateException.class) public void testMustHaveValidatorName() { Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class)); GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create("http: CacheLoader.from(Functions.forMap(ImmutableMap.of("foo", BootstrapConfig.builder().build()))), installChefOmnibus, Optional.<String> absent(), validatorCredential); fn.apply("foo", null); }
@Test(expectedExceptions = IllegalStateException.class) public void testMustHaveValidatorCredential() { GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create("http: CacheLoader.from(Functions.forMap(ImmutableMap.of("foo", BootstrapConfig.builder().build()))), installChefOmnibus, validatorName, Optional.<PrivateKey> absent()); fn.apply("foo", null); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Key 'foo' not present in map") public void testMustHaveRunScriptsName() { Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class)); GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create("http: CacheLoader.from(Functions.forMap(ImmutableMap.<String, BootstrapConfig> of())), installChefOmnibus, validatorName, validatorCredential); fn.apply("foo", null); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "null value in entry: foo=null") public void testMustHaveRunScriptsValue() { Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class)); GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create("http: CacheLoader.from(Functions.forMap(ImmutableMap.of("foo", (BootstrapConfig) null))), installChefOmnibus, validatorName, validatorCredential); fn.apply("foo", null); } |
UriForResource implements Function<Object, URI> { @Override public URI apply(Object input) { checkArgument(checkNotNull(input, "input") instanceof Resource, "This function can only be applied to Resource objects"); return ((Resource) input).getUrl(); } @Override URI apply(Object input); } | @Test public void testWithValidResource() { Function<Object, URI> function = new UriForResource(); Resource res = Resource.builder().name("test").url(URI.create("http: URI result = function.apply(res); assertEquals(res.getUrl().toString(), result.toString()); }
@Test(expectedExceptions = NullPointerException.class) public void testWithNullInput() { Function<Object, URI> function = new UriForResource(); function.apply(null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testWithInvalidInput() { Function<Object, URI> function = new UriForResource(); function.apply(new Object()); }
@Test public void testWithValidResource() { Function<Object, URI> function = new UriForResource(); Resource res = new Resource("test", URI.create("http: URI result = function.apply(res); assertEquals(res.getUrl().toString(), result.toString()); } |
BootstrapConfigForGroup implements Function<String, BootstrapConfig> { @Override public BootstrapConfig apply(String from) { DatabagItem bootstrapConfig = api.getDatabagItem(databag, from); checkState(bootstrapConfig != null, "databag item %s/%s not found", databag, from); return json.fromJson(bootstrapConfig.toString(), BootstrapConfig.class); } @Inject BootstrapConfigForGroup(@Named(CHEF_BOOTSTRAP_DATABAG) String databag, ChefApi api, Json json); @Override BootstrapConfig apply(String from); } | @Test(expectedExceptions = IllegalStateException.class) public void testWhenNoDatabagItem() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Client client = createMock(Client.class); BootstrapConfigForGroup fn = new BootstrapConfigForGroup("jclouds", chefApi, json); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(null); replay(client, chefApi); fn.apply("foo"); verify(client, chefApi); }
@Test public void testReturnsItem() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Client client = createMock(Client.class); BootstrapConfigForGroup fn = new BootstrapConfigForGroup("jclouds", chefApi, json); DatabagItem databag = new DatabagItem("foo", "{\"environment\":\"development\",\"ssl_ca_file\":\"/etc/certs/chef-server.crt\"," + "\"ssl_verify_mode\": \":verify_peer\"," + "\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]," + "\"attributes\":{\"tomcat6\":{\"ssl_port\":8433}}}"); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(databag); replay(client, chefApi); BootstrapConfig config = fn.apply("foo"); assertEquals(config.getEnvironment(), "development"); assertEquals(config.getSslCAFile(), "/etc/certs/chef-server.crt"); assertEquals(config.getSslVerifyMode(), SSLVerifyMode.PEER); assertEquals(config.getRunList().get(0), "recipe[apache2]"); assertEquals(config.getRunList().get(1), "role[webserver]"); assertEquals(config.getAttributes().toString(), "{\"tomcat6\":{\"ssl_port\":8433}}"); verify(client, chefApi); } |
SignedHeaderAuth implements HttpRequestFilter { @VisibleForTesting String canonicalPath(String path) { path = path.replaceAll("\\/+", "/"); return path.endsWith("/") && path.length() > 1 ? path.substring(0, path.length() - 1) : path; } @Inject SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
Supplier<PrivateKey> supplyKey, @TimeStamp Provider<String> timeStampProvider, HttpUtils utils, Crypto crypto); HttpRequest filter(HttpRequest input); String createStringToSign(String request, String hashedPath, String contentHash, String timestamp); String sign(String toSign); static final String SIGNING_DESCRIPTION; } | @Test void canonicalizedPathRemovesMultipleSlashes() { assertEquals(signing_obj.canonicalPath(" }
@Test void canonicalizedPathRemovesTrailingSlash() { assertEquals(signing_obj.canonicalPath("/path/"), "/path"); } |
SignedHeaderAuth implements HttpRequestFilter { public HttpRequest filter(HttpRequest input) throws HttpException { HttpRequest request = input.toBuilder().endpoint(input.getEndpoint().toString().replace("%3F", "?")).build(); String contentHash = hashBody(request.getPayload()); Multimap<String, String> headers = ArrayListMultimap.create(); headers.put("X-Ops-Content-Hash", contentHash); String timestamp = timeStampProvider.get(); String toSign = createStringToSign(request.getMethod(), hashPath(request.getEndpoint().getPath()), contentHash, timestamp); headers.put("X-Ops-Userid", creds.get().identity); headers.put("X-Ops-Sign", SIGNING_DESCRIPTION); request = calculateAndReplaceAuthorizationHeaders(request, toSign); headers.put("X-Ops-Timestamp", timestamp); utils.logRequest(signatureLog, request, "<<"); return request.toBuilder().replaceHeaders(headers).build(); } @Inject SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
Supplier<PrivateKey> supplyKey, @TimeStamp Provider<String> timeStampProvider, HttpUtils utils, Crypto crypto); HttpRequest filter(HttpRequest input); String createStringToSign(String request, String hashedPath, String contentHash, String timestamp); String sign(String toSign); static final String SIGNING_DESCRIPTION; } | @Test void shouldGenerateTheCorrectStringToSignAndSignatureWithNoBody() { HttpRequest request = HttpRequest.builder().method(HttpMethod.DELETE).endpoint("http: .build(); request = signing_obj.filter(request); Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders()); assertEqualsNoOrder(headersWithoutContentLength.entries().toArray(), EXPECTED_SIGN_RESULT_EMPTY.entries() .toArray()); }
@Test void shouldNotChokeWhenSigningARequestForAResourceWithALongName() { StringBuilder path = new StringBuilder("nodes/"); for (int i = 0; i < 100; i++) path.append('A'); HttpRequest request = HttpRequest.builder().method(HttpMethod.PUT) .endpoint("http: signing_obj.filter(request); }
@Test void shouldReplacePercentage3FWithQuestionMarkAtUrl() { StringBuilder path = new StringBuilder("nodes/"); path.append("test/cookbooks/myCookBook%3Fnum_versions=5"); HttpRequest request = HttpRequest.builder().method(HttpMethod.GET) .endpoint("http: request = signing_obj.filter(request); assertTrue(request.getRequestLine().contains("?num_versions=5")); } |
Role { public static Builder builder() { return new Builder(); } @ConstructorProperties({ "name", "description", "default_attributes", "run_list", "override_attributes", "env_run_lists" }) protected Role(String name, String description, @Nullable Map<String, JsonBall> defaultAttributes,
@Nullable List<String> runList, @Nullable Map<String, JsonBall> overrideAttributes,
@Nullable Map<String, List<String>> envRunList); static Builder builder(); String getName(); String getDescription(); Map<String, JsonBall> getOverrideAttributes(); Map<String, JsonBall> getDefaultAttributes(); List<String> getRunList(); Map<String, List<String>> getEnvRunList(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); } | @Test(expectedExceptions = NullPointerException.class) public void canNotAddEnvRunListMapThatIsNull() { Role.builder().envRunList((Map<String, List<String>>) null); }
@Test(expectedExceptions = NullPointerException.class) public void canNotAddRunListForEnvironmentThatIsNull() { Role.builder().envRunList("does.not.matter", (List<String>) null); }
@Test(expectedExceptions = NullPointerException.class) public void canNotUseNullEnvNameWhenAddingEnvRunListEntry() { Role.builder().envRunListElement((String) null, "does.not.matter"); }
@Test(expectedExceptions = NullPointerException.class) public void canNotUseNullEntryWhenAddingEnvRunListEntry() { Role.builder().envRunListElement("does.not.matter", (String) null); } |
ParseCredentialsFromJsonResponse implements
Function<HttpResponse, Credentials> { @Override public Credentials apply(HttpResponse input) { Map<String, Credentials> returnVal = parser.apply(input); checkState(!(returnVal.size() > 1), "expecting only 1 credential in response, but had more: " + returnVal.keySet()); return (!returnVal.isEmpty()) ? Iterables.getOnlyElement(returnVal.values()) : null; } @Inject ParseCredentialsFromJsonResponse(
ParseServerNameToCredentialsMapFromJsonResponse parser); @Override Credentials apply(HttpResponse input); } | @Test(expectedExceptions = IllegalStateException.class) public void testFailWhenTooManyPasswords() throws UnknownHostException { InputStream is = getClass().getResourceAsStream("/test_credentials_list.json"); HttpResponse response = HttpResponse.builder().statusCode(200).message("ok").payload(is).build(); ParseCredentialsFromJsonResponse parser = i.getInstance(ParseCredentialsFromJsonResponse.class); parser.apply(response); }
@Test public void testValid() throws UnknownHostException { InputStream is = getClass().getResourceAsStream("/test_credential.json"); HttpResponse response = HttpResponse.builder().statusCode(200).message("ok").payload(is).build(); ParseCredentialsFromJsonResponse parser = i.getInstance(ParseCredentialsFromJsonResponse.class); Credentials creds = parser.apply(response); assertEquals(creds.identity, "root"); assertEquals(creds.credential, "zot40ced"); } |
ServerToNodeMetadata implements Function<Server, NodeMetadata> { @Override public NodeMetadata apply(Server from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); Location location = Iterables.find(locations.get(), LocationPredicates.idEquals(from.getDatacenter().getId() + "")); builder.location(location); builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName())); builder.hardware(parseHardware(from)); builder.imageId(from.getImage().getId() + ""); Image image = parseImage(from); if (image != null) builder.operatingSystem(image.getOperatingSystem()); builder.status(serverStateToNodeStatus.get(from.getState())); builder.publicAddresses(ImmutableSet.of(from.getIp().getIp())); return builder.build(); } @Inject ServerToNodeMetadata(Map<ServerState, Status> serverStateToNodeStatus,
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares,
@Memoized Supplier<Set<? extends Location>> locations,
GroupNamingConvention.Factory namingConvention); @Override NodeMetadata apply(Server from); } | @SuppressWarnings("unchecked") @Test public void testApplySetsTagFromNameAndCredentialsFromName() { Map<ServerState, Status> serverStateToNodeStatus = createMock(Map.class); org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); Option dc = Option.createWithIdNameAndDescription(1L, "US-West-1", "US West 1 Datacenter"); Option ram = Option.createWithIdNameAndDescription(1L, "512MB", "Server with 512MB RAM"); Set<? extends org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage); Server server = createMock(Server.class); expect(server.getId()).andReturn(1000L).atLeastOnce(); expect(server.getName()).andReturn("group-ff").atLeastOnce(); expect(server.getState()).andReturn(ServerState.ON).atLeastOnce(); expect(serverStateToNodeStatus.get(ServerState.ON)).andReturn(Status.RUNNING); Location location = new LocationBuilder().scope(LocationScope.ZONE).id("1").description("US-West-1").build(); Set< ? extends Location> locations = ImmutableSet.< Location> of( location); expect(server.getIp()).andReturn(Ip.builder().ip("127.0.0.1").build()); ServerImage image = createMock(ServerImage.class); expect(server.getImage()).andReturn(image).atLeastOnce(); expect(server.getRam()).andReturn(ram).atLeastOnce(); expect(server.getDatacenter()).andReturn(dc).atLeastOnce(); expect(image.getId()).andReturn(2000L).atLeastOnce(); expect(jcImage.getProviderId()).andReturn("2000").atLeastOnce(); expect(jcImage.getLocation()).andReturn(location).atLeastOnce(); expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce(); replay(serverStateToNodeStatus); replay(server); replay(image); replay(jcImage); ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers .<Set<? extends Image>> ofInstance(images), Suppliers .<Set<? extends Hardware>> ofInstance(GoGridHardwareSupplier.H_ALL), Suppliers .<Set<? extends Location>> ofInstance(locations), namingConvention); NodeMetadata metadata = parser.apply(server); assertEquals(metadata.getLocation(), location); assertEquals(metadata.getImageId(), "2000"); assertEquals(metadata.getGroup(), "group"); verify(serverStateToNodeStatus); verify(image); verify(server); verify(jcImage); }
@SuppressWarnings("unchecked") @Test public void testApplySetsTagFromNameAndCredentialsFromName() { Map<ServerState, Status> serverStateToNodeStatus = createMock(Map.class); org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); Option dc = Option.createWithIdNameAndDescription(1l, "US-West-1", "US West 1 Datacenter"); Option ram = Option.createWithIdNameAndDescription(1l, "512MB", "Server with 512MB RAM"); Set<? extends org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage); Server server = createMock(Server.class); expect(server.getId()).andReturn(1000l).atLeastOnce(); expect(server.getName()).andReturn("group-ff").atLeastOnce(); expect(server.getState()).andReturn(ServerState.ON).atLeastOnce(); expect(serverStateToNodeStatus.get(ServerState.ON)).andReturn(Status.RUNNING); Location location = new LocationBuilder().scope(LocationScope.ZONE).id("1").description("US-West-1").build(); Set< ? extends Location> locations = ImmutableSet.< Location> of( location); expect(server.getIp()).andReturn(Ip.builder().ip("127.0.0.1").build()); ServerImage image = createMock(ServerImage.class); expect(server.getImage()).andReturn(image).atLeastOnce(); expect(server.getRam()).andReturn(ram).atLeastOnce(); expect(server.getDatacenter()).andReturn(dc).atLeastOnce(); expect(image.getId()).andReturn(2000l).atLeastOnce(); expect(jcImage.getProviderId()).andReturn("2000").atLeastOnce(); expect(jcImage.getLocation()).andReturn(location).atLeastOnce(); expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce(); replay(serverStateToNodeStatus); replay(server); replay(image); replay(jcImage); ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers .<Set<? extends Image>> ofInstance(images), Suppliers .<Set<? extends Hardware>> ofInstance(GoGridHardwareSupplier.H_ALL), Suppliers .<Set<? extends Location>> ofInstance(locations), namingConvention); NodeMetadata metadata = parser.apply(server); assertEquals(metadata.getLocation(), location); assertEquals(metadata.getImageId(), "2000"); assertEquals(metadata.getGroup(), "group"); verify(serverStateToNodeStatus); verify(image); verify(server); verify(jcImage); } |
VirtualGuestToJson implements Binder { @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(input instanceof VirtualGuest); VirtualGuest virtualGuest = VirtualGuest.class.cast(checkNotNull(input, "input")); request.setPayload(buildJson(virtualGuest)); return request; } @Inject VirtualGuestToJson(Json json); @Override R bindToRequest(R request, Object input); static final String USER_DATA_KEY; } | @Test public void testVirtualGuestWithOperatingSystem() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("https: VirtualGuestToJson binder = new VirtualGuestToJson(json); VirtualGuest virtualGuestWithOS = VirtualGuest.builder() .hostname("hostname") .domain("domain") .startCpus(1) .maxMemory(1024) .datacenter(Datacenter.builder() .name("datacenterName") .build()) .operatingSystem(OperatingSystem.builder().id("123456789") .operatingSystemReferenceCode("UBUNTU_12_64") .build()) .localDiskFlag(true) .networkComponents(ImmutableSet.<VirtualGuestNetworkComponent>of()) .build(); request = binder.bindToRequest(request, virtualGuestWithOS); assertEquals(request.getPayload().getRawContent(), "{" + "\"parameters\":[{\"hostname\":\"hostname\",\"domain\":\"domain\",\"startCpus\":1,\"maxMemory\":1024,\"hourlyBillingFlag\":false,\"localDiskFlag\":true,\"dedicatedAccountHostOnlyFlag\":false,\"privateNetworkOnlyFlag\":false,\"operatingSystemReferenceCode\":\"UBUNTU_12_64\",\"datacenter\":{\"name\":\"datacenterName\"}}]}"); }
@Test public void testVirtualGuestWithVirtualGuestBlockDeviceTemplateGroup() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("https: VirtualGuestToJson binder = new VirtualGuestToJson(json); VirtualGuest virtualGuestWithVirtualGuestBlockDeviceTemplateGroup = VirtualGuest.builder() .hostname("hostname") .domain("domain") .startCpus(1) .maxMemory(1024) .datacenter(Datacenter.builder() .name("datacenterName") .build()) .blockDeviceTemplateGroup(VirtualGuestBlockDeviceTemplateGroup.builder() .globalIdentifier("ffaafa98-4b4a-4fa7-b9f7-b1bad5ec50f0") .build()) .localDiskFlag(true) .networkComponents(ImmutableSet.<VirtualGuestNetworkComponent>of()) .build(); request = binder.bindToRequest(request, virtualGuestWithVirtualGuestBlockDeviceTemplateGroup); assertEquals(request.getPayload().getRawContent(), "{" + "\"parameters\":[{" + "\"hostname\":\"hostname\"," + "\"domain\":\"domain\"," + "\"startCpus\":1," + "\"maxMemory\":1024," + "\"hourlyBillingFlag\":false," + "\"localDiskFlag\":true," + "\"dedicatedAccountHostOnlyFlag\":false," + "\"privateNetworkOnlyFlag\":false," + "\"blockDeviceTemplateGroup\":{\"globalIdentifier\":\"ffaafa98-4b4a-4fa7-b9f7-b1bad5ec50f0\"}," + "\"datacenter\":{\"name\":\"datacenterName\"}}]}"); } |
TagToJson implements Binder { @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(input instanceof Set); Set<String> tags = Set.class.cast(checkNotNull(input, "input")); request.setPayload(buildJson(tags)); return request; } @Inject TagToJson(Json json); @Override R bindToRequest(R request, Object input); } | @Test public void testVirtualGuestWithOperatingSystem() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("https: TagToJson binder = new TagToJson(json); Set<String> tags = ImmutableSet.of("jclouds"); request = binder.bindToRequest(request, tags); assertEquals(request.getPayload().getRawContent(), "{\"parameters\":[\"jclouds\"]}"); } |
SoftLayerTemplateOptions extends TemplateOptions implements Cloneable { public String getDomainName() { return domainName; } @Override SoftLayerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); SoftLayerTemplateOptions domainName(String domainName); SoftLayerTemplateOptions blockDevices(Iterable<Integer> capacities); SoftLayerTemplateOptions blockDevices(Integer... capacities); SoftLayerTemplateOptions diskType(@Nullable String diskType); SoftLayerTemplateOptions portSpeed(@Nullable Integer portSpeed); SoftLayerTemplateOptions userData(@Nullable String userData); SoftLayerTemplateOptions primaryNetworkComponentNetworkVlanId(@Nullable Integer primaryNetworkComponentNetworkVlanId); SoftLayerTemplateOptions primaryBackendNetworkComponentNetworkVlanId(@Nullable Integer primaryBackendNetworkComponentNetworkVlanId); SoftLayerTemplateOptions hourlyBillingFlag(@Nullable Boolean hourlyBillingFlag); SoftLayerTemplateOptions dedicatedAccountHostOnlyFlag(@Nullable Boolean dedicatedAccountHostOnlyFlag); SoftLayerTemplateOptions privateNetworkOnlyFlag(@Nullable Boolean privateNetworkOnlyFlag); SoftLayerTemplateOptions postInstallScriptUri(@Nullable String postInstallScriptUri); SoftLayerTemplateOptions sshKeys(Iterable<Integer> sshKeys); SoftLayerTemplateOptions sshKeys(Integer... sshKeys); String getDomainName(); List<Integer> getBlockDevices(); String getDiskType(); Integer getPortSpeed(); String getUserData(); Integer getPrimaryNetworkComponentNetworkVlanId(); Integer getPrimaryBackendNetworkComponentNetworkVlanId(); Boolean isHourlyBillingFlag(); Boolean isDedicatedAccountHostOnlyFlag(); Boolean isPrivateNetworkOnlyFlag(); String getPostInstallScriptUri(); List<Integer> getSshKeys(); @Override SoftLayerTemplateOptions blockOnPort(int port, int seconds); @Override SoftLayerTemplateOptions inboundPorts(int... ports); @Override SoftLayerTemplateOptions authorizePublicKey(String publicKey); @Override SoftLayerTemplateOptions installPrivateKey(String privateKey); @Override SoftLayerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override SoftLayerTemplateOptions dontAuthorizePublicKey(); @Override SoftLayerTemplateOptions nameTask(String name); @Override SoftLayerTemplateOptions runAsRoot(boolean runAsRoot); @Override SoftLayerTemplateOptions runScript(Statement script); @Override SoftLayerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override SoftLayerTemplateOptions overrideLoginPassword(String password); @Override SoftLayerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override SoftLayerTemplateOptions overrideLoginUser(String loginUser); @Override SoftLayerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override SoftLayerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override SoftLayerTemplateOptions userMetadata(String key, String value); @Override SoftLayerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override SoftLayerTemplateOptions networks(Iterable<String> networks); } | @Test public void testDefaultDomainName() { TemplateOptions options = new SoftLayerTemplateOptions(); assertEquals(options.as(SoftLayerTemplateOptions.class).getDomainName(), "jclouds.org"); } |