index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/frigga/src/main/java/com/netflix/frigga | Create_ds/frigga/src/main/java/com/netflix/frigga/ami/BaseAmiInfo.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.ami;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Bean containing the various pieces of information available from the description of an AMI created by Netflix's
* bakery. Construct using the {@link parseDescription} factory method.
*/
public class BaseAmiInfo {
private static final String IMAGE_ID = "ami-[a-z0-9]{8}";
private static final Pattern BASE_AMI_ID_PATTERN = Pattern.compile("^.*?base_ami_id=(" + IMAGE_ID + ").*?");
private static final Pattern ANCESTOR_ID_PATTERN = Pattern.compile("^.*?ancestor_id=(" + IMAGE_ID + ").*?$");
private static final Pattern BASE_AMI_NAME_PATTERN = Pattern.compile("^.*?base_ami_name=([^,]+).*?$");
private static final Pattern ANCESTOR_NAME_PATTERN = Pattern.compile("^.*?ancestor_name=([^,]+).*?$");
private static final Pattern AMI_DATE_PATTERN = Pattern.compile(".*\\-(20[0-9]{6})(\\-.*)?");
private String baseAmiId;
private String baseAmiName;
private Date baseAmiDate;
private BaseAmiInfo() { }
/**
* Parse an AMI description into its component parts.
*
* @param imageDescription description field of an AMI created by Netflix's bakery
* @return bean representing the component parts of the AMI description
*/
public static BaseAmiInfo parseDescription(String imageDescription) {
BaseAmiInfo info = new BaseAmiInfo();
if (imageDescription == null) {
return info;
}
info.baseAmiId = extractBaseAmiId(imageDescription);
info.baseAmiName = extractBaseAmiName(imageDescription);
if (info.baseAmiName != null) {
Matcher dateMatcher = AMI_DATE_PATTERN.matcher(info.baseAmiName);
if (dateMatcher.matches()) {
try {
// Example: 20100823
info.baseAmiDate = new SimpleDateFormat("yyyyMMdd").parse(dateMatcher.group(1));
} catch (Exception ignored) {
// Ignore failure.
}
}
}
return info;
}
private static String extractBaseAmiId(String imageDescription) {
// base_ami_id=ami-1eb75c77,base_ami_name=servicenet-roku-qadd.dc.81210.10.44
Matcher matcher = BASE_AMI_ID_PATTERN.matcher(imageDescription);
if (matcher.matches()) {
return matcher.group(1);
}
// store=ebs,ancestor_name=ebs-centosbase-x86_64-20101124,ancestor_id=ami-7b4eb912
matcher = ANCESTOR_ID_PATTERN.matcher(imageDescription);
if (matcher.matches()) {
return matcher.group(1);
}
return null;
}
private static String extractBaseAmiName(String imageDescription) {
// base_ami_id=ami-1eb75c77,base_ami_name=servicenet-roku-qadd.dc.81210.10.44
Matcher matcher = BASE_AMI_NAME_PATTERN.matcher(imageDescription);
if (matcher.matches()) {
return matcher.group(1);
}
// store=ebs,ancestor_name=ebs-centosbase-x86_64-20101124,ancestor_id=ami-7b4eb912
matcher = ANCESTOR_NAME_PATTERN.matcher(imageDescription);
if (matcher.matches()) {
return matcher.group(1);
}
return null;
}
public String getBaseAmiId() {
return baseAmiId;
}
public String getBaseAmiName() {
return baseAmiName;
}
public Date getBaseAmiDate() {
return baseAmiDate != null ? (Date) baseAmiDate.clone() : null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((baseAmiDate == null) ? 0 : baseAmiDate.hashCode());
result = prime * result + ((baseAmiId == null) ? 0 : baseAmiId.hashCode());
result = prime * result + ((baseAmiName == null) ? 0 : baseAmiName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BaseAmiInfo other = (BaseAmiInfo) obj;
if (baseAmiDate == null) {
if (other.baseAmiDate != null)
return false;
} else if (!baseAmiDate.equals(other.baseAmiDate))
return false;
if (baseAmiId == null) {
if (other.baseAmiId != null)
return false;
} else if (!baseAmiId.equals(other.baseAmiId))
return false;
if (baseAmiName == null) {
if (other.baseAmiName != null)
return false;
} else if (!baseAmiName.equals(other.baseAmiName))
return false;
return true;
}
@Override
public String toString() {
return "BaseAmiInfo [baseAmiId=" + baseAmiId + ", baseAmiName=" + baseAmiName + ", baseAmiDate=" + baseAmiDate
+ "]";
}
}
| 5,400 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga | Create_ds/frigga/src/main/java/com/netflix/frigga/cluster/ClusterGrouper.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.cluster;
import com.netflix.frigga.Names;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utility methods for grouping ASG related objects by cluster. The cluster name is derived from the name of the ASG.
*/
public class ClusterGrouper {
private ClusterGrouper() { }
/**
* Groups a list of ASG related objects by cluster name.
*
* @param <T> Type to group
* @param inputs list of objects associated with an ASG
* @param nameProvider strategy object used to extract the ASG name of the object type of the input list
* @return map of cluster name to list of input object
*/
public static <T> Map<String, List<T>> groupByClusterName(List<T> inputs, AsgNameProvider<T> nameProvider) {
Map<String, List<T>> clusterNamesToAsgs = new HashMap<String, List<T>>();
for (T input : inputs) {
String clusterName = Names.parseName(nameProvider.extractAsgName(input)).getCluster();
if (!clusterNamesToAsgs.containsKey(clusterName)) {
clusterNamesToAsgs.put(clusterName, new ArrayList<T>());
}
clusterNamesToAsgs.get(clusterName).add(input);
}
return clusterNamesToAsgs;
}
/**
* Groups a list of ASG names by cluster name.
*
* @param asgNames list of asg names
* @return map of cluster name to list of ASG names in that cluster
*/
public static Map<String, List<String>> groupAsgNamesByClusterName(List<String> asgNames) {
return groupByClusterName(asgNames, new AsgNameProvider<String>() {
public String extractAsgName(String asgName) {
return asgName;
}
});
}
}
| 5,401 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga | Create_ds/frigga/src/main/java/com/netflix/frigga/cluster/AsgNameProvider.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.cluster;
/**
* Command object for extracting the ASG name from the provided type. Used with grouping ASGs by cluster.
*
* @param <T> Type to extract ASG name from
*/
public interface AsgNameProvider<T> {
/**
* Extracts the ASG name from an input object.
*
* @param object the object to inspect
* @return asg name of the provided object
*/
String extractAsgName(T object);
}
| 5,402 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga | Create_ds/frigga/src/main/java/com/netflix/frigga/elb/LoadBalancerNameBuilder.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.elb;
import com.netflix.frigga.NameBuilder;
/**
* Logic for constructing the name of a new load balancer in Asgard.
*/
public class LoadBalancerNameBuilder extends NameBuilder {
private String appName;
private String stack;
private String detail;
/**
* Constructs and returns the name of the load balancer.
*
* @return load balancer name
*/
public String buildLoadBalancerName() {
return combineAppStackDetail(appName, stack, detail);
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getStack() {
return stack;
}
public void setStack(String stack) {
this.stack = stack;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
| 5,403 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga | Create_ds/frigga/src/main/java/com/netflix/frigga/extensions/NamingResult.java | /**
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.extensions;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
/**
* The result of applying a NamingConvention.
*
* @param <T> the type of the result extracted from the name
*/
public interface NamingResult<T> {
/**
* @return the result (if any) extracted by a NamingConvention
*/
Optional<T> getResult();
/**
* @return the remaining part of a name component after applying a NamingConvention
*/
String getUnprocessed();
/**
* Warnings encountered applying a NamingConvention.
*
* Warnings are non fatal.
*
* @return any warnings encountered applying a NamingConvention.
*/
default Collection<String> getWarnings() {
return Collections.emptyList();
}
/**
* Errors encountered applying a NamingConvention.
*
* Errors are fatal - if errors were encountered this NamingResult should be considered unusable.
*
* @return any errors encountered applying a NamingConvention
*/
default Collection<String> getErrors() {
return Collections.emptyList();
}
/**
* @return whether this NamingResult represents a valid application of a NamingConvention
*/
default boolean isValid() {
return getErrors().isEmpty();
}
}
| 5,404 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga | Create_ds/frigga/src/main/java/com/netflix/frigga/extensions/NamingConvention.java | /**
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.extensions;
/**
* A NamingConvention can examine a component of a name to extract encoded values.
*
* @param <R> the NamingResult type
*/
public interface NamingConvention<R extends NamingResult<?>> {
/**
* Parses the nameComponent to extract the naming convention into a typed object
* @param nameComponent the name component to examine
* @return The NamingResult, never null
*/
R extractNamingConvention(String nameComponent);
}
| 5,405 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/labeledvariables/LabeledVariablesNamingConvention.java | /**
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.conventions.labeledvariables;
import com.netflix.frigga.NameConstants;
import com.netflix.frigga.extensions.NamingConvention;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A NamingConvention that applies the legacy labeled variables convention against a name.
*
* This logic was extracted out of Names (and referenced from there for backwards-ish compatibility).
*/
public class LabeledVariablesNamingConvention implements NamingConvention<LabeledVariablesNamingResult> {
private static final Pattern LABELED_VARS_PATTERN = Pattern.compile(
"(.*?)((?:(?:^|-)" +NameConstants.LABELED_VARIABLE + ")+)$");
//--------------------------
//VisibleForTesting:
static final Pattern LABELED_COUNTRIES_PATTERN = createLabeledVariablePattern(NameConstants.COUNTRIES_KEY);
static final Pattern LABELED_DEV_PHASE_KEY_PATTERN = createLabeledVariablePattern(NameConstants.DEV_PHASE_KEY);
static final Pattern LABELED_HARDWARE_KEY_PATTERN = createLabeledVariablePattern(NameConstants.HARDWARE_KEY);
static final Pattern LABELED_PARTNERS_KEY_PATTERN = createLabeledVariablePattern(NameConstants.PARTNERS_KEY);
static final Pattern LABELED_REVISION_KEY_PATTERN = createLabeledVariablePattern(NameConstants.REVISION_KEY);
static final Pattern LABELED_USED_BY_KEY_PATTERN = createLabeledVariablePattern(NameConstants.USED_BY_KEY);
static final Pattern LABELED_RED_BLACK_SWAP_KEY_PATTERN = createLabeledVariablePattern(NameConstants.RED_BLACK_SWAP_KEY);
static final Pattern LABELED_ZONE_KEY_PATTERN = createLabeledVariablePattern(NameConstants.ZONE_KEY);
//--------------------------
@Override
public LabeledVariablesNamingResult extractNamingConvention(String nameComponent) {
if (nameComponent == null || nameComponent.isEmpty()) {
return LabeledVariablesNamingResult.EMPTY;
}
Matcher labeledVarsMatcher = LABELED_VARS_PATTERN.matcher(nameComponent);
boolean labeledAndUnlabeledMatches = labeledVarsMatcher.matches();
if (!labeledAndUnlabeledMatches) {
return LabeledVariablesNamingResult.EMPTY;
}
String unprocessed = labeledVarsMatcher.group(1);
String labeledVariables = labeledVarsMatcher.group(2);
String countries = extractLabeledVariable(labeledVariables, LABELED_COUNTRIES_PATTERN);
String devPhase = extractLabeledVariable(labeledVariables, LABELED_DEV_PHASE_KEY_PATTERN);
String hardware = extractLabeledVariable(labeledVariables, LABELED_HARDWARE_KEY_PATTERN);
String partners = extractLabeledVariable(labeledVariables, LABELED_PARTNERS_KEY_PATTERN);
String revision = extractLabeledVariable(labeledVariables, LABELED_REVISION_KEY_PATTERN);
String usedBy = extractLabeledVariable(labeledVariables, LABELED_USED_BY_KEY_PATTERN);
String redBlackSwap = extractLabeledVariable(labeledVariables, LABELED_RED_BLACK_SWAP_KEY_PATTERN);
String zone = extractLabeledVariable(labeledVariables, LABELED_ZONE_KEY_PATTERN);
return new LabeledVariablesNamingResult(new LabeledVariables(countries, devPhase, hardware, partners, revision, usedBy, redBlackSwap, zone), unprocessed);
}
//VisibleForTesting
static String extractLabeledVariable(String labeledVariablesString, Pattern labelPattern) {
if (labeledVariablesString != null && !labeledVariablesString.isEmpty()) {
Matcher labelMatcher = labelPattern.matcher(labeledVariablesString);
boolean hasLabel = labelMatcher.find();
if (hasLabel) {
return labelMatcher.group(1);
}
}
return null;
}
private static Pattern createLabeledVariablePattern(String label) {
if (label == null || label.length() != 1 || !NameConstants.EXISTING_LABELS.contains(label)) {
throw new IllegalArgumentException(String.format("Invalid label %s must be one of %s", label, NameConstants.EXISTING_LABELS));
}
String labeledVariablePattern
= "-?"
+ label
+ NameConstants.LABELED_VAR_SEPARATOR
+ "(" + NameConstants.LABELED_VAR_VALUES + "+)";
return Pattern.compile(labeledVariablePattern);
}
}
| 5,406 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/labeledvariables/LabeledVariablesNamingResult.java | /**
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.conventions.labeledvariables;
import com.netflix.frigga.extensions.NamingResult;
import java.util.Optional;
/**
* The result of applying the LabeledVariablesNamingConvention.
*
* Contains LabeledVariables for the extracted labeled variables, as well as
* the unprocessed leading component of the name up to the start of the first labeled
* variable.
*/
public class LabeledVariablesNamingResult implements NamingResult<LabeledVariables> {
public static final LabeledVariablesNamingResult EMPTY = new LabeledVariablesNamingResult(null, null);
private final LabeledVariables labeledVariables;
private final String unprocessed;
public LabeledVariablesNamingResult(LabeledVariables labeledVariables, String unprocessed) {
this.labeledVariables = labeledVariables;
this.unprocessed = unprocessed;
}
@Override
public Optional<LabeledVariables> getResult() {
return Optional.ofNullable(labeledVariables);
}
@Override
public String getUnprocessed() {
return unprocessed;
}
}
| 5,407 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/labeledvariables/LabeledVariables.java | /**
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.conventions.labeledvariables;
import java.util.Objects;
/**
* The legacy labeled variables that can be encoded in the details component of a name.
*/
public class LabeledVariables {
private final String countries;
private final String devPhase;
private final String hardware;
private final String partners;
private final String revision;
private final String usedBy;
private final String redBlackSwap;
private final String zone;
public LabeledVariables(String countries, String devPhase, String hardware, String partners, String revision, String usedBy, String redBlackSwap, String zone) {
this.countries = countries;
this.devPhase = devPhase;
this.hardware = hardware;
this.partners = partners;
this.revision = revision;
this.usedBy = usedBy;
this.redBlackSwap = redBlackSwap;
this.zone = zone;
}
public String getCountries() {
return countries;
}
public String getDevPhase() {
return devPhase;
}
public String getHardware() {
return hardware;
}
public String getPartners() {
return partners;
}
public String getRevision() {
return revision;
}
public String getUsedBy() {
return usedBy;
}
public String getRedBlackSwap() {
return redBlackSwap;
}
public String getZone() {
return zone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LabeledVariables that = (LabeledVariables) o;
return Objects.equals(countries, that.countries) &&
Objects.equals(devPhase, that.devPhase) &&
Objects.equals(hardware, that.hardware) &&
Objects.equals(partners, that.partners) &&
Objects.equals(revision, that.revision) &&
Objects.equals(usedBy, that.usedBy) &&
Objects.equals(redBlackSwap, that.redBlackSwap) &&
Objects.equals(zone, that.zone);
}
@Override
public int hashCode() {
return Objects.hash(countries, devPhase, hardware, partners, revision, usedBy, redBlackSwap, zone);
}
@Override
public String toString() {
return "LabeledVariables{" +
"countries='" + countries + '\'' +
", devPhase='" + devPhase + '\'' +
", hardware='" + hardware + '\'' +
", partners='" + partners + '\'' +
", revision='" + revision + '\'' +
", usedBy='" + usedBy + '\'' +
", redBlackSwap='" + redBlackSwap + '\'' +
", zone='" + zone + '\'' +
'}';
}
}
| 5,408 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/sharding/ShardingNamingResult.java | /**
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.conventions.sharding;
import com.netflix.frigga.extensions.NamingResult;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
/**
* A NamingResult for ShardingNamingConvention.
*
* Result is a Map of {@code shardId -> Shard}, or {@code Optional.empty} if no shards were present.
*
* unprocessed is the remaining portion of the freeFormDetails after no more shards were present.
*
* Duplicate values for a shard Id are treated as a warning.
* The presence of the sharding pattern in the unprocessed text is treated as a warning.
*/
public class ShardingNamingResult implements NamingResult<Map<Integer, Shard>> {
private final Map<Integer, Shard> result;
private final String unprocessed;
private final Collection<String> warnings;
private final Collection<String> errors;
public ShardingNamingResult(Map<Integer, Shard> result, String unprocessed, Collection<String> warnings, Collection<String> errors) {
this.result = result != null && result.isEmpty() ? null : result;
this.unprocessed = unprocessed == null ? "" : unprocessed;
this.warnings = warnings == null || warnings.isEmpty() ? Collections.emptyList() : Collections.unmodifiableCollection(warnings);
this.errors = errors == null || errors.isEmpty() ? Collections.emptyList() : Collections.unmodifiableCollection(errors);
}
@Override
public Optional<Map<Integer, Shard>> getResult() {
return Optional.ofNullable(result);
}
@Override
public String getUnprocessed() {
return unprocessed;
}
@Override
public Collection<String> getWarnings() {
return warnings;
}
@Override
public Collection<String> getErrors() {
return errors;
}
}
| 5,409 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/sharding/Shard.java | /**
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.conventions.sharding;
import java.util.Objects;
/**
* A Shard is a pair with a numeric (greater than 0) id and value extracted out of the
* freeFormDetails component of a Name by ShardingNamingConvention.
*/
public class Shard {
private final Integer shardId;
private final String shardValue;
public Shard(Integer shardId, String shardValue) {
if (Objects.requireNonNull(shardId, "shardId") < 1) {
throw new IllegalArgumentException("shardId must be greater than 0");
}
if (Objects.requireNonNull(shardValue, "shardValue").isEmpty()) {
throw new IllegalArgumentException("shardValue must be non empty");
}
this.shardId = shardId;
this.shardValue = shardValue;
}
public Integer getShardId() {
return shardId;
}
public String getShardValue() {
return shardValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Shard shard = (Shard) o;
return shardId.equals(shard.shardId) &&
shardValue.equals(shard.shardValue);
}
@Override
public int hashCode() {
return Objects.hash(shardId, shardValue);
}
}
| 5,410 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions | Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/sharding/ShardingNamingConvention.java | /**
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.conventions.sharding;
import com.netflix.frigga.NameConstants;
import com.netflix.frigga.extensions.NamingConvention;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A NamingConvention that extracts Shards out of the freeFormDetails component of a name.
*
* Shards are only considered in the leading portion of the freeFormDetails, and are extracted while
* present, leaving any remaining portion of the details as the unprocessed portion of the NamingResult.
*
* A shard has a numeric id greater than 0.
* The first component of a shard value must be a non digit (leading digits get consumed into the shardId)
* A shard value can contain ASCII letters, digits, as well as '.', '_', '^', and '~'
*
* A specification for the ShardingNamingConvention follows:
* <pre>
* {@code
* ; the naming convention operates on free-form-details:
* free-form-details = *free-form-detail-char
*
* ; shard extraction specification:
* shards = [first-shard *additional-shard] [unprocessed]
* first-shard = shard-content
* additional-shard = "-" shard-content
* shard-content = "x" shard
* shard = shard-id shard-value
* shard-id = non-zero-digit *DIGIT
* shard-value = shard-value-first-char *shard-value-remaining-char
* unprocessed = *free-form-detail-char
*
* ; character sets:
* non-zero-digit = %x31-39
* shard-value-first-char = ALPHA
* shard-value-remaining-char = shard-value-first-char / DIGIT
* free-form-detail-char = shard-value-remaining-char / "-"
* }
* </pre>
*
* If multiple shard tokens are present with the same shardId, the last value supplied takes precedence, and
* the NamingResult will contain a warning indicating that there was a collision.
*
* If a shard appears to be present in the unprocessed portion of the freeFormDetails, this is noted as a warning.
*/
public class ShardingNamingConvention implements NamingConvention<ShardingNamingResult> {
private static final String SHARD_CONTENTS_REGEX = "x([1-9][0-9]*)([a-zA-Z][a-zA-Z0-9]*)(.*?)$";
private static final String VALID_SHARDS_REGEX = "(?:^|-)" + SHARD_CONTENTS_REGEX;
private static final String SHARD_WARNING_REGEX = ".*?-" + SHARD_CONTENTS_REGEX;
private static final Pattern SHARD_PATTERN = Pattern.compile(VALID_SHARDS_REGEX);
private static final Pattern SHARD_WARNING_PATTERN = Pattern.compile(SHARD_WARNING_REGEX);
@Override
public ShardingNamingResult extractNamingConvention(String freeFormDetails) {
Map<Integer, Shard> result = new HashMap<>();
String remaining = freeFormDetails;
Matcher matcher = SHARD_PATTERN.matcher(freeFormDetails);
Collection<String> warnings = new ArrayList<>();
while (matcher.matches() && !remaining.isEmpty()) {
Integer shardId = Integer.parseInt(matcher.group(1));
String shardValue = matcher.group(2);
Shard shard = new Shard(shardId, shardValue);
Shard previous = result.put(shardId, shard);
if (previous != null) {
warnings.add(duplicateShardWarning(previous, shard));
}
remaining = matcher.group(3);
matcher.reset(remaining);
}
if (!remaining.isEmpty()) {
Matcher warningsMatcher = SHARD_WARNING_PATTERN.matcher(remaining);
if (warningsMatcher.matches() && warningsMatcher.groupCount() > 2) {
warnings.add(shardInRemainingWarning(remaining, warningsMatcher.group(1), warningsMatcher.group(2)));
}
}
return new ShardingNamingResult(result, remaining, warnings, Collections.emptyList());
}
//visible for testing
static String duplicateShardWarning(Shard previous, Shard current) {
return String.format("duplicate shardId %s, shard value %s will be ignored in favor of %s",
current.getShardId(),
previous.getShardValue(),
current.getShardValue());
}
//visible for testing
static String shardInRemainingWarning(String remaining, String shardId, String shardValue) {
return String.format("detected additional shard configuration in remaining detail string %s. shard %s, value %s",
remaining, shardId, shardValue);
}
}
| 5,411 |
0 | Create_ds/frigga/src/main/java/com/netflix/frigga | Create_ds/frigga/src/main/java/com/netflix/frigga/autoscaling/AutoScalingGroupNameBuilder.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.frigga.autoscaling;
import com.netflix.frigga.Names;
import com.netflix.frigga.NameBuilder;
import com.netflix.frigga.NameConstants;
import com.netflix.frigga.NameValidation;
import java.util.regex.Pattern;
/**
* Logic for constructing the name of a new auto scaling group in Asgard.
*/
public class AutoScalingGroupNameBuilder extends NameBuilder {
private static final Pattern CONTAINS_PUSH_PATTERN =
Pattern.compile("(^|-)" + NameConstants.PUSH_FORMAT + "(-|$)");
private String appName;
private String stack;
private String detail;
private String countries;
private String devPhase;
private String hardware;
private String partners;
private String revision;
private String usedBy;
private String redBlackSwap;
private String zoneVar;
/**
* Constructs and returns the name of the auto scaling group without validation.
*
* @return auto scaling group name
*/
public String buildGroupName() {
return buildGroupName(false);
}
/**
* Construct and return the name of the auto scaling group.
*
* @param doValidation validate the supplied parameters before constructing the name
* @return auto scaling group name
*/
public String buildGroupName(Boolean doValidation) {
NameValidation.notEmpty(appName, "appName");
if (doValidation) {
validateNames(appName, stack, countries, devPhase, hardware, partners, revision, usedBy, redBlackSwap,
zoneVar);
if (detail != null && !detail.isEmpty() && !NameValidation.checkNameWithHyphen(detail)) {
throw new IllegalArgumentException("(Use alphanumeric characters only)");
}
validateDoesNotContainPush("stack", stack);
validateDoesNotContainPush("detail", detail);
}
// Build the labeled variables for the end of the group name.
String labeledVars = "";
labeledVars += generateIfSpecified(NameConstants.COUNTRIES_KEY, countries);
labeledVars += generateIfSpecified(NameConstants.DEV_PHASE_KEY, devPhase);
labeledVars += generateIfSpecified(NameConstants.HARDWARE_KEY, hardware);
labeledVars += generateIfSpecified(NameConstants.PARTNERS_KEY, partners);
labeledVars += generateIfSpecified(NameConstants.REVISION_KEY, revision);
labeledVars += generateIfSpecified(NameConstants.USED_BY_KEY, usedBy);
labeledVars += generateIfSpecified(NameConstants.RED_BLACK_SWAP_KEY, redBlackSwap);
labeledVars += generateIfSpecified(NameConstants.ZONE_KEY, zoneVar);
String result = combineAppStackDetail(appName, stack, detail) + labeledVars;
return result;
}
private static void validateDoesNotContainPush(String field, String name) {
if (name != null && !name.isEmpty() && CONTAINS_PUSH_PATTERN.matcher(name).find()) {
throw new IllegalArgumentException(field + " cannot contain a push version");
}
}
private static void validateNames(String... names) {
for (String name : names) {
if (name != null && !name.isEmpty() && !NameValidation.checkName(name)) {
throw new IllegalArgumentException("(Use alphanumeric characters only)");
}
}
}
private static String generateIfSpecified(String key, String value) {
if (value != null && !value.isEmpty()) {
return "-" + key + NameConstants.LABELED_VAR_SEPARATOR + value;
}
return "";
}
public static String buildNextGroupName(String asg) {
if (asg == null) throw new IllegalArgumentException("asg name must be specified");
Names parsed = Names.parseName(asg);
Integer sequence = parsed.getSequence();
Integer nextSequence = new Integer((sequence == null) ? 0 : sequence.intValue() + 1);
if (nextSequence.intValue() >= 1000) nextSequence = new Integer(0); // Hack
return String.format("%s-v%03d", parsed.getCluster(), nextSequence);
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public AutoScalingGroupNameBuilder withAppName(String appName) {
this.appName = appName;
return this;
}
public String getStack() {
return stack;
}
public void setStack(String stack) {
this.stack = stack;
}
public AutoScalingGroupNameBuilder withStack(String stack) {
this.stack = stack;
return this;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public AutoScalingGroupNameBuilder withDetail(String detail) {
this.detail = detail;
return this;
}
public String getCountries() {
return countries;
}
public void setCountries(String countries) {
this.countries = countries;
}
public AutoScalingGroupNameBuilder withCountries(String countries) {
this.countries = countries;
return this;
}
public String getDevPhase() {
return devPhase;
}
public void setDevPhase(String devPhase) {
this.devPhase = devPhase;
}
public AutoScalingGroupNameBuilder withDevPhase(String devPhase) {
this.devPhase = devPhase;
return this;
}
public String getHardware() {
return hardware;
}
public void setHardware(String hardware) {
this.hardware = hardware;
}
public AutoScalingGroupNameBuilder withHardware(String hardware) {
this.hardware = hardware;
return this;
}
public String getPartners() {
return partners;
}
public void setPartners(String partners) {
this.partners = partners;
}
public AutoScalingGroupNameBuilder withPartners(String partners) {
this.partners = partners;
return this;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
public AutoScalingGroupNameBuilder withRevision(String revision) {
this.revision = revision;
return this;
}
public String getUsedBy() {
return usedBy;
}
public void setUsedBy(String usedBy) {
this.usedBy = usedBy;
}
public AutoScalingGroupNameBuilder withUsedBy(String usedBy) {
this.usedBy = usedBy;
return this;
}
public String getRedBlackSwap() {
return redBlackSwap;
}
public void setRedBlackSwap(String redBlackSwap) {
this.redBlackSwap = redBlackSwap;
}
public AutoScalingGroupNameBuilder withRedBlackSwap(String redBlackSwap) {
this.redBlackSwap = redBlackSwap;
return this;
}
public String getZoneVar() {
return zoneVar;
}
public void setZoneVar(String zoneVar) {
this.zoneVar = zoneVar;
}
public AutoScalingGroupNameBuilder withZoneVar(String zoneVar) {
this.zoneVar = zoneVar;
return this;
}
}
| 5,412 |
0 | Create_ds/sagemaker-xgboost-container/docker/1.7-1/resources | Create_ds/sagemaker-xgboost-container/docker/1.7-1/resources/mms/ExecutionParameters.java | package software.amazon.ai.mms.plugins.endpoint;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import software.amazon.ai.mms.servingsdk.Context;
import software.amazon.ai.mms.servingsdk.ModelServerEndpoint;
import software.amazon.ai.mms.servingsdk.annotations.Endpoint;
import software.amazon.ai.mms.servingsdk.annotations.helpers.EndpointTypes;
import software.amazon.ai.mms.servingsdk.http.Request;
import software.amazon.ai.mms.servingsdk.http.Response;
/**
The modified endpoint source code for the jar used in this container.
You can create this endpoint by moving it by cloning the MMS repo:
> git clone https://github.com/awslabs/mxnet-model-server.git
Copy this file into plugins/endpoints/src/main/java/software/amazon/ai/mms/plugins/endpoints/
and then from the plugins directory, run:
> ./gradlew fJ
Modify file in plugins/endpoint/resources/META-INF/services/* to specify this file location
Then build the JAR:
> ./gradlew build
The jar should be available in plugins/endpoints/build/libs as endpoints-1.0.jar
**/
@Endpoint(
urlPattern = "execution-parameters",
endpointType = EndpointTypes.INFERENCE,
description = "Execution parameters endpoint")
public class ExecutionParameters extends ModelServerEndpoint {
@Override
public void doGet(Request req, Response rsp, Context ctx) throws IOException {
Properties prop = ctx.getConfig();
// 6 * 1024 * 1024
int maxRequestSize = Integer.parseInt(prop.getProperty("max_request_size", "6291456"));
SagemakerXgboostResponse response = new SagemakerXgboostResponse();
response.setMaxConcurrentTransforms(Integer.parseInt(prop.getProperty("NUM_WORKERS", "1")));
response.setBatchStrategy("MULTI_RECORD");
response.setMaxPayloadInMB(maxRequestSize / (1024 * 1024));
rsp.getOutputStream()
.write(
new GsonBuilder()
.setPrettyPrinting()
.create()
.toJson(response)
.getBytes(StandardCharsets.UTF_8));
}
/** Response for Model server endpoint */
public static class SagemakerXgboostResponse {
@SerializedName("MaxConcurrentTransforms")
private int maxConcurrentTransforms;
@SerializedName("BatchStrategy")
private String batchStrategy;
@SerializedName("MaxPayloadInMB")
private int maxPayloadInMB;
public SagemakerXgboostResponse() {
maxConcurrentTransforms = 4;
batchStrategy = "MULTI_RECORD";
maxPayloadInMB = 6;
}
public int getMaxConcurrentTransforms() {
return maxConcurrentTransforms;
}
public String getBatchStrategy() {
return batchStrategy;
}
public int getMaxPayloadInMB() {
return maxPayloadInMB;
}
public void setMaxConcurrentTransforms(int newMaxConcurrentTransforms) {
maxConcurrentTransforms = newMaxConcurrentTransforms;
}
public void setBatchStrategy(String newBatchStrategy) {
batchStrategy = newBatchStrategy;
}
public void setMaxPayloadInMB(int newMaxPayloadInMB) {
maxPayloadInMB = newMaxPayloadInMB;
}
}
}
| 5,413 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/java/software/amazon/cryptography/encryptionsdk | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/java/software/amazon/cryptography/encryptionsdk/internaldafny/__default.java | package software.amazon.cryptography.encryptionsdk.internaldafny;
public class __default extends software.amazon.cryptography.encryptionsdk.internaldafny._ExternBase___default {
}
| 5,414 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/ToNative.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk;
import java.lang.RuntimeException;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.Error;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.Error_AwsEncryptionSdkException;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.Error_CollectionOfErrors;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.Error_Opaque;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.IAwsEncryptionSdkClient;
import software.amazon.cryptography.encryptionsdk.model.AwsEncryptionSdkConfig;
import software.amazon.cryptography.encryptionsdk.model.AwsEncryptionSdkException;
import software.amazon.cryptography.encryptionsdk.model.CollectionOfErrors;
import software.amazon.cryptography.encryptionsdk.model.DecryptInput;
import software.amazon.cryptography.encryptionsdk.model.DecryptOutput;
import software.amazon.cryptography.encryptionsdk.model.EncryptInput;
import software.amazon.cryptography.encryptionsdk.model.EncryptOutput;
import software.amazon.cryptography.encryptionsdk.model.OpaqueError;
public class ToNative {
public static OpaqueError Error(Error_Opaque dafnyValue) {
OpaqueError.Builder nativeBuilder = OpaqueError.builder();
nativeBuilder.obj(dafnyValue.dtor_obj());
return nativeBuilder.build();
}
public static CollectionOfErrors Error(Error_CollectionOfErrors dafnyValue) {
CollectionOfErrors.Builder nativeBuilder = CollectionOfErrors.builder();
nativeBuilder.list(
software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToList(
dafnyValue.dtor_list(),
ToNative::Error));
nativeBuilder.message(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_message()));
return nativeBuilder.build();
}
public static AwsEncryptionSdkException Error(Error_AwsEncryptionSdkException dafnyValue) {
AwsEncryptionSdkException.Builder nativeBuilder = AwsEncryptionSdkException.builder();
nativeBuilder.message(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_message()));
return nativeBuilder.build();
}
public static RuntimeException Error(Error dafnyValue) {
if (dafnyValue.is_AwsEncryptionSdkException()) {
return ToNative.Error((Error_AwsEncryptionSdkException) dafnyValue);
}
if (dafnyValue.is_Opaque()) {
return ToNative.Error((Error_Opaque) dafnyValue);
}
if (dafnyValue.is_CollectionOfErrors()) {
return ToNative.Error((Error_CollectionOfErrors) dafnyValue);
}
if (dafnyValue.is_AwsCryptographyPrimitives()) {
return software.amazon.cryptography.primitives.ToNative.Error(dafnyValue.dtor_AwsCryptographyPrimitives());
}
if (dafnyValue.is_AwsCryptographyMaterialProviders()) {
return software.amazon.cryptography.materialproviders.ToNative.Error(dafnyValue.dtor_AwsCryptographyMaterialProviders());
}
OpaqueError.Builder nativeBuilder = OpaqueError.builder();
nativeBuilder.obj(dafnyValue);
return nativeBuilder.build();
}
public static AwsEncryptionSdkConfig AwsEncryptionSdkConfig(
software.amazon.cryptography.encryptionsdk.internaldafny.types.AwsEncryptionSdkConfig dafnyValue) {
AwsEncryptionSdkConfig.Builder nativeBuilder = AwsEncryptionSdkConfig.builder();
if (dafnyValue.dtor_commitmentPolicy().is_Some()) {
nativeBuilder.commitmentPolicy(software.amazon.cryptography.materialproviders.ToNative.ESDKCommitmentPolicy(dafnyValue.dtor_commitmentPolicy().dtor_value()));
}
if (dafnyValue.dtor_maxEncryptedDataKeys().is_Some()) {
nativeBuilder.maxEncryptedDataKeys((dafnyValue.dtor_maxEncryptedDataKeys().dtor_value()));
}
return nativeBuilder.build();
}
public static DecryptInput DecryptInput(
software.amazon.cryptography.encryptionsdk.internaldafny.types.DecryptInput dafnyValue) {
DecryptInput.Builder nativeBuilder = DecryptInput.builder();
nativeBuilder.ciphertext(software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer(dafnyValue.dtor_ciphertext()));
if (dafnyValue.dtor_materialsManager().is_Some()) {
nativeBuilder.materialsManager(software.amazon.cryptography.materialproviders.ToNative.CryptographicMaterialsManager(dafnyValue.dtor_materialsManager().dtor_value()));
}
if (dafnyValue.dtor_keyring().is_Some()) {
nativeBuilder.keyring(software.amazon.cryptography.materialproviders.ToNative.Keyring(dafnyValue.dtor_keyring().dtor_value()));
}
if (dafnyValue.dtor_encryptionContext().is_Some()) {
nativeBuilder.encryptionContext(software.amazon.cryptography.materialproviders.ToNative.EncryptionContext(dafnyValue.dtor_encryptionContext().dtor_value()));
}
return nativeBuilder.build();
}
public static DecryptOutput DecryptOutput(
software.amazon.cryptography.encryptionsdk.internaldafny.types.DecryptOutput dafnyValue) {
DecryptOutput.Builder nativeBuilder = DecryptOutput.builder();
nativeBuilder.plaintext(software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer(dafnyValue.dtor_plaintext()));
nativeBuilder.encryptionContext(software.amazon.cryptography.materialproviders.ToNative.EncryptionContext(dafnyValue.dtor_encryptionContext()));
nativeBuilder.algorithmSuiteId(software.amazon.cryptography.materialproviders.ToNative.ESDKAlgorithmSuiteId(dafnyValue.dtor_algorithmSuiteId()));
return nativeBuilder.build();
}
public static EncryptInput EncryptInput(
software.amazon.cryptography.encryptionsdk.internaldafny.types.EncryptInput dafnyValue) {
EncryptInput.Builder nativeBuilder = EncryptInput.builder();
nativeBuilder.plaintext(software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer(dafnyValue.dtor_plaintext()));
if (dafnyValue.dtor_encryptionContext().is_Some()) {
nativeBuilder.encryptionContext(software.amazon.cryptography.materialproviders.ToNative.EncryptionContext(dafnyValue.dtor_encryptionContext().dtor_value()));
}
if (dafnyValue.dtor_materialsManager().is_Some()) {
nativeBuilder.materialsManager(software.amazon.cryptography.materialproviders.ToNative.CryptographicMaterialsManager(dafnyValue.dtor_materialsManager().dtor_value()));
}
if (dafnyValue.dtor_keyring().is_Some()) {
nativeBuilder.keyring(software.amazon.cryptography.materialproviders.ToNative.Keyring(dafnyValue.dtor_keyring().dtor_value()));
}
if (dafnyValue.dtor_algorithmSuiteId().is_Some()) {
nativeBuilder.algorithmSuiteId(software.amazon.cryptography.materialproviders.ToNative.ESDKAlgorithmSuiteId(dafnyValue.dtor_algorithmSuiteId().dtor_value()));
}
if (dafnyValue.dtor_frameLength().is_Some()) {
nativeBuilder.frameLength((dafnyValue.dtor_frameLength().dtor_value()));
}
return nativeBuilder.build();
}
public static EncryptOutput EncryptOutput(
software.amazon.cryptography.encryptionsdk.internaldafny.types.EncryptOutput dafnyValue) {
EncryptOutput.Builder nativeBuilder = EncryptOutput.builder();
nativeBuilder.ciphertext(software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer(dafnyValue.dtor_ciphertext()));
nativeBuilder.encryptionContext(software.amazon.cryptography.materialproviders.ToNative.EncryptionContext(dafnyValue.dtor_encryptionContext()));
nativeBuilder.algorithmSuiteId(software.amazon.cryptography.materialproviders.ToNative.ESDKAlgorithmSuiteId(dafnyValue.dtor_algorithmSuiteId()));
return nativeBuilder.build();
}
public static ESDK AwsEncryptionSdk(IAwsEncryptionSdkClient dafnyValue) {
return new ESDK(dafnyValue);
}
}
| 5,415 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/ESDK.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk;
import Wrappers_Compile.Result;
import java.lang.IllegalArgumentException;
import java.util.Objects;
import software.amazon.cryptography.encryptionsdk.internaldafny.ESDKClient;
import software.amazon.cryptography.encryptionsdk.internaldafny.__default;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.Error;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.IAwsEncryptionSdkClient;
import software.amazon.cryptography.encryptionsdk.model.AwsEncryptionSdkConfig;
import software.amazon.cryptography.encryptionsdk.model.DecryptInput;
import software.amazon.cryptography.encryptionsdk.model.DecryptOutput;
import software.amazon.cryptography.encryptionsdk.model.EncryptInput;
import software.amazon.cryptography.encryptionsdk.model.EncryptOutput;
public class ESDK {
private final IAwsEncryptionSdkClient _impl;
protected ESDK(BuilderImpl builder) {
AwsEncryptionSdkConfig input = builder.AwsEncryptionSdkConfig();
software.amazon.cryptography.encryptionsdk.internaldafny.types.AwsEncryptionSdkConfig dafnyValue = ToDafny.AwsEncryptionSdkConfig(input);
Result<ESDKClient, Error> result = __default.ESDK(dafnyValue);
if (result.is_Failure()) {
throw ToNative.Error(result.dtor_error());
}
this._impl = result.dtor_value();
}
ESDK(IAwsEncryptionSdkClient impl) {
this._impl = impl;
}
public static Builder builder() {
return new BuilderImpl();
}
public DecryptOutput Decrypt(DecryptInput input) {
software.amazon.cryptography.encryptionsdk.internaldafny.types.DecryptInput dafnyValue = ToDafny.DecryptInput(input);
Result<software.amazon.cryptography.encryptionsdk.internaldafny.types.DecryptOutput, Error> result = this._impl.Decrypt(dafnyValue);
if (result.is_Failure()) {
throw ToNative.Error(result.dtor_error());
}
return ToNative.DecryptOutput(result.dtor_value());
}
public EncryptOutput Encrypt(EncryptInput input) {
software.amazon.cryptography.encryptionsdk.internaldafny.types.EncryptInput dafnyValue = ToDafny.EncryptInput(input);
Result<software.amazon.cryptography.encryptionsdk.internaldafny.types.EncryptOutput, Error> result = this._impl.Encrypt(dafnyValue);
if (result.is_Failure()) {
throw ToNative.Error(result.dtor_error());
}
return ToNative.EncryptOutput(result.dtor_value());
}
protected IAwsEncryptionSdkClient impl() {
return this._impl;
}
public interface Builder {
Builder AwsEncryptionSdkConfig(AwsEncryptionSdkConfig AwsEncryptionSdkConfig);
AwsEncryptionSdkConfig AwsEncryptionSdkConfig();
ESDK build();
}
static class BuilderImpl implements Builder {
protected AwsEncryptionSdkConfig AwsEncryptionSdkConfig;
protected BuilderImpl() {
}
public Builder AwsEncryptionSdkConfig(AwsEncryptionSdkConfig AwsEncryptionSdkConfig) {
this.AwsEncryptionSdkConfig = AwsEncryptionSdkConfig;
return this;
}
public AwsEncryptionSdkConfig AwsEncryptionSdkConfig() {
return this.AwsEncryptionSdkConfig;
}
public ESDK build() {
if (Objects.isNull(this.AwsEncryptionSdkConfig())) {
throw new IllegalArgumentException("Missing value for required field `AwsEncryptionSdkConfig`");
}
return new ESDK(this);
}
}
}
| 5,416 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/ToDafny.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk;
import Wrappers_Compile.Option;
import dafny.DafnyMap;
import dafny.DafnySequence;
import java.lang.Byte;
import java.lang.Character;
import java.lang.Long;
import java.lang.RuntimeException;
import java.util.Objects;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.AwsEncryptionSdkConfig;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.DecryptInput;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.DecryptOutput;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.EncryptInput;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.EncryptOutput;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.Error;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.Error_AwsEncryptionSdkException;
import software.amazon.cryptography.encryptionsdk.internaldafny.types.IAwsEncryptionSdkClient;
import software.amazon.cryptography.encryptionsdk.model.AwsEncryptionSdkException;
import software.amazon.cryptography.encryptionsdk.model.CollectionOfErrors;
import software.amazon.cryptography.encryptionsdk.model.OpaqueError;
import software.amazon.cryptography.materialproviders.internaldafny.types.ESDKAlgorithmSuiteId;
import software.amazon.cryptography.materialproviders.internaldafny.types.ESDKCommitmentPolicy;
import software.amazon.cryptography.materialproviders.internaldafny.types.ICryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.internaldafny.types.IKeyring;
public class ToDafny {
public static Error Error(RuntimeException nativeValue) {
if (nativeValue instanceof AwsEncryptionSdkException) {
return ToDafny.Error((AwsEncryptionSdkException) nativeValue);
}
if (nativeValue instanceof OpaqueError) {
return ToDafny.Error((OpaqueError) nativeValue);
}
if (nativeValue instanceof CollectionOfErrors) {
return ToDafny.Error((CollectionOfErrors) nativeValue);
}
return Error.create_Opaque(nativeValue);
}
public static Error Error(OpaqueError nativeValue) {
return Error.create_Opaque(nativeValue.obj());
}
public static Error Error(CollectionOfErrors nativeValue) {
DafnySequence<? extends Error> list = software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToSequence(
nativeValue.list(),
ToDafny::Error,
Error._typeDescriptor());
DafnySequence<? extends Character> message = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.getMessage());
return Error.create_CollectionOfErrors(list, message);
}
public static AwsEncryptionSdkConfig AwsEncryptionSdkConfig(
software.amazon.cryptography.encryptionsdk.model.AwsEncryptionSdkConfig nativeValue) {
Option<ESDKCommitmentPolicy> commitmentPolicy;
commitmentPolicy = Objects.nonNull(nativeValue.commitmentPolicy()) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.ESDKCommitmentPolicy(nativeValue.commitmentPolicy()))
: Option.create_None();
Option<Long> maxEncryptedDataKeys;
maxEncryptedDataKeys = Objects.nonNull(nativeValue.maxEncryptedDataKeys()) ?
Option.create_Some((nativeValue.maxEncryptedDataKeys()))
: Option.create_None();
return new AwsEncryptionSdkConfig(commitmentPolicy, maxEncryptedDataKeys);
}
public static DecryptInput DecryptInput(
software.amazon.cryptography.encryptionsdk.model.DecryptInput nativeValue) {
DafnySequence<? extends Byte> ciphertext;
ciphertext = software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence(nativeValue.ciphertext());
Option<ICryptographicMaterialsManager> materialsManager;
materialsManager = Objects.nonNull(nativeValue.materialsManager()) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.CryptographicMaterialsManager(nativeValue.materialsManager()))
: Option.create_None();
Option<IKeyring> keyring;
keyring = Objects.nonNull(nativeValue.keyring()) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.Keyring(nativeValue.keyring()))
: Option.create_None();
Option<DafnyMap<? extends DafnySequence<? extends Byte>, ? extends DafnySequence<? extends Byte>>> encryptionContext;
encryptionContext = (Objects.nonNull(nativeValue.encryptionContext()) && nativeValue.encryptionContext().size() > 0) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.EncryptionContext(nativeValue.encryptionContext()))
: Option.create_None();
return new DecryptInput(ciphertext, materialsManager, keyring, encryptionContext);
}
public static DecryptOutput DecryptOutput(
software.amazon.cryptography.encryptionsdk.model.DecryptOutput nativeValue) {
DafnySequence<? extends Byte> plaintext;
plaintext = software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence(nativeValue.plaintext());
DafnyMap<? extends DafnySequence<? extends Byte>, ? extends DafnySequence<? extends Byte>> encryptionContext;
encryptionContext = software.amazon.cryptography.materialproviders.ToDafny.EncryptionContext(nativeValue.encryptionContext());
ESDKAlgorithmSuiteId algorithmSuiteId;
algorithmSuiteId = software.amazon.cryptography.materialproviders.ToDafny.ESDKAlgorithmSuiteId(nativeValue.algorithmSuiteId());
return new DecryptOutput(plaintext, encryptionContext, algorithmSuiteId);
}
public static EncryptInput EncryptInput(
software.amazon.cryptography.encryptionsdk.model.EncryptInput nativeValue) {
DafnySequence<? extends Byte> plaintext;
plaintext = software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence(nativeValue.plaintext());
Option<DafnyMap<? extends DafnySequence<? extends Byte>, ? extends DafnySequence<? extends Byte>>> encryptionContext;
encryptionContext = (Objects.nonNull(nativeValue.encryptionContext()) && nativeValue.encryptionContext().size() > 0) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.EncryptionContext(nativeValue.encryptionContext()))
: Option.create_None();
Option<ICryptographicMaterialsManager> materialsManager;
materialsManager = Objects.nonNull(nativeValue.materialsManager()) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.CryptographicMaterialsManager(nativeValue.materialsManager()))
: Option.create_None();
Option<IKeyring> keyring;
keyring = Objects.nonNull(nativeValue.keyring()) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.Keyring(nativeValue.keyring()))
: Option.create_None();
Option<ESDKAlgorithmSuiteId> algorithmSuiteId;
algorithmSuiteId = Objects.nonNull(nativeValue.algorithmSuiteId()) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.ESDKAlgorithmSuiteId(nativeValue.algorithmSuiteId()))
: Option.create_None();
Option<Long> frameLength;
frameLength = Objects.nonNull(nativeValue.frameLength()) ?
Option.create_Some((nativeValue.frameLength()))
: Option.create_None();
return new EncryptInput(plaintext, encryptionContext, materialsManager, keyring, algorithmSuiteId, frameLength);
}
public static EncryptOutput EncryptOutput(
software.amazon.cryptography.encryptionsdk.model.EncryptOutput nativeValue) {
DafnySequence<? extends Byte> ciphertext;
ciphertext = software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence(nativeValue.ciphertext());
DafnyMap<? extends DafnySequence<? extends Byte>, ? extends DafnySequence<? extends Byte>> encryptionContext;
encryptionContext = software.amazon.cryptography.materialproviders.ToDafny.EncryptionContext(nativeValue.encryptionContext());
ESDKAlgorithmSuiteId algorithmSuiteId;
algorithmSuiteId = software.amazon.cryptography.materialproviders.ToDafny.ESDKAlgorithmSuiteId(nativeValue.algorithmSuiteId());
return new EncryptOutput(ciphertext, encryptionContext, algorithmSuiteId);
}
public static Error Error(AwsEncryptionSdkException nativeValue) {
DafnySequence<? extends Character> message;
message = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.message());
return new Error_AwsEncryptionSdkException(message);
}
public static IAwsEncryptionSdkClient AwsEncryptionSdk(ESDK nativeValue) {
return nativeValue.impl();
}
}
| 5,417 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/model/DecryptInput.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk.model;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Objects;
import software.amazon.cryptography.materialproviders.CryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.ICryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.IKeyring;
import software.amazon.cryptography.materialproviders.Keyring;
public class DecryptInput {
private final ByteBuffer ciphertext;
private final ICryptographicMaterialsManager materialsManager;
private final IKeyring keyring;
private final Map<String, String> encryptionContext;
protected DecryptInput(BuilderImpl builder) {
this.ciphertext = builder.ciphertext();
this.materialsManager = builder.materialsManager();
this.keyring = builder.keyring();
this.encryptionContext = builder.encryptionContext();
}
public ByteBuffer ciphertext() {
return this.ciphertext;
}
public ICryptographicMaterialsManager materialsManager() {
return this.materialsManager;
}
public IKeyring keyring() {
return this.keyring;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder ciphertext(ByteBuffer ciphertext);
ByteBuffer ciphertext();
Builder materialsManager(ICryptographicMaterialsManager materialsManager);
ICryptographicMaterialsManager materialsManager();
Builder keyring(IKeyring keyring);
IKeyring keyring();
Builder encryptionContext(Map<String, String> encryptionContext);
Map<String, String> encryptionContext();
DecryptInput build();
}
static class BuilderImpl implements Builder {
protected ByteBuffer ciphertext;
protected ICryptographicMaterialsManager materialsManager;
protected IKeyring keyring;
protected Map<String, String> encryptionContext;
protected BuilderImpl() {
}
protected BuilderImpl(DecryptInput model) {
this.ciphertext = model.ciphertext();
this.materialsManager = model.materialsManager();
this.keyring = model.keyring();
this.encryptionContext = model.encryptionContext();
}
public Builder ciphertext(ByteBuffer ciphertext) {
this.ciphertext = ciphertext;
return this;
}
public ByteBuffer ciphertext() {
return this.ciphertext;
}
public Builder materialsManager(ICryptographicMaterialsManager materialsManager) {
this.materialsManager = CryptographicMaterialsManager.wrap(materialsManager);
return this;
}
public ICryptographicMaterialsManager materialsManager() {
return this.materialsManager;
}
public Builder keyring(IKeyring keyring) {
this.keyring = Keyring.wrap(keyring);
return this;
}
public IKeyring keyring() {
return this.keyring;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
this.encryptionContext = encryptionContext;
return this;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public DecryptInput build() {
if (Objects.isNull(this.ciphertext())) {
throw new IllegalArgumentException("Missing value for required field `ciphertext`");
}
return new DecryptInput(this);
}
}
}
| 5,418 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/model/AwsEncryptionSdkConfig.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk.model;
import software.amazon.cryptography.materialproviders.model.ESDKCommitmentPolicy;
public class AwsEncryptionSdkConfig {
private final ESDKCommitmentPolicy commitmentPolicy;
private final long maxEncryptedDataKeys;
protected AwsEncryptionSdkConfig(BuilderImpl builder) {
this.commitmentPolicy = builder.commitmentPolicy();
this.maxEncryptedDataKeys = builder.maxEncryptedDataKeys();
}
public ESDKCommitmentPolicy commitmentPolicy() {
return this.commitmentPolicy;
}
public long maxEncryptedDataKeys() {
return this.maxEncryptedDataKeys;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder commitmentPolicy(ESDKCommitmentPolicy commitmentPolicy);
ESDKCommitmentPolicy commitmentPolicy();
Builder maxEncryptedDataKeys(long maxEncryptedDataKeys);
long maxEncryptedDataKeys();
AwsEncryptionSdkConfig build();
}
static class BuilderImpl implements Builder {
protected ESDKCommitmentPolicy commitmentPolicy;
protected long maxEncryptedDataKeys;
private boolean _maxEncryptedDataKeysSet = false;
protected BuilderImpl() {
}
protected BuilderImpl(AwsEncryptionSdkConfig model) {
this.commitmentPolicy = model.commitmentPolicy();
this.maxEncryptedDataKeys = model.maxEncryptedDataKeys();
this._maxEncryptedDataKeysSet = true;
}
public Builder commitmentPolicy(ESDKCommitmentPolicy commitmentPolicy) {
this.commitmentPolicy = commitmentPolicy;
return this;
}
public ESDKCommitmentPolicy commitmentPolicy() {
return this.commitmentPolicy;
}
public Builder maxEncryptedDataKeys(long maxEncryptedDataKeys) {
this.maxEncryptedDataKeys = maxEncryptedDataKeys;
this._maxEncryptedDataKeysSet = true;
return this;
}
public long maxEncryptedDataKeys() {
return this.maxEncryptedDataKeys;
}
public AwsEncryptionSdkConfig build() {
if (this._maxEncryptedDataKeysSet && this.maxEncryptedDataKeys() < 1) {
throw new IllegalArgumentException("`maxEncryptedDataKeys` must be greater than or equal to 1");
}
return new AwsEncryptionSdkConfig(this);
}
}
}
| 5,419 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/model/EncryptInput.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk.model;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Objects;
import software.amazon.cryptography.materialproviders.CryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.ICryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.IKeyring;
import software.amazon.cryptography.materialproviders.Keyring;
import software.amazon.cryptography.materialproviders.model.ESDKAlgorithmSuiteId;
public class EncryptInput {
private final ByteBuffer plaintext;
private final Map<String, String> encryptionContext;
private final ICryptographicMaterialsManager materialsManager;
private final IKeyring keyring;
private final ESDKAlgorithmSuiteId algorithmSuiteId;
private final long frameLength;
protected EncryptInput(BuilderImpl builder) {
this.plaintext = builder.plaintext();
this.encryptionContext = builder.encryptionContext();
this.materialsManager = builder.materialsManager();
this.keyring = builder.keyring();
this.algorithmSuiteId = builder.algorithmSuiteId();
this.frameLength = builder.frameLength();
}
public ByteBuffer plaintext() {
return this.plaintext;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public ICryptographicMaterialsManager materialsManager() {
return this.materialsManager;
}
public IKeyring keyring() {
return this.keyring;
}
public ESDKAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public long frameLength() {
return this.frameLength;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder plaintext(ByteBuffer plaintext);
ByteBuffer plaintext();
Builder encryptionContext(Map<String, String> encryptionContext);
Map<String, String> encryptionContext();
Builder materialsManager(ICryptographicMaterialsManager materialsManager);
ICryptographicMaterialsManager materialsManager();
Builder keyring(IKeyring keyring);
IKeyring keyring();
Builder algorithmSuiteId(ESDKAlgorithmSuiteId algorithmSuiteId);
ESDKAlgorithmSuiteId algorithmSuiteId();
Builder frameLength(long frameLength);
long frameLength();
EncryptInput build();
}
static class BuilderImpl implements Builder {
protected ByteBuffer plaintext;
protected Map<String, String> encryptionContext;
protected ICryptographicMaterialsManager materialsManager;
protected IKeyring keyring;
protected ESDKAlgorithmSuiteId algorithmSuiteId;
protected long frameLength;
private boolean _frameLengthSet = false;
protected BuilderImpl() {
}
protected BuilderImpl(EncryptInput model) {
this.plaintext = model.plaintext();
this.encryptionContext = model.encryptionContext();
this.materialsManager = model.materialsManager();
this.keyring = model.keyring();
this.algorithmSuiteId = model.algorithmSuiteId();
this.frameLength = model.frameLength();
this._frameLengthSet = true;
}
public Builder plaintext(ByteBuffer plaintext) {
this.plaintext = plaintext;
return this;
}
public ByteBuffer plaintext() {
return this.plaintext;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
this.encryptionContext = encryptionContext;
return this;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public Builder materialsManager(ICryptographicMaterialsManager materialsManager) {
this.materialsManager = CryptographicMaterialsManager.wrap(materialsManager);
return this;
}
public ICryptographicMaterialsManager materialsManager() {
return this.materialsManager;
}
public Builder keyring(IKeyring keyring) {
this.keyring = Keyring.wrap(keyring);
return this;
}
public IKeyring keyring() {
return this.keyring;
}
public Builder algorithmSuiteId(ESDKAlgorithmSuiteId algorithmSuiteId) {
this.algorithmSuiteId = algorithmSuiteId;
return this;
}
public ESDKAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public Builder frameLength(long frameLength) {
this.frameLength = frameLength;
this._frameLengthSet = true;
return this;
}
public long frameLength() {
return this.frameLength;
}
public EncryptInput build() {
if (Objects.isNull(this.plaintext())) {
throw new IllegalArgumentException("Missing value for required field `plaintext`");
}
if (this._frameLengthSet && this.frameLength() < 1) {
throw new IllegalArgumentException("`frameLength` must be greater than or equal to 1");
}
if (this._frameLengthSet && this.frameLength() > 4294967296) {
throw new IllegalArgumentException("`frameLength` must be less than or equal to 4294967296.");
}
return new EncryptInput(this);
}
}
}
| 5,420 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/model/OpaqueError.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk.model;
public class OpaqueError extends RuntimeException {
/**
* The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed.
*/
private final Object obj;
protected OpaqueError(BuilderImpl builder) {
super(messageFromBuilder(builder), builder.cause());
this.obj = builder.obj();
}
private static String messageFromBuilder(Builder builder) {
if (builder.message() != null) {
return builder.message();
}
if (builder.cause() != null) {
return builder.cause().getMessage();
}
return null;
}
/**
* See {@link Throwable#getMessage()}.
*/
public String message() {
return this.getMessage();
}
/**
* See {@link Throwable#getCause()}.
*/
public Throwable cause() {
return this.getCause();
}
/**
* @return The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed.
*/
public Object obj() {
return this.obj;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
/**
* @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
Builder message(String message);
/**
* @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
String message();
/**
* @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Builder cause(Throwable cause);
/**
* @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Throwable cause();
/**
* @param obj The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed.
*/
Builder obj(Object obj);
/**
* @return The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed.
*/
Object obj();
OpaqueError build();
}
static class BuilderImpl implements Builder {
protected String message;
protected Throwable cause;
protected Object obj;
protected BuilderImpl() {
}
protected BuilderImpl(OpaqueError model) {
this.cause = model.getCause();
this.message = model.getMessage();
this.obj = model.obj();
}
public Builder message(String message) {
this.message = message;
return this;
}
public String message() {
return this.message;
}
public Builder cause(Throwable cause) {
this.cause = cause;
return this;
}
public Throwable cause() {
return this.cause;
}
public Builder obj(Object obj) {
this.obj = obj;
return this;
}
public Object obj() {
return this.obj;
}
public OpaqueError build() {
if (this.obj != null && this.cause == null && this.obj instanceof Throwable) {
this.cause = (Throwable) this.obj;
} else if (this.obj == null && this.cause != null) {
this.obj = this.cause;
}
return new OpaqueError(this);
}
}
}
| 5,421 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/model/EncryptOutput.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk.model;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Objects;
import software.amazon.cryptography.materialproviders.model.ESDKAlgorithmSuiteId;
public class EncryptOutput {
private final ByteBuffer ciphertext;
private final Map<String, String> encryptionContext;
private final ESDKAlgorithmSuiteId algorithmSuiteId;
protected EncryptOutput(BuilderImpl builder) {
this.ciphertext = builder.ciphertext();
this.encryptionContext = builder.encryptionContext();
this.algorithmSuiteId = builder.algorithmSuiteId();
}
public ByteBuffer ciphertext() {
return this.ciphertext;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public ESDKAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder ciphertext(ByteBuffer ciphertext);
ByteBuffer ciphertext();
Builder encryptionContext(Map<String, String> encryptionContext);
Map<String, String> encryptionContext();
Builder algorithmSuiteId(ESDKAlgorithmSuiteId algorithmSuiteId);
ESDKAlgorithmSuiteId algorithmSuiteId();
EncryptOutput build();
}
static class BuilderImpl implements Builder {
protected ByteBuffer ciphertext;
protected Map<String, String> encryptionContext;
protected ESDKAlgorithmSuiteId algorithmSuiteId;
protected BuilderImpl() {
}
protected BuilderImpl(EncryptOutput model) {
this.ciphertext = model.ciphertext();
this.encryptionContext = model.encryptionContext();
this.algorithmSuiteId = model.algorithmSuiteId();
}
public Builder ciphertext(ByteBuffer ciphertext) {
this.ciphertext = ciphertext;
return this;
}
public ByteBuffer ciphertext() {
return this.ciphertext;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
this.encryptionContext = encryptionContext;
return this;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public Builder algorithmSuiteId(ESDKAlgorithmSuiteId algorithmSuiteId) {
this.algorithmSuiteId = algorithmSuiteId;
return this;
}
public ESDKAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public EncryptOutput build() {
if (Objects.isNull(this.ciphertext())) {
throw new IllegalArgumentException("Missing value for required field `ciphertext`");
}
if (Objects.isNull(this.encryptionContext())) {
throw new IllegalArgumentException("Missing value for required field `encryptionContext`");
}
if (Objects.isNull(this.algorithmSuiteId())) {
throw new IllegalArgumentException("Missing value for required field `algorithmSuiteId`");
}
return new EncryptOutput(this);
}
}
}
| 5,422 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/model/DecryptOutput.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk.model;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Objects;
import software.amazon.cryptography.materialproviders.model.ESDKAlgorithmSuiteId;
public class DecryptOutput {
private final ByteBuffer plaintext;
private final Map<String, String> encryptionContext;
private final ESDKAlgorithmSuiteId algorithmSuiteId;
protected DecryptOutput(BuilderImpl builder) {
this.plaintext = builder.plaintext();
this.encryptionContext = builder.encryptionContext();
this.algorithmSuiteId = builder.algorithmSuiteId();
}
public ByteBuffer plaintext() {
return this.plaintext;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public ESDKAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder plaintext(ByteBuffer plaintext);
ByteBuffer plaintext();
Builder encryptionContext(Map<String, String> encryptionContext);
Map<String, String> encryptionContext();
Builder algorithmSuiteId(ESDKAlgorithmSuiteId algorithmSuiteId);
ESDKAlgorithmSuiteId algorithmSuiteId();
DecryptOutput build();
}
static class BuilderImpl implements Builder {
protected ByteBuffer plaintext;
protected Map<String, String> encryptionContext;
protected ESDKAlgorithmSuiteId algorithmSuiteId;
protected BuilderImpl() {
}
protected BuilderImpl(DecryptOutput model) {
this.plaintext = model.plaintext();
this.encryptionContext = model.encryptionContext();
this.algorithmSuiteId = model.algorithmSuiteId();
}
public Builder plaintext(ByteBuffer plaintext) {
this.plaintext = plaintext;
return this;
}
public ByteBuffer plaintext() {
return this.plaintext;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
this.encryptionContext = encryptionContext;
return this;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public Builder algorithmSuiteId(ESDKAlgorithmSuiteId algorithmSuiteId) {
this.algorithmSuiteId = algorithmSuiteId;
return this;
}
public ESDKAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public DecryptOutput build() {
if (Objects.isNull(this.plaintext())) {
throw new IllegalArgumentException("Missing value for required field `plaintext`");
}
if (Objects.isNull(this.encryptionContext())) {
throw new IllegalArgumentException("Missing value for required field `encryptionContext`");
}
if (Objects.isNull(this.algorithmSuiteId())) {
throw new IllegalArgumentException("Missing value for required field `algorithmSuiteId`");
}
return new DecryptOutput(this);
}
}
}
| 5,423 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/model/AwsEncryptionSdkException.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk.model;
import java.util.Objects;
public class AwsEncryptionSdkException extends RuntimeException {
protected AwsEncryptionSdkException(BuilderImpl builder) {
super(messageFromBuilder(builder), builder.cause());
}
private static String messageFromBuilder(Builder builder) {
if (builder.message() != null) {
return builder.message();
}
if (builder.cause() != null) {
return builder.cause().getMessage();
}
return null;
}
/**
* See {@link Throwable#getMessage()}.
*/
public String message() {
return this.getMessage();
}
/**
* See {@link Throwable#getCause()}.
*/
public Throwable cause() {
return this.getCause();
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
/**
* @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
Builder message(String message);
/**
* @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
String message();
/**
* @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Builder cause(Throwable cause);
/**
* @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Throwable cause();
AwsEncryptionSdkException build();
}
static class BuilderImpl implements Builder {
protected String message;
protected Throwable cause;
protected BuilderImpl() {
}
protected BuilderImpl(AwsEncryptionSdkException model) {
this.message = model.message();
this.cause = model.cause();
}
public Builder message(String message) {
this.message = message;
return this;
}
public String message() {
return this.message;
}
public Builder cause(Throwable cause) {
this.cause = cause;
return this;
}
public Throwable cause() {
return this.cause;
}
public AwsEncryptionSdkException build() {
if (Objects.isNull(this.message())) {
throw new IllegalArgumentException("Missing value for required field `message`");
}
return new AwsEncryptionSdkException(this);
}
}
}
| 5,424 |
0 | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk | Create_ds/aws-encryption-sdk-dafny/AwsEncryptionSDK/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/encryptionsdk/model/CollectionOfErrors.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.encryptionsdk.model;
import java.util.List;
public class CollectionOfErrors extends RuntimeException {
/**
* The list of Exceptions encountered.
*/
private final List<RuntimeException> list;
protected CollectionOfErrors(BuilderImpl builder) {
super(messageFromBuilder(builder), builder.cause());
this.list = builder.list();
}
private static String messageFromBuilder(Builder builder) {
if (builder.message() != null) {
return builder.message();
}
if (builder.cause() != null) {
return builder.cause().getMessage();
}
return null;
}
/**
* See {@link Throwable#getMessage()}.
*/
public String message() {
return this.getMessage();
}
/**
* See {@link Throwable#getCause()}.
*/
public Throwable cause() {
return this.getCause();
}
/**
* @return The list of Exceptions encountered.
*/
public List<RuntimeException> list() {
return this.list;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
/**
* @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
Builder message(String message);
/**
* @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
String message();
/**
* @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Builder cause(Throwable cause);
/**
* @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Throwable cause();
/**
* @param list The list of Exceptions encountered.
*/
Builder list(List<RuntimeException> list);
/**
* @return The list of Exceptions encountered.
*/
List<RuntimeException> list();
CollectionOfErrors build();
}
static class BuilderImpl implements Builder {
protected String message;
protected Throwable cause;
protected List<RuntimeException> list;
protected BuilderImpl() {
}
protected BuilderImpl(CollectionOfErrors model) {
this.cause = model.getCause();
this.message = model.getMessage();
this.list = model.list();
}
public Builder message(String message) {
this.message = message;
return this;
}
public String message() {
return this.message;
}
public Builder cause(Throwable cause) {
this.cause = cause;
return this;
}
public Throwable cause() {
return this.cause;
}
public Builder list(List<RuntimeException> list) {
this.list = list;
return this;
}
public List<RuntimeException> list() {
return this.list;
}
public CollectionOfErrors build() {
return new CollectionOfErrors(this);
}
}
}
| 5,425 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/ConfigurationVariable.java | package com.netflix.governator.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Documented
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface ConfigurationVariable {
String name();
}
| 5,426 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/NonConcurrent.java | package com.netflix.governator.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Used to indicate that a constructor argument cannot be constructed concurrently.
* Use this in conjunction with {@link ConcurrentProviders.of()} when instantiating
* an injected dependency in parallel results in the guice @Singleton scope deadlock.
*
* @see {@link ConcurrentProviders}
* @author elandau
*/
@Documented
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface NonConcurrent {
}
| 5,427 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/SuppressLifecycleUninitialized.java | package com.netflix.governator.annotations;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Documented
@Retention(RUNTIME)
@Target(TYPE)
public @interface SuppressLifecycleUninitialized {
}
| 5,428 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/WarmUp.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* @deprecated 2016-05-19 This class is being deprecated in favor of using {@literal @}PostConstruct
* or running initialization code in the constructor. While {@literal @}WarmUp did promise to help
* with parallel initialization of singletons it resulted in excessive complexity and invalidated DI
* expectations that a class is fully initialized by the time it is injected. WarmUp methods are
* now treated exactly like PostConstruct and are therefore guaranteed to have been executed by the
* time an object is injected.
*/
@Documented
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Deprecated
public @interface WarmUp
{
}
| 5,429 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/Configuration.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Marks a field as a configuration item. Governator will auto-assign the value based
* on the {@link #value()} of the annotation via the set com.netflix.governator.configurationConfigurationProvider.
*/
@Documented
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface Configuration
{
/**
* @return name/key of the config to assign
*/
String value();
/**
* @return user displayable description of this configuration
*/
String documentation() default "";
/**
* If the value of the property defined for this config is not the same or can not be converted to the
* required type, setting this to <code>true</code> will ignore such a value. In such a case, the target field
* will contain the default value if defined.<br/>
* The error during configuration is deemed as a type mismatch if the exception thrown by the
* com.netflix.governator.configurationConfigurationProvider is one amongst:
* <ul>
* <li>{@link IllegalArgumentException}</li>
* <li>org.apache.commons.configuration.ConversionException</li>
</ul>
*
* @return <code>true</code> if type mismatch must be ignored. <code>false</code> otherwise. Default value is
* <code>false</code>
*/
boolean ignoreTypeMismatch() default false;
}
| 5,430 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/PreConfiguration.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Marks a method as a pre-configuration method. Governator will execute pre-configuration methods
* prior to configuration assignment
*/
@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface PreConfiguration
{
}
| 5,431 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/AutoBind.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations;
import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation binding that combines with Governator's classpath scanning and a bound
* AutoBindProvider to automatically/programmatically bind fields and constructor/method
* arguments
*
* @deprecated 2015-10-10 Deprecated in favor of standard Guice modules.
* See https://github.com/Netflix/governator/wiki/Auto-Binding
*/
@Documented
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
@Qualifier
@Deprecated
public @interface AutoBind
{
/**
* @return optional binding argument
*/
String value() default "";
}
| 5,432 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/AutoBindSingleton.java | /*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Marks a class as a singleton. Governator will auto-bind it as an eager singleton
* @deprecated 2015-10-10 AutoBindSingleton is deprecated in favor of bindings in a Guice Module.
* See https://github.com/Netflix/governator/wiki/Auto-Binding
*/
@Documented
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(java.lang.annotation.ElementType.TYPE)
@Deprecated
public @interface AutoBindSingleton
{
/**
* By default, AutoBindSingleton binds to the class that has the annotation. However,
* you can set the value to any base class/interface that you want to bind to. You can
* bind to generic base classes/interfaces by specifying the raw type (i.e. <code>@AutoBindSingleton(List.class)</code>
* for <code>List<String></code>)
*
* @return base class/interface to bind to
*/
Class<?> value() default Void.class;
/**
* This is a synonym for {@link #value()}. It exists to make the annotation
* more legible if other annotation values are used. NOTE: it is an error to
* specify both {@link #value()} and {@link #baseClass()}
*
* @return base class/interface to bind to
*/
Class<?> baseClass() default Void.class;
/**
* If true, instances are gathered into a Set using Guice's Multibinder. You must
* also set a base class using either {@link #value()} or {@link #baseClass()}
*
* @return true/false
*/
boolean multiple() default false;
/**
* If true, instances will be created eagerly.
* @return
*/
boolean eager() default true;
}
| 5,433 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Message.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Message
{
}
| 5,434 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Size.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Size
{
}
| 5,435 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Status.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Status
{
}
| 5,436 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Region.java | package com.netflix.governator.annotations.binding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* A generic binding annotation normally used to bind the region id.
* For AWS Region can be 'us-east', 'us-west-2', etc.
*/
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Region {
}
| 5,437 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Response.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Response
{
}
| 5,438 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/DataCenter.java | package com.netflix.governator.annotations.binding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* A generic binding annotation normally used to bind the DataCenter name.
*
* Internally at Netflix Datacenter is set to 'cloud' for amazon and 'dc' for a
* traditional datacenter.
*/
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataCenter {
}
| 5,439 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Mode.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Mode
{
}
| 5,440 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Context.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Context
{
}
| 5,441 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/IO.java | package com.netflix.governator.annotations.binding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation that can be used to specify that something
* is tied to IO processing. For example,
*
* bind(ExecutorService.class).annotatedWith(IO.class).toInstance(Executors.newScheduledThreadPool(10));
*
*/
public @interface IO
{
}
| 5,442 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Option.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Option
{
}
| 5,443 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Secondary.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Secondary
{
}
| 5,444 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Computation.java | package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation that can be used to specify that something
* is tied to computation related tasks.
*
* bind(ExecutorService.class).annotatedWith(Computation.class).toInstance(Executors.newCachedThreadPool(10));
*/
public @interface Computation {
}
| 5,445 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Rack.java | package com.netflix.governator.annotations.binding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* A generic binding annotation normally used to bind the rack id.
* For AWS Rack should be used to bind the Zone name.
*/
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Rack {
}
| 5,446 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Profiles.java | package com.netflix.governator.annotations.binding;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* Qualifier associated with Set{@literal <}String{@literal >} of active profiles
*/
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Qualifier
public @interface Profiles {
}
| 5,447 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Style.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Style
{
}
| 5,448 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Output.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Output
{
}
| 5,449 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Primary.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Primary
{
}
| 5,450 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Minor.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Minor
{
}
| 5,451 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Main.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Main
{
}
| 5,452 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Input.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Input
{
}
| 5,453 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/UpStatus.java | package com.netflix.governator.annotations.binding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* A generic binding annotation that can be associated with the up status
* of an application.
*
* <pre>
* bind(Boolean.class).annotatedWith(UpStatus.class).toInstance(new AtomicBoolean(true));
* bind(new TypeLiteral<Supplier<Boolean>() {}>).annotatedWith(UpStatus.class).toInstance(new SomeSupplierThatTellsYouTheUpStatus());
*
* public class Foo() {
* @Inject
* public Foo(@UpStatus Supplier<Boolean> isUp) {
* System.out.println("Application isUp: " + isUp);
* }
* }
* </pre>
*
* If you're using RxJava you can set up an Observable of up status
* <pre>
* bind(new TypeLiteral<Observable<Boolean>>() {}>).annotatedWith(UpStatus.class).toInstance(new SomethingThatEmitsChangesInUpStatus());
*
* public class Foo() {
* @Inject
* public Foo(@UpStatus Observable<Boolean> upStatus) {
* upStatus.subscribe(new Action1<Boolean>() {
* public void call(Boolean status) {
* System.out.println("Status is now up");
* }
* });
* }
* }
*
* @see DownStatus
* </pre>
*/
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UpStatus
{
}
| 5,454 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/DownStatus.java | package com.netflix.governator.annotations.binding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* Generic annotation that is equivalent to !{@link UpStatus}.
*
* @author elandau
*/
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DownStatus {
}
| 5,455 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Background.java | package com.netflix.governator.annotations.binding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation that can be used to specify that something
* is tied to background processing. For example,
*
* bind(ExecutorService.class).annotatedWith(Background.class).toInstance(Executors.newScheduledThreadPool(10));
*
*/
public @interface Background
{
}
| 5,456 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/State.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface State
{
}
| 5,457 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Major.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Major
{
}
| 5,458 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Subsidiary.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Subsidiary
{
}
| 5,459 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Arguments.java | package com.netflix.governator.annotations.binding;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* Qualifier associated with String[] arguments passed to Karyon.start(args)
*/
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Qualifier
public @interface Arguments {
}
| 5,460 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Color.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Color
{
}
| 5,461 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/annotations/binding/Request.java | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.annotations.binding;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
/**
* A generic binding annotation
*/
public @interface Request
{
}
| 5,462 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/spi/LifecycleListener.java | package com.netflix.governator.spi;
/**
* Listener for Injector lifecycle events.
*
* When writing a LifecycleListener that is managed by Guice, make sure to
* inject all dependencies lazily using {@link Provider} injection. Otherwise,
* these dependencies will be instantiated too early thereby bypassing lifecycle
* features in LifecycleModule.
*/
public interface LifecycleListener {
/**
* Notification that the Injector has been created.
*/
void onStarted();
/**
* Notification that the Injector is shutting down
*/
void onStopped(Throwable error);
}
| 5,463 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/event/ApplicationEventRegistration.java | package com.netflix.governator.event;
/**
* Interface to unregistering a subscriber to events. Returned from {@link ApplicationEventDispatcher}
* whenever a received is programmatically registered.
*/
public interface ApplicationEventRegistration {
void unregister();
}
| 5,464 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/event/EventListener.java | package com.netflix.governator.event;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
/**
* Marks a method as an {@link ApplicationEvent} subscriber.
*
* Subscriber methods should be public, void, and accept only one argument implementing {@link ApplicationEvent}
*
* <code>
* public class MyService {
*
* {@literal @}EventListener
* public void onEvent(MyCustomEvent event) {
*
* }
*
* }
* </code>
*
*/
public @interface EventListener {
}
| 5,465 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/event/ApplicationEvent.java | package com.netflix.governator.event;
/**
* Marker interface for application events to be published
* to subscribed consumers. See {@link ApplicationEventDispatcher} and {@link EventListener}
* for examples of publishing and subscribing to events.
*/
public interface ApplicationEvent {
}
| 5,466 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/event/ApplicationEventDispatcher.java | package com.netflix.governator.event;
import java.lang.reflect.Method;
/**
* Interface for publishing {@link ApplicationEvent}s as well as programmatically registering
* {@link ApplicationEventListener}s.
*/
public interface ApplicationEventDispatcher {
<T extends ApplicationEvent> ApplicationEventRegistration registerListener(Class<T> eventType, ApplicationEventListener<T> eventListener);
ApplicationEventRegistration registerListener(ApplicationEventListener<? extends ApplicationEvent> eventListener);
ApplicationEventRegistration registerListener(Object instance, Method method, Class<? extends ApplicationEvent> acceptedType);
void publishEvent(ApplicationEvent event);
}
| 5,467 |
0 | Create_ds/governator/governator-api/src/main/java/com/netflix/governator | Create_ds/governator/governator-api/src/main/java/com/netflix/governator/event/ApplicationEventListener.java | package com.netflix.governator.event;
/***
* Interface for receiving to events of a given type. Can be registered explicitly
* via {@link ApplicationEventDispatcher#registerListener(ApplicationEventListener)}
* or implicitly in Guice by detecting by all bindings for instances of {@link ApplicationEvent}
* */
public interface ApplicationEventListener<T extends ApplicationEvent> {
public void onEvent(T event);
}
| 5,468 |
0 | Create_ds/governator/governator-test-junit/src/test/java/com/netflix/governator/guice/test | Create_ds/governator/governator-test-junit/src/test/java/com/netflix/governator/guice/test/junit4/GovernatorJunit4ClassRunnerTest.java | package com.netflix.governator.guice.test.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import javax.inject.Inject;
import javax.inject.Named;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import org.mockito.internal.util.MockUtil;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.name.Names;
import com.netflix.governator.guice.test.ModulesForTesting;
import com.netflix.governator.guice.test.ReplaceWithMock;
import com.netflix.governator.guice.test.WrapWithSpy;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(GovernatorJunit4ClassRunner.class)
@ModulesForTesting({ TestInjectorRuleTestModule.class })
public class GovernatorJunit4ClassRunnerTest {
MockUtil mockUtil = new MockUtil();
@Inject
@Named("testString")
String testString;
@Inject @ReplaceWithMock ToBeMocked toBeMocked;
@Inject @ReplaceWithMock NewBindingToBeMocked newBindingToBeMocked;
@Named("namedMock")
@Inject @ReplaceWithMock(name="namedMock") NamedMock namedMock;
@Inject InvokesMock invokesMock;
@Inject @WrapWithSpy Spied spied;
@Inject @WrapWithSpy(name="namedSpied") Spied namedSpied;
@Inject @Named("notSpied") Spied notSpied;
@Inject InvokesSpy invokesSpy;
@Test
public void basicInjectionTest() {
assertNotNull(testString);
assertEquals("Test", testString);
}
@Test
public void testAddingMockAsNewBinding() {
assertNotNull(newBindingToBeMocked);
assertTrue(mockUtil.isMock(newBindingToBeMocked));
}
@Test
public void testMockingOverridesBinding() {
assertNotNull(invokesMock);
assertNotNull(toBeMocked);
assertNotNull(invokesMock.mocked);
assertTrue(mockUtil.isMock(toBeMocked));
}
@Test
public void testMockingNamedBindings() {
assertNotNull(namedMock);
assertTrue(mockUtil.isMock(namedMock));
}
@Test
public void za_testMocksCleanUpAfterTestsPartOne() {
assertNotNull(toBeMocked);
toBeMocked.invoke();
Mockito.verify(toBeMocked, Mockito.times(1)).invoke();
}
@Test
public void zz_testMocksCleanUpAfterTestsPartTwo() {
assertNotNull(toBeMocked);
Mockito.verifyZeroInteractions(toBeMocked);
}
@Test
public void testWrapWithSpy() {
assertNotNull(spied);
assertNotNull(invokesSpy);
assertTrue(mockUtil.isSpy(spied));
assertTrue(mockUtil.isSpy(namedSpied));
assertFalse(mockUtil.isSpy(notSpied));
assertTrue(mockUtil.isSpy(invokesSpy.spied));
invokesSpy.invoke();
assertSame(spied,invokesSpy.spied);
Mockito.verify(spied, Mockito.times(1)).invoke();
}
}
class TestInjectorRuleTestModule extends AbstractModule {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("testString")).toInstance("Test");
bind(ToBeMocked.class);
bind(InvokesMock.class);
bind(NamedMock.class).annotatedWith(Names.named("namedMock"));
bind(InvokesSpy.class);
}
@Provides
@Singleton
public Spied spied() {
return new Spied();
}
@Provides
@Singleton
@Named("namedSpied")
public Spied namedSpied() {
return new Spied();
}
@Provides
@Singleton
@Named("notSpied")
public Spied notSpied() {
return new Spied();
}
}
class ToBeMocked {
public void invoke() {}
}
class NewBindingToBeMocked {}
class NamedMock {}
@Singleton
class InvokesMock {
@Inject ToBeMocked mocked;
}
@Singleton
class Spied {
public void invoke() {};
}
@Singleton
class InvokesSpy {
@Inject Spied spied;
public void invoke() {
spied.invoke();
}
}
| 5,469 |
0 | Create_ds/governator/governator-test-junit/src/test/java/com/netflix/governator/guice/test | Create_ds/governator/governator-test-junit/src/test/java/com/netflix/governator/guice/test/junit4/GovernatorJunit4ClassRunnerArchaius2IntegrationTest.java | package com.netflix.governator.guice.test.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.archaius.api.Config;
import com.netflix.archaius.guice.ArchaiusModule;
import com.netflix.archaius.test.TestCompositeConfig;
import com.netflix.archaius.test.TestPropertyOverride;
import com.netflix.governator.guice.test.ModulesForTesting;
@RunWith(GovernatorJunit4ClassRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ModulesForTesting({GovernatorJunit4ClassRunnerArchaius2IntegrationTestModule.class, ArchaiusModule.class})
@TestPropertyOverride("foo=bar")
public class GovernatorJunit4ClassRunnerArchaius2IntegrationTest {
@Inject
Config config;
@Inject
@Named("foo")
String earlyInitString;
@Test
public void testConfigWiring() {
assertNotNull(config);
assertTrue(config instanceof TestCompositeConfig);
}
@Test
public void testClassLevelConfig() {
assertEquals("bar", config.getString("foo"));
assertEquals("bar", earlyInitString);
}
@Test
@TestPropertyOverride("foo=baz")
public void testMethodLevelConfigOverridesClassLevelConfig() {
assertEquals("baz", config.getString("foo"));
assertEquals("bar", earlyInitString);
}
@Test
public void zz_testMethodLevelConfigClearedBetweenTests() {
assertEquals("bar", config.getString("foo"));
assertEquals("bar", earlyInitString);
}
}
class GovernatorJunit4ClassRunnerArchaius2IntegrationTestModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton
@Named("foo")
public String earlyInitString(Config config) {
return config.getString("foo");
}
} | 5,470 |
0 | Create_ds/governator/governator-test-junit/src/test/java/com/netflix/governator/guice/test | Create_ds/governator/governator-test-junit/src/test/java/com/netflix/governator/guice/test/junit4/GovernatorJunit4ClassRunnerCreationModeTest.java | package com.netflix.governator.guice.test.junit4;
import static org.junit.Assert.*;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import com.netflix.governator.guice.test.ModulesForTesting;
import com.netflix.governator.guice.test.InjectorCreationMode;
@RunWith(Enclosed.class)
public class GovernatorJunit4ClassRunnerCreationModeTest {
@RunWith(GovernatorJunit4ClassRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ModulesForTesting()
public static class ClassLevelTest {
@Inject
StatefulTestBinding stateful;
@Test
public void test1() {
assertEquals(null, stateful.getState());
stateful.setState("foo");
}
@Test
public void test2() {
assertEquals("foo", stateful.getState());
stateful.setState("foo");
}
}
@RunWith(GovernatorJunit4ClassRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ModulesForTesting(injectorCreation=InjectorCreationMode.BEFORE_EACH_TEST_METHOD)
public static class MethodLevelTest {
@Inject
StatefulTestBinding stateful;
@Test
public void test1() {
assertNull(stateful.getState());
stateful.setState("foo");
}
@Test
public void test2() {
assertNull(stateful.getState());
}
}
}
@Singleton
class StatefulTestBinding {
private String state;
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
}
| 5,471 |
0 | Create_ds/governator/governator-test-junit/src/main/java/com/netflix/governator | Create_ds/governator/governator-test-junit/src/main/java/com/netflix/governator/guice/LifecycleTester.java | package com.netflix.governator.guice;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.rules.ExternalResource;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import com.netflix.governator.lifecycle.LifecycleManager;
/**
* Rule for testing with governator. The rule provides the following conveniences
* 1. Mechanism to customize the configuration via external modules.
* 2. Auto shutdown the lifecycle manager when a test ends
* 3. Methods to test whether certain bindings were heard and injected
*
* Usage
*
* <pre>
* public class MyUnitTest {
* @Rule
* public LifecycleTester tester = new LifecycleTester(new MyTestSuite());
*
* @Test
* public void test() {
* // Test specific setup
* tester.builder().
* withAdditionalModule(new TheModuleImTesting());
*
* // Creates the injector and start LifecycleManager
* tester.start();
*
* // Your test code goes here
*
* } // On termination the LifecycleTester will shutdown LifecycleManager
* }
*
* </pre>
*
* public static class
* @author elandau
*/
public class LifecycleTester extends ExternalResource {
private BootstrapModule[] suites;
private Injector injector;
private Class<?> bootstrap;
private LifecycleInjectorBuilder builder;
private Module externalModule;
public LifecycleTester(List<BootstrapModule> suites) {
this.suites = suites.toArray(new BootstrapModule[suites.size()]);
}
public LifecycleTester(BootstrapModule ... suites) {
this.suites = suites;
}
public LifecycleTester(Class bootstrap, BootstrapModule ... suites) {
this.bootstrap = bootstrap;
this.suites = suites;
}
/**
*
* @return the new Injector
*/
public Injector start() {
if (bootstrap != null) {
injector = LifecycleInjector.bootstrap(bootstrap, externalModule, suites);
}
else {
builder = LifecycleInjector.builder();
injector = builder.build().createInjector();
}
LifecycleManager manager = injector.getInstance(LifecycleManager.class);
try {
manager.start();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
return injector;
}
public LifecycleTester withBootstrapModule(BootstrapModule bootstrapModule) {
if (this.suites == null || this.suites.length == 0) {
this.suites = new BootstrapModule[] { bootstrapModule };
}
else {
this.suites = Arrays.copyOf(this.suites, this.suites.length + 1);
this.suites[this.suites.length-1] = bootstrapModule;
}
return this;
}
public LifecycleTester withExternalBindings(Module module) {
this.externalModule = module;
return this;
}
public LifecycleInjectorBuilder builder() {
return builder;
}
public <T> T getInstance(Class<T> type) {
return injector.getInstance(type);
}
public <T> T getInstance(Key<T> type) {
return injector.getInstance(type);
}
public <T> T getInstance(TypeLiteral<T> type) {
return injector.getInstance(Key.get(type));
}
/**
* Override to tear down your specific external resource.
*/
protected void after() {
if (injector != null) {
LifecycleManager manager = injector.getInstance(LifecycleManager.class);
try {
manager.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
}
}
| 5,472 |
0 | Create_ds/governator/governator-test-junit/src/main/java/com/netflix/governator/guice/test | Create_ds/governator/governator-test-junit/src/main/java/com/netflix/governator/guice/test/junit4/GovernatorJunit4ClassRunner.java | package com.netflix.governator.guice.test.junit4;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.internal.runners.statements.RunAfters;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import com.netflix.governator.guice.test.AnnotationBasedTestInjectorManager;
import com.netflix.governator.guice.test.ModulesForTesting;
import com.netflix.governator.guice.test.ReplaceWithMock;
import com.netflix.governator.guice.test.InjectorCreationMode;
import com.netflix.governator.guice.test.WrapWithSpy;
import com.netflix.governator.guice.test.mocks.mockito.MockitoMockHandler;
/**
* An extended {@link BlockJUnit4ClassRunner} which creates a Governator-Guice
* injector from a list of modules, as well as provides utilities for
* Mocking/Spying bindings.
*
* See {@link ModulesForTesting}, {@link ReplaceWithMock}, and
* {@link WrapWithSpy} for example usage.
*/
public class GovernatorJunit4ClassRunner extends BlockJUnit4ClassRunner {
private AnnotationBasedTestInjectorManager annotationBasedTestInjectorManager;
public GovernatorJunit4ClassRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
protected Statement classBlock(RunNotifier notifier) {
annotationBasedTestInjectorManager = new AnnotationBasedTestInjectorManager(getTestClass().getJavaClass(), MockitoMockHandler.class);
annotationBasedTestInjectorManager.prepareConfigForTestClass(getDescription().getTestClass());
if (InjectorCreationMode.BEFORE_TEST_CLASS == annotationBasedTestInjectorManager.getInjectorCreationMode()) {
annotationBasedTestInjectorManager.createInjector();
}
return super.classBlock(notifier);
}
@Override
protected Object createTest() throws Exception {
final Object testInstance = super.createTest();
annotationBasedTestInjectorManager.prepareTestFixture(testInstance);
return testInstance;
}
@Override
protected Statement methodBlock(FrameworkMethod method) {
annotationBasedTestInjectorManager.prepareConfigForTestClass(getDescription().getTestClass(), method.getMethod());
if (InjectorCreationMode.BEFORE_EACH_TEST_METHOD == annotationBasedTestInjectorManager.getInjectorCreationMode()) {
annotationBasedTestInjectorManager.createInjector();
}
return super.methodBlock(method);
}
@Override
protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) {
final List<FrameworkMethod> afters = getTestClass().getAnnotatedMethods(After.class);
return new RunAfters(statement, afters, target) {
@Override
public void evaluate() throws Throwable {
try {
super.evaluate();
} finally {
annotationBasedTestInjectorManager.cleanUpMethodLevelConfig();
annotationBasedTestInjectorManager.cleanUpMocks();
if (InjectorCreationMode.BEFORE_EACH_TEST_METHOD == annotationBasedTestInjectorManager
.getInjectorCreationMode()) {
annotationBasedTestInjectorManager.cleanUpInjector();
}
}
}
};
}
@Override
protected Statement withAfterClasses(Statement statement) {
final List<FrameworkMethod> afters = getTestClass().getAnnotatedMethods(AfterClass.class);
return new RunAfters(statement, afters, null) {
@Override
public void evaluate() throws Throwable {
try {
super.evaluate();
} finally {
annotationBasedTestInjectorManager.cleanUpInjector();
}
}
};
}
} | 5,473 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/JettyServerTest.java | package com.netflix.governator.guice.jetty;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.util.Modules;
import com.netflix.governator.InjectorBuilder;
import com.netflix.governator.LifecycleInjector;
import com.netflix.governator.ShutdownHookModule;
import com.netflix.governator.guice.jetty.resources1.SampleResource;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.junit.Assert;
import org.junit.Test;
import javax.annotation.PreDestroy;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
public class JettyServerTest {
static class Foo {
private boolean shutdownCalled;
@PreDestroy
void shutdown() {
shutdownCalled = true;
}
};
@Test
public void confirmShutdownSequence() throws InterruptedException, MalformedURLException, IOException {
// Create the injector and autostart Jetty
LifecycleInjector injector = InjectorBuilder.fromModules(
new SampleServletModule(),
new ShutdownHookModule(),
Modules.override(new JettyModule())
.with(new AbstractModule() {
@Override
protected void configure() {
bind(Foo.class).asEagerSingleton();
}
@Provides
JettyConfig getConfig() {
// Use emphemeral ports
return new DefaultJettyConfig().setPort(0);
}
}))
.createInjector();
Foo foo = injector.getInstance(Foo.class);
// Determine the emphermal port from jetty
Server server = injector.getInstance(Server.class);
int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
SampleResource resource = injector.getInstance(SampleResource.class);
Assert.assertEquals(1, resource.getPostConstructCount());
Assert.assertEquals(0, resource.getPreDestroyCount());
System.out.println("Listening on port : "+ port);
URL url = new URL(String.format("http://localhost:%d/kill", port));
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
try {
conn.getResponseCode();
}
catch (Exception e) {
}
injector.awaitTermination();
Assert.assertTrue(foo.shutdownCalled);
Assert.assertEquals(1, resource.getPostConstructCount());
Assert.assertEquals(1, resource.getPreDestroyCount());
}
@Test
public void testConnectorBinding() throws Exception {
LifecycleInjector injector = InjectorBuilder.fromModules(
new SampleServletModule(),
new ShutdownHookModule(),
Modules.override(new JettyModule())
.with(new AbstractModule() {
@Override
protected void configure() {
}
@Provides
JettyConfig getConfig() {
// Use ephemeral ports
return new DefaultJettyConfig().setPort(0);
}
}),
new JettySslModule()
).createInjector();
Server server = injector.getInstance(Server.class);
Assert.assertEquals(2, server.getConnectors().length);
KeyStore keyStore = injector.getInstance(KeyStore.class);
int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
int sslPort = ((ServerConnector)server.getConnectors()[1]).getLocalPort();
// Do a plaintext GET and verify that the default connector works
String response = doGet(String.format("http://localhost:%d/", port), null);
Assert.assertTrue(response.startsWith("hello "));
// Do an SSL GET and verify the response is valid
response = doGet(String.format("https://localhost:%d/", sslPort), keyStore);
Assert.assertTrue(response.startsWith("hello "));
injector.close();
}
private static String doGet(String url, KeyStore sslTrustStore) throws Exception {
URLConnection urlConnection = new URL(url).openConnection();
if (sslTrustStore != null) {
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(sslTrustStore);
sslContext.init(null, tmf.getTrustManagers(), null);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;
httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
}
try (InputStream inputStream = urlConnection.getInputStream()) {
byte[] buffer = new byte[4096];
int n = inputStream.read(buffer);
return new String(buffer, 0, n, StandardCharsets.UTF_8);
}
}
}
| 5,474 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/JettyGuiceContextListenerExample.java | package com.netflix.governator.guice.jetty;
import com.netflix.governator.Governator;
import com.netflix.governator.ShutdownHookModule;
import com.netflix.governator.guice.jetty.JettyModule;
public class JettyGuiceContextListenerExample {
public static void main(String args[]) throws Exception {
new Governator()
.addModules(
new SampleServletModule(),
new ShutdownHookModule(),
new JettyModule())
.run()
.awaitTermination();
}
}
| 5,475 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/JettySslModule.java | package com.netflix.governator.guice.jetty;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.sun.jersey.core.util.Base64;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
public class JettySslModule extends AbstractModule {
// Generated with
// openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365000 -subj '/CN=localhost/' -nodes
private static final String CERTIFICATE =
"MIIC/TCCAeWgAwIBAgIJAICIMvFHSibpMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNV" +
"BAMMCWxvY2FsaG9zdDAgFw0xNjA5MDYyMDM3NDJaGA8zMDE2MDEwODIwMzc0Mlow" +
"FDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB" +
"CgKCAQEAx22xi43/Y/DwPJczTXjs8fQFOdH5PmtNCteaJMAG14wb3LZd55EEstJ6" +
"lKy9LqTOywlsiIFMWDvOs5yUxFeak5OwJ8/84xfblCLyQZ7CHnkBcvXpx3jM934j" +
"rdgP+X2GeGj3QC8u/Qs3vlFaOoAB/k/sLm15VO3j9b4bp0E76joWOhwQieBe5/Qc" +
"ZvXUhfL+5DGoO9ROejP3+M9TM74L+ceQpN/8m71lUDiTOk13UhcqlFD7YSxWIzGq" +
"6maHa8z54L+Zuis6juHsgQHASZsYhN7nynW3+KBSNrs859x/WSPmy/zYwh08W8lm" +
"4kdjVE5TXw/NDjFnngwv16vtejh8gwIDAQABo1AwTjAdBgNVHQ4EFgQU4cWlr1ut" +
"ZZu4Qp3WVAzd7a1R5LAwHwYDVR0jBBgwFoAU4cWlr1utZZu4Qp3WVAzd7a1R5LAw" +
"DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAHsClc/3ftd9A/95Xj6H0" +
"g10hlqb0EAFRM97/DiDwt9ESdFoBnE51Zv7BmcPN0CBCyHMj/MnaB/BijuDR0N8/" +
"7h2R97rsXbNJkSFtLeV7cXBD/sXi+e8INX3rqADWQJ24Buv55miyR6M3CarY6yNl" +
"i+gnulM4jFRSq7jvfYUbzA9mi/fCqGI9F4poS2QKxMiyx5xcU57u3mHJYD+JbS+W" +
"UywJfv9PXkBkHxO9yEYJ3DG78CPUv45CsBCmoBRN7TDndpwDCqpXbXlxME2i8ljL" +
"yKg6WQUrig6xdE0yRcLoY8n3ibuNghDPBTEjhQ4UTs2JfISaBB/T2fZP8PQXqUgm" +
"Ag==";
private static final String PRIVATE_KEY =
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDHbbGLjf9j8PA8" +
"lzNNeOzx9AU50fk+a00K15okwAbXjBvctl3nkQSy0nqUrL0upM7LCWyIgUxYO86z" +
"nJTEV5qTk7Anz/zjF9uUIvJBnsIeeQFy9enHeMz3fiOt2A/5fYZ4aPdALy79Cze+" +
"UVo6gAH+T+wubXlU7eP1vhunQTvqOhY6HBCJ4F7n9Bxm9dSF8v7kMag71E56M/f4" +
"z1Mzvgv5x5Ck3/ybvWVQOJM6TXdSFyqUUPthLFYjMarqZodrzPngv5m6KzqO4eyB" +
"AcBJmxiE3ufKdbf4oFI2uzzn3H9ZI+bL/NjCHTxbyWbiR2NUTlNfD80OMWeeDC/X" +
"q+16OHyDAgMBAAECggEBAKOXWA0ibl2NR4Rsg6kJiVTw11iW5d5OJuS997Qt0W7/" +
"f9uNvXo3e6M1BVjwWj/o8bmcAWv4pKe8Z9LunxpwwlxMyjPeaZPf/j+GazNpB9P3" +
"bzjegOcgMQLUdnAkzPXcAnLDqA7+pYztpsx374wNdZUn+pYbN2xzuIvdZtHMsVlw" +
"2ZSd/ZU/e3++jpDAqgdpul6TdMGcSxqjYyuwPWQhYx00qBIJNZig9phQKACxNYxR" +
"yyqdRv3t/csFhK17qnFgVf424nXFbg7ELoLpCujkwXkMQWkr8Z44DtKNJspJlST9" +
"zoVaTRhV5p7tXged/JUt8FG5nvgu4snlnMhn/K1n0AECgYEA7iK0sJaCwLtWnB46" +
"diUOkhANHrAe+XTXl1nwQQkD7vUHyrlukJDliEh1NhmJMRxPQbHf9RrUhLhgLBRg" +
"2ge67w6kGj2Agyx3WF2oblbD2OAHCe2Rrs5fF69mqMpvbqZZIWD+yFiBJp79bin5" +
"jN+uOhiABh1yfw/EjV0eU+XWyA8CgYEA1mOiaXWDVB7t495MJ8mi5I+BZcnMbvgI" +
"4hKWpZMdIGCsjEmvQJrjXzIXyATpznNOzrEup6tFjX0WmgWQOuQE5wSi9iGoaZLw" +
"YdGPgH3j2MwXlplSiWviibdZfIli28C4i3+FmGZlO5THHB/xK4uVtezDDMxpwFyQ" +
"SeDuL2ussE0CgYEA0uQLbwOsAfEmb5XZoj2JHNN4OwAwPi06rH/q5D2OrTV01BTK" +
"FN8tVzcMDoAo3kQ68GwNcWx0XqFGEmNtrkkARKuLqu1ifUiI3Mn82tKeGNe1hBZP" +
"WSbMUhZ07PByJOTOtF/I4zZ2EfTlbYVgymBhVHPUFRZJCru1DpgzvosiXgMCgYBV" +
"sAjwAan1607FrsnddTgIBlt/pYJyL+zM/wT7NKuFj14nzCOhvMZ3+/uJVH1mqKus" +
"7SBqn4fzHzXzZZnaD9ztwOqpWZaIa9RsJGgowShaNGiRJsLYbihjRscbgYXjs0mP" +
"Z+6rlPGNOM/EK/gmoWm7BuCGswTpf5WkEaThizXAWQKBgCgV3hc6wDbD84h6XGFF" +
"cNPJ1fiBdZflQ5P21QRGTe5tsIJPnZ3qj2JSsY4GODCfkzBOK+7VzGMCAi7fWlUt" +
"drUEPaOCDY7/9JkKgu8uPDYsUb22Q1BZi2vfbsfXytkna8bi4cXKJkeoNEKimJni" +
"jZIzPiAGS5/h4W+2PcfvygvD";
@Override
protected void configure() {
final KeyStore keyStore;
try {
keyStore = loadSelfSignedKeyStore();
} catch (Exception e) {
throw new RuntimeException(e);
}
bind(KeyStore.class).toInstance(keyStore);
Multibinder.newSetBinder(binder(), JettyConnectorProvider.class).addBinding()
.toInstance(new SslJettyConnectorProvider(keyStore));
}
private static class SslJettyConnectorProvider implements JettyConnectorProvider {
private final KeyStore keyStore;
private SslJettyConnectorProvider(KeyStore keyStore) {
this.keyStore = keyStore;
}
@Override
public Connector getConnector(Server server) {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, "password".toCharArray());
sslContext.init(kmf.getKeyManagers(), null, null);
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setSslContext(sslContext);
ServerConnector serverConnector = new ServerConnector(server, sslContextFactory);
// In a real module, this would be configurable; for tests always use an ephemeral port
serverConnector.setPort(0);
return serverConnector;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private static KeyStore loadSelfSignedKeyStore() throws Exception {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
X509Certificate[] chain = new X509Certificate[1];
try (InputStream inputStream = new ByteArrayInputStream(Base64.decode(CERTIFICATE))) {
chain[0] = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(inputStream);
}
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decode(PRIVATE_KEY));
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privateKey = kf.generatePrivate(spec);
keyStore.setKeyEntry("1", privateKey, "password".toCharArray(), chain);
return keyStore;
}
}
| 5,476 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/SampleServletModule.java | package com.netflix.governator.guice.jetty;
import com.google.inject.servlet.ServletModule;
import com.netflix.governator.guice.jetty.resources1.SampleResource;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
public class SampleServletModule extends ServletModule {
@Override
protected void configureServlets() {
bind(SampleResource.class);
bind(GuiceContainer.class);
serve("/*").with(GuiceContainer.class);
}
}
| 5,477 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/SomeSingleton.java | package com.netflix.governator.guice.jetty;
import com.netflix.governator.guice.lazy.LazySingleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
@LazySingleton
public class SomeSingleton {
private static final Logger LOG = LoggerFactory.getLogger(SomeSingleton.class);
@Inject
public SomeSingleton() {
LOG.info("SomeSingleton created");
}
@PreDestroy
private void shutdown() {
LOG.info("SomeSingleton#shutdown()");
}
}
| 5,478 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/PreDestroySingletonScopeBugTest.java | package com.netflix.governator.guice.jetty;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.governator.InjectorBuilder;
import com.netflix.governator.LifecycleInjector;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
public class PreDestroySingletonScopeBugTest {
private static final Logger LOG = LoggerFactory.getLogger(PreDestroySingletonScopeBugTest.class);
@Test
public void callingScopeOnSingletonDoesntBlowUp() throws Exception {
LifecycleInjector injector = InjectorBuilder
.fromModules(
new JerseyServletModule() {
@Override
protected void configureServlets() {
serve("/*").with(GuiceContainer.class, Collections.singletonMap(
PackagesResourceConfig.PROPERTY_PACKAGES, "com.netflix.governator.guice.jetty.resources2"));
}
},
new JettyModule())
.overrideWith(new AbstractModule() {
@Override
protected void configure() {
}
@Provides
JettyConfig getConfig() {
// Use emphemeral ports
return new DefaultJettyConfig().setPort(0);
}
})
.createInjector();
LOG.info("-----------------------------------");
Server server = injector.getInstance(Server.class);
int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
LOG.info("Port : " + port);
URL url = new URL(String.format("http://localhost:%d/hello", port));
HttpURLConnection conn;
conn = (HttpURLConnection)url.openConnection();
Assert.assertEquals(200, conn.getResponseCode());
conn = (HttpURLConnection)url.openConnection();
LOG.info("Response : " + conn.getResponseCode());
Assert.assertEquals(200, conn.getResponseCode());
injector.close();
}
}
| 5,479 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/SomeFineGrainedLazySingleton.java | package com.netflix.governator.guice.jetty;
import com.netflix.governator.guice.lazy.FineGrainedLazySingleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
@FineGrainedLazySingleton
public class SomeFineGrainedLazySingleton {
private static final Logger LOG = LoggerFactory.getLogger(SomeFineGrainedLazySingleton.class);
@Inject
public SomeFineGrainedLazySingleton() {
LOG.info("@FineGrainedLazySingleton created");
}
@PreDestroy
private void shutdown() {
LOG.info("@FineGrainedLazySingleton#shutdown()");
}
}
| 5,480 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/SomeLazySingleton.java | package com.netflix.governator.guice.jetty;
import com.netflix.governator.guice.lazy.LazySingleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
@LazySingleton
public class SomeLazySingleton {
private static final Logger LOG = LoggerFactory.getLogger(SomeLazySingleton.class);
@Inject
public SomeLazySingleton() {
LOG.info("SomeLazySingleton created");
}
@PreDestroy
private void shutdown() {
LOG.info("SomeLazySingleton#shutdown()");
}
}
| 5,481 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/resources1/SampleResource.java | package com.netflix.governator.guice.jetty.resources1;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.governator.LifecycleShutdownSignal;
@Path("/")
@Singleton
public class SampleResource {
private static final Logger LOG = LoggerFactory.getLogger(SampleResource.class);
private AtomicInteger counter = new AtomicInteger();
private final LifecycleShutdownSignal event;
private final AtomicInteger postConstruct = new AtomicInteger();
private final AtomicInteger preDestroy = new AtomicInteger();
@Inject
public SampleResource(LifecycleShutdownSignal event) {
this.event = event;
}
@GET
public String getHello() {
LOG.info("Saying hello");
return "hello " + counter.incrementAndGet();
}
@PostConstruct
public void init() {
postConstruct.incrementAndGet();
LOG.info("Post construct " + postConstruct.get());
}
@PreDestroy
public void shutdown() {
preDestroy.incrementAndGet();
LOG.info("Pre destroy " + preDestroy.get());
}
@Path("kill")
public String kill() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
event.signal();
}
});
t.setDaemon(true);
t.start();
return "killing";
}
public int getPreDestroyCount() {
return preDestroy.get();
}
public int getPostConstructCount() {
return postConstruct.get();
}
}
| 5,482 |
0 | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty | Create_ds/governator/governator-jetty/src/test/java/com/netflix/governator/guice/jetty/resources2/NonSingletonResource.java | package com.netflix.governator.guice.jetty.resources2;
import com.netflix.governator.guice.jetty.SomeFineGrainedLazySingleton;
import com.netflix.governator.guice.jetty.SomeLazySingleton;
import com.netflix.governator.guice.jetty.SomeSingleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class NonSingletonResource {
private static final Logger LOG = LoggerFactory.getLogger(NonSingletonResource.class);
@Inject
public NonSingletonResource(SomeLazySingleton lazySingleton, SomeSingleton singleton, SomeFineGrainedLazySingleton fglSingleton) {
LOG.info("NonSingletonResource()");
}
@PreDestroy
private void shutdown() {
LOG.info("NonSingletonResource#shutdown()");
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public String echo() {
LOG.info("Saying hello");
return "hello";
}
} | 5,483 |
0 | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice/jetty/JettyModule.java |
package com.netflix.governator.guice.jetty;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.ProvisionException;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.servlet.GuiceFilter;
import com.netflix.governator.AbstractLifecycleListener;
import com.netflix.governator.LifecycleManager;
import com.netflix.governator.LifecycleShutdownSignal;
import com.netflix.governator.spi.LifecycleListener;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.FragmentConfiguration;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.webapp.WebXmlConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.DispatcherType;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Set;
/**
* Installing JettyModule will create a Jetty web server within the context
* of the Injector and will use servlet and filter bindings from any additionally
* installed ServletModule.
*
*
* <pre>
* {@code
public static void main(String args[]) throws Exception {
Governator.createInjector(
new SampleServletModule(),
new ShutdownHookModule(),
new JettyModule())
.awaitTermination();
}
* }
*
* To change Jetty's configuration provide an override binding for JettyConfig.class.
*
* <pre>
* {@code
public static void main(String args[]) throws Exception {
Governator.createInjector(
new SampleServletModule(),
new ShutdownHookModule(),
Modules.override(new JettyModule())
.with(new AbstractModule() {
@Overrides
private void configure() {}
@Provider
@Singleton
private JettyConfig getConfig() {
DefaultJettyConfig config = new DefaultJettyConfig();
config.setPort(80);
return config;
}
})
.awaitTermination());
}
* }
* </pre>
*
* Note that only one Jetty server may be created in an Injector
*
* @author elandau
*
*/
public final class JettyModule extends AbstractModule {
public final static String UNENCRYPTED_CONNECTOR_NAME = "unencrypted";
private final static String CLASSPATH_RESOURCE_PREFIX = "classpath:";
private final static Logger LOG = LoggerFactory.getLogger(JettyModule.class);
/**
* Eager singleton to start the Jetty Server
*
* @author elandau
*/
@Singleton
public static class JettyRunner {
private final Server server;
private final int port;
@Inject
public JettyRunner(Server server, final LifecycleManager manager) {
this.server = server;
LOG.info("Jetty server starting");
try {
server.start();
int port = -1;
for (Connector connector : server.getConnectors()) {
if (connector.getName().equals(UNENCRYPTED_CONNECTOR_NAME)) {
port = ((ServerConnector)connector).getLocalPort();
break;
}
}
this.port = port;
LOG.info("Jetty server on port {} started", port);
} catch (Exception e) {
try {
server.stop();
}
catch (Exception e2) {
}
throw new ProvisionException("Jetty server failed to start", e);
}
}
public boolean isRunning() {
return server.isRunning();
}
public int getLocalPort() {
return this.port;
}
}
@Singleton
static class OptionalJettyConfig {
@com.google.inject.Inject(optional=true)
private JettyConfig jettyConfig;
public JettyConfig getJettyConfig() {
return jettyConfig != null ? jettyConfig : new DefaultJettyConfig();
}
}
/**
* LifecycleListener to stop Jetty Server. This will catch shutting down
* Jetty when notified only through LifecycleManager#shutdown() and not via the
* LifecycleEvent#shutdown().
*
* @author elandau
*
*/
@Singleton
public static class JettyShutdown extends AbstractLifecycleListener {
private Server server;
@Inject
public JettyShutdown(Server server) {
this.server = server;
}
@Override
public void onStopped(Throwable optionalError) {
LOG.info("Jetty Server shutting down");
try {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
server.stop();
LOG.info("Jetty Server shut down");
} catch (Exception e) {
LOG.warn("Failed to shut down Jetty server", e);
}
}
});
t.start();
} catch (Exception e) {
LOG.warn("Error shutting down Jetty server");
}
}
}
@Override
protected void configure() {
bind(JettyRunner.class).asEagerSingleton();
Multibinder.newSetBinder(binder(), LifecycleListener.class).addBinding().to(JettyShutdown.class);
bind(LifecycleShutdownSignal.class).to(JettyLifecycleShutdownSignal.class);
Multibinder.newSetBinder(binder(), JettyConnectorProvider.class);
}
@Provides
@Singleton
private Server getServer(OptionalJettyConfig optionalConfig, Set<JettyConnectorProvider> jettyConnectors) {
JettyConfig config = optionalConfig.getJettyConfig();
Server server = new Server();
Resource webAppResourceBase = null;
if (config.getWebAppResourceBase() != null && !config.getWebAppResourceBase().isEmpty()) {
if (config.getWebAppResourceBase().startsWith(CLASSPATH_RESOURCE_PREFIX)) {
webAppResourceBase = Resource.newClassPathResource(config.getWebAppResourceBase().substring(CLASSPATH_RESOURCE_PREFIX.length()));
} else {
try {
webAppResourceBase = Resource.newResource(config.getWebAppResourceBase());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Resource staticResourceBase = Resource.newClassPathResource(config.getStaticResourceBase());
if (staticResourceBase != null) {
// Set up a full web app since we have static content. We require the app to have its static content
// under src/main/webapp and any other static resources that are packaged into jars are expected under
// META-INF/resources.
WebAppContext webAppContext = new WebAppContext();
// We want to fail fast if we don't have any root resources defined or we have other issues starting up.
webAppContext.setThrowUnavailableOnStartupException(true);
webAppContext.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
webAppContext.addServlet(DefaultServlet.class, "/");
webAppContext.setBaseResource(webAppResourceBase);
webAppContext.setContextPath(config.getWebAppContextPath());
webAppContext.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*\\.jar$");
webAppContext.setConfigurations(new Configuration[]{
new WebXmlConfiguration(),
new WebInfConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
});
server.setHandler(webAppContext);
} else {
// We don't have static content so just set up servlets.
ServletContextHandler servletContextHandler =
new ServletContextHandler(server, config.getWebAppContextPath(), ServletContextHandler.SESSIONS);
servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
servletContextHandler.addServlet(DefaultServlet.class, "/");
servletContextHandler.setBaseResource(webAppResourceBase);
}
if (config.isUnencryptedSocketEnabled()) {
ServerConnector connector = new ServerConnector(server);
connector.setName(UNENCRYPTED_CONNECTOR_NAME);
connector.setPort(config.getPort());
if (config.getBindToHost() != null && !config.getBindToHost().isEmpty()) {
connector.setHost(config.getBindToHost());
}
HttpConfiguration httpConfiguration = ((HttpConnectionFactory)connector.getConnectionFactory(HttpVersion.HTTP_1_1.asString())).getHttpConfiguration();
httpConfiguration.setRequestHeaderSize(config.getRequestHeaderSizeBytes());
server.addConnector(connector);
}
if (jettyConnectors != null) {
for (JettyConnectorProvider connectorProvider : jettyConnectors) {
Connector connector = connectorProvider.getConnector(server);
if (connector != null) {
server.addConnector(connector);
}
}
}
if (server.getConnectors().length == 0) {
throw new IllegalStateException("No connectors have been configured. Either set unencryptedSocketEnabled=true or bind a JettyConnectorProvider");
}
return server;
}
@Provides
@Singleton
@Named("embeddedJettyPort")
public Integer jettyPort(JettyRunner runner) {
return runner.getLocalPort();
}
@Override
public boolean equals(Object obj) {
return JettyModule.class.equals(obj.getClass());
}
@Override
public int hashCode() {
return JettyModule.class.hashCode();
}
}
| 5,484 |
0 | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice/jetty/JettyLifecycleShutdownSignal.java | package com.netflix.governator.guice.jetty;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.governator.AbstractLifecycleShutdownSignal;
import com.netflix.governator.LifecycleManager;
@Singleton
public class JettyLifecycleShutdownSignal extends AbstractLifecycleShutdownSignal {
private static final Logger LOG = LoggerFactory.getLogger(JettyLifecycleShutdownSignal.class);
private final Server server;
@Inject
public JettyLifecycleShutdownSignal(Server server, LifecycleManager manager) {
super(manager);
this.server = server;
}
@Override
public void signal() {
final int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
LOG.info("Jetty Server on port {} shutting down", port);
try {
shutdown();
server.stop();
} catch (Exception e) {
LOG.error("Failed to shut down jetty on port{}", port, e);
throw new RuntimeException(e);
}
}
@Override
public void await() throws InterruptedException {
int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
LOG.info("Joining Jetty server on port {}", port);
server.join();
}
}
| 5,485 |
0 | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice/jetty/Archaius2JettyConfig.java | package com.netflix.governator.guice.jetty;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix="governator.jetty.embedded")
public interface Archaius2JettyConfig extends JettyConfig {
@DefaultValue("8080")
int getPort();
/**
* @deprecated 2016-10-14 use {@link #getStaticResourceBase()} instead
*/
@Deprecated
@DefaultValue("/META-INF/resources/")
String getResourceBase();
/**
* @return The directory where the webapp has the static resources. It can just be a suffix since we'll scan the
* classpath to find the exact directory name.
*/
@DefaultValue("/META-INF/resources/")
String getStaticResourceBase();
/**
* @return web app base resource path
*/
@DefaultValue("src/main/webapp")
String getWebAppResourceBase();
/**
* @return the default web app context path for jetty
*/
@DefaultValue("/")
String getWebAppContextPath();
@DefaultValue("true")
boolean isUnencryptedSocketEnabled();
@DefaultValue("16384")
int getRequestHeaderSizeBytes();
String getBindToHost();
}
| 5,486 |
0 | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice/jetty/DefaultJettyConfig.java | package com.netflix.governator.guice.jetty;
import javax.inject.Singleton;
@Singleton
public class DefaultJettyConfig implements JettyConfig {
private int port = 8080;
// Where static files live. We pass this to Jetty for class path scanning to find the exact directory.
// The default is to use resources supported by the servlet 3.0 spec.
private String staticResourceBase = "/META-INF/resources/";
private String webAppResourceBase = "src/main/webapp";
private String webAppContextPath = "/";
private boolean unencryptedSocketEnabled = true;
private int requestHeaderSizeBytes = 16384;
private String bindToHost = null;
@Override
public int getPort() {
return port;
}
@Override
public String getResourceBase() {
return staticResourceBase;
}
@Override
public String getStaticResourceBase() {
return staticResourceBase;
}
@Override
public String getWebAppResourceBase() {
return webAppResourceBase;
}
@Override
public String getWebAppContextPath() {
return webAppContextPath;
}
@Override
public boolean isUnencryptedSocketEnabled() {
return unencryptedSocketEnabled;
}
@Override
public int getRequestHeaderSizeBytes() {
return requestHeaderSizeBytes;
}
@Override
public String getBindToHost() {
return bindToHost;
}
public DefaultJettyConfig setPort(int port) {
this.port = port;
return this;
}
/**
* @deprecated 2016-10-14 use {@link #setStaticResourceBase(String)} instead
*/
@Deprecated
public DefaultJettyConfig setResourceBase(String staticResourceBase) {
this.staticResourceBase = staticResourceBase;
return this;
}
public DefaultJettyConfig setStaticResourceBase(String staticResourceBase) {
this.staticResourceBase = staticResourceBase;
return this;
}
public DefaultJettyConfig setWebAppResourceBase(String webAppResourceBase) {
this.webAppResourceBase = webAppResourceBase;
return this;
}
public DefaultJettyConfig setWebAppContextPath(String webAppContextPath) {
this.webAppContextPath = webAppContextPath;
return this;
}
public DefaultJettyConfig setUnencryptedSocketEnabled(boolean unencryptedSocketEnabled) {
this.unencryptedSocketEnabled = unencryptedSocketEnabled;
return this;
}
public DefaultJettyConfig setRequestHeaderSizeBytes(int requestHeaderSizeBytes) {
this.requestHeaderSizeBytes = requestHeaderSizeBytes;
return this;
}
public DefaultJettyConfig setBindToHost(String bindToHost) {
this.bindToHost = bindToHost;
return this;
}
}
| 5,487 |
0 | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice/jetty/JettyConnectorProvider.java | package com.netflix.governator.guice.jetty;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
/**
* Implementations of this interface should return a connector which may be added to a Jetty server. The server is
* passed as an argument to the getConnector() argument so that implementations can utilize subclasses of Jetty's
* ServerConnector which requires the Server as a constructor argument.
*/
public interface JettyConnectorProvider {
public Connector getConnector(Server server);
}
| 5,488 |
0 | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice/jetty/Archaius2JettyModule.java | package com.netflix.governator.guice.jetty;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.archaius.ConfigProxyFactory;
public final class Archaius2JettyModule extends AbstractModule {
@Override
protected void configure() {
install(new JettyModule());
}
@Provides
@Singleton
public JettyConfig jettyConfig(ConfigProxyFactory configProxyFactory) {
return configProxyFactory.newProxy(Archaius2JettyConfig.class);
}
@Override
public boolean equals(Object obj) {
return Archaius2JettyModule.class.equals(obj.getClass());
}
@Override
public int hashCode() {
return Archaius2JettyModule.class.hashCode();
}
}
| 5,489 |
0 | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-jetty/src/main/java/com/netflix/governator/guice/jetty/JettyConfig.java | package com.netflix.governator.guice.jetty;
public interface JettyConfig {
int getPort();
/**
* @deprecated 2016-10-14 use {@link #getStaticResourceBase()} instead
*
* @return The directory where the webapp has the static resources. It can just be a suffix since we'll scan the
* classpath to find the exact directory name.
*/
@Deprecated
String getResourceBase();
/**
* @return The directory where the webapp has the static resources. It can just be a suffix since we'll scan the
* classpath to find the exact directory name.
*/
default String getStaticResourceBase() { return getResourceBase(); };
/**
* @return the web app resource base
*/
String getWebAppResourceBase();
/**
* @return the web app context path
*/
default String getWebAppContextPath() { return "/"; }
boolean isUnencryptedSocketEnabled();
int getRequestHeaderSizeBytes();
String getBindToHost();
}
| 5,490 |
0 | Create_ds/governator/governator-servlet/src/test/java/com/netflix/governator/guice | Create_ds/governator/governator-servlet/src/test/java/com/netflix/governator/guice/servlet/GovernatorServletContextListenerTest.java | /*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.guice.servlet;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.netflix.governator.LifecycleShutdownSignal;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
/**
* @author Nikos Michalakis <nikos@netflix.com>
*/
public class GovernatorServletContextListenerTest {
private GovernatorServletContextListener listener;
private LifecycleShutdownSignal mockLifecycleSignal;
@Before
public void setUp() {
mockLifecycleSignal = Mockito.mock(LifecycleShutdownSignal.class);
listener = new GovernatorServletContextListener() {
@Override
protected Injector createInjector() throws Exception {
return Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(LifecycleShutdownSignal.class).toInstance(mockLifecycleSignal);
}
});
}
};
}
@Test(expected = IllegalStateException.class)
public void testGetInjectorIsCreatedOnlyOnce() {
Injector injector = listener.getInjector();
Assert.assertNotNull(injector);
listener.getInjector();
}
@Test
public void testContextDestroyedAfterInjectorIsCreated() {
// The app starts and gets an injector.
listener.getInjector();
// Now we make sure it's signalled when we shutdown.
ServletContextEvent servletContextEvent = Mockito.mock(ServletContextEvent.class);
ServletContext mockServletContext = Mockito.mock(ServletContext.class);
Mockito.when(servletContextEvent.getServletContext()).thenReturn(mockServletContext);
listener.contextDestroyed(servletContextEvent);
Mockito.verify(mockLifecycleSignal).signal();
}
}
| 5,491 |
0 | Create_ds/governator/governator-servlet/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-servlet/src/main/java/com/netflix/governator/guice/servlet/GovernatorServletContainerInitializer.java | package com.netflix.governator.guice.servlet;
import java.lang.reflect.Modifier;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.servlet.DispatcherType;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceFilter;
@HandlesTypes(WebApplicationInitializer.class)
public class GovernatorServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> initializerClasses, ServletContext servletContext) throws ServletException {
final WebApplicationInitializer initializer = getInitializer(initializerClasses, servletContext);
if (initializer != null) {
servletContext.addFilter("guiceFilter", new GuiceFilter()).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
servletContext.addListener(new GovernatorServletContextListener() {
@Override
protected Injector createInjector() throws Exception {
return initializer.createInjector();
}
});
}
}
private WebApplicationInitializer getInitializer(Set<Class<?>> initializerClasses, ServletContext servletContext)
throws ServletException {
List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();
if (initializerClasses != null) {
for (Class<?> initializerClass : initializerClasses) {
if (!initializerClass.isInterface() && !Modifier.isAbstract(initializerClass.getModifiers())
&& WebApplicationInitializer.class.isAssignableFrom(initializerClass)) {
try {
initializers.add((WebApplicationInitializer) initializerClass.newInstance());
} catch (Throwable ex) {
throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
}
}
}
}
if (initializers.isEmpty()) {
servletContext.log("No WebApplicationInitializer types found on classpath");
return null;
}
if (initializers.size() > 1) {
servletContext.log(
"Multiple WebApplicationInitializer types found on classpath. Expected one but found " + initializers.size());
return null;
}
return initializers.get(0);
}
}
| 5,492 |
0 | Create_ds/governator/governator-servlet/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-servlet/src/main/java/com/netflix/governator/guice/servlet/JspDispatchServlet.java | package com.netflix.governator.guice.servlet;
import java.io.IOException;
import javax.inject.Singleton;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* This service is a hack to solve a bug in Guice's serving of jsp files.
*
* To enable add this line to your ServletModule
* <pre>
* {@code
* serveRegex("/.*\\.jsp").with(JspDispatchServlet.class);
* bind(JspDispatchServlet.class).asEagerSingleton();
* }
* </pre>
*
* @author elandau
*/
@Singleton
public class JspDispatchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
RequestDispatcher rd = getServletContext().getRequestDispatcher(req.getRequestURI());
req.setAttribute("org.apache.catalina.jsp_file", req.getRequestURI());
// Wrap ServletPath with an empty value to avoid Guice's null getServletPath() bug from within a filter/servlet chain
HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {
public String getServletPath() {
return "";
}
};
rd.include(wrapped, resp);
}
}
| 5,493 |
0 | Create_ds/governator/governator-servlet/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-servlet/src/main/java/com/netflix/governator/guice/servlet/WebApplicationInitializer.java | package com.netflix.governator.guice.servlet;
import com.google.inject.Injector;
/***
* Servlet 3.0+ compatible interface for bootstrapping a web application. Any
* class (or classes) on the classpath implementing WebApplicationInitializer
* will be initialized by the container.
*
* public class MyWebApplication implements WebApplicationInitializer {
*
* @Override
* protected Injector createInjector() throws Exception {
* return InjectorBuilder.fromModules().createInjector();
* }
*
* }
*
* @author twicksell
*/
public interface WebApplicationInitializer {
Injector createInjector();
}
| 5,494 |
0 | Create_ds/governator/governator-servlet/src/main/java/com/netflix/governator/guice | Create_ds/governator/governator-servlet/src/main/java/com/netflix/governator/guice/servlet/GovernatorServletContextListener.java | /*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.governator.guice.servlet;
import javax.servlet.ServletContextEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Injector;
import com.google.inject.ProvisionException;
import com.google.inject.servlet.GuiceServletContextListener;
import com.netflix.governator.LifecycleShutdownSignal;
/**
* An extension of {@link GuiceServletContextListener} which integrates with Governator's
* LifecycleInjector. This implementation drives shutdown of LifecycleManager through the
* ServletContextListener's contextDestroyed event.
*
* To use, subclass your main server class from GovernatorServletContextListener
* <pre>
* {@code
*
package com.cloudservice.StartServer;
public class StartServer extends GovernatorServletContextListener
{
@Override
protected Injector createInjector() {
return Governator.createInjector(
new JerseyServletModule() {
{@literal @}Override
protected void configureServlets() {
serve("/REST/*").with(GuiceContainer.class);
binder().bind(GuiceContainer.class).asEagerSingleton();
bind(MyResource.class).asEagerSingleton();
}
}
);
}
}
* }
* </pre>
*
* Then reference this class from web.xml.
*
<PRE>
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>com.cloudservice.StartServer</listener-class>
</listener>
</PRE>
*
* @author Eran Landau
*/
public abstract class GovernatorServletContextListener extends GuiceServletContextListener {
protected static final Logger LOG = LoggerFactory.getLogger(GovernatorServletContextListener.class);
private Injector injector;
public void contextInitialized(ServletContextEvent servletContextEvent) {
super.contextInitialized(servletContextEvent);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
super.contextDestroyed(servletContextEvent);
if (injector != null) {
injector.getInstance(LifecycleShutdownSignal.class).signal();
}
}
/**
* Override this method to create (or otherwise obtain a reference to) your
* injector.
* NOTE: If everything is set up right, then this method should only be called once during
* application startup.
*/
protected final Injector getInjector() {
if (injector != null) {
throw new IllegalStateException("Injector already created.");
}
try {
injector = createInjector();
}
catch (Exception e) {
LOG.error("Failed to created injector", e);
throw new ProvisionException("Failed to create injector", e);
}
return injector;
}
protected abstract Injector createInjector() throws Exception;
}
| 5,495 |
0 | Create_ds/governator/governator-core/src/test/java/com/netflix | Create_ds/governator/governator-core/src/test/java/com/netflix/governator/TracingProvisionListenerTest.java | package com.netflix.governator;
import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;
import com.netflix.governator.test.TracingProvisionListener;
import org.junit.Test;
public class TracingProvisionListenerTest {
@Test
public void testDefault() {
LifecycleInjector injector = InjectorBuilder
.fromModules(
new AbstractModule() {
@Override
protected void configure() {
bindListener(Matchers.any(), TracingProvisionListener.createDefault());
}
})
.createInjector();
}
}
| 5,496 |
0 | Create_ds/governator/governator-core/src/test/java/com/netflix | Create_ds/governator/governator-core/src/test/java/com/netflix/governator/InjectorBuilderTest.java | package com.netflix.governator;
import com.google.inject.AbstractModule;
import com.google.inject.spi.Element;
import com.netflix.governator.visitors.BindingTracingVisitor;
import com.netflix.governator.visitors.KeyTracingVisitor;
import com.netflix.governator.visitors.ModuleSourceTracingVisitor;
import com.netflix.governator.visitors.WarnOfToInstanceInjectionVisitor;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.mockito.Mockito;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import javax.inject.Inject;
public class InjectorBuilderTest {
@Test
public void testLifecycleInjectorEvents() {
final AtomicBoolean injectCalled = new AtomicBoolean(false);
final AtomicBoolean afterInjectorCalled = new AtomicBoolean(false);
InjectorBuilder
.fromModule(new AbstractModule() {
@Override
protected void configure() {
}
})
.createInjector(new LifecycleInjectorCreator() {
@Inject
public void initialize() {
injectCalled.set(true);
}
@Override
protected void onCompletedInjectorCreate() {
afterInjectorCalled.set(true);
}
})
.shutdown();
Assert.assertTrue(injectCalled.get());
Assert.assertTrue(afterInjectorCalled.get());
}
@Before
public void printTestHeader() {
System.out.println("\n=======================================================");
System.out.println(" Running Test : " + name.getMethodName());
System.out.println("=======================================================\n");
}
@Rule
public TestName name = new TestName();
@Test
public void testBindingTracing() {
InjectorBuilder
.fromModule(new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("Hello world");
}
})
.traceEachElement(new BindingTracingVisitor())
.createInjector();
}
@Test
public void testForEachBinding() {
Consumer<String> consumer = Mockito.mock(Consumer.class);
InjectorBuilder
.fromModule(new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("Hello world");
}
})
.forEachElement(new WarnOfToInstanceInjectionVisitor(), consumer)
.createInjector();
Mockito.verify(consumer, Mockito.times(1)).accept(Mockito.anyString());
}
@Test
public void testKeyTracing() {
try (LifecycleInjector li = InjectorBuilder
.fromModule(new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("Hello world");
}
})
.traceEachElement(new KeyTracingVisitor())
.createInjector()) {}
}
@Test
public void testWarnOnStaticInjection() {
List<Element> elements = InjectorBuilder
.fromModule(new AbstractModule() {
@Override
protected void configure() {
this.requestStaticInjection(String.class);
}
})
.warnOfStaticInjections()
.getElements();
Assert.assertEquals(1, elements.size());
}
@Test
public void testStripStaticInjection() {
List<Element> elements = InjectorBuilder
.fromModule(new AbstractModule() {
@Override
protected void configure() {
this.requestStaticInjection(String.class);
}
})
.stripStaticInjections()
.warnOfStaticInjections()
.getElements();
Assert.assertEquals(0, elements.size());
}
public static class ModuleA extends AbstractModule {
@Override
protected void configure() {
install(new ModuleB());
install(new ModuleC());
}
}
public static class ModuleB extends AbstractModule {
@Override
protected void configure() {
install(new ModuleC());
}
}
public static class ModuleC extends AbstractModule {
@Override
protected void configure() {
bind(String.class).toInstance("Hello world");
}
@Override
public int hashCode() {
return ModuleC.class.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj.getClass().equals(getClass());
}
}
@Test
public void testTraceModules() {
InjectorBuilder
.fromModule(new ModuleA())
.traceEachElement(new ModuleSourceTracingVisitor())
.createInjector();
}
}
| 5,497 |
0 | Create_ds/governator/governator-core/src/test/java/com/netflix | Create_ds/governator/governator-core/src/test/java/com/netflix/governator/AutoBindSingletonTest.java | package com.netflix.governator;
import com.google.inject.AbstractModule;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.Matchers;
import com.google.inject.spi.ProvisionListener;
import com.netflix.governator.package1.AutoBindSingletonConcrete;
import com.netflix.governator.package1.AutoBindSingletonInterface;
import com.netflix.governator.package1.AutoBindSingletonMultiBinding;
import com.netflix.governator.package1.AutoBindSingletonWithInterface;
import com.netflix.governator.package1.FooModule;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
public class AutoBindSingletonTest {
@Test
public void confirmBindingsCreatedForAutoBindSinglton() {
final Set<Class> created = new HashSet<>();
try (LifecycleInjector injector = InjectorBuilder.fromModules(
new ScanningModuleBuilder()
.forPackages("com.netflix.governator.package1", "com.netflix")
.addScanner(new AutoBindSingletonAnnotatedClassScanner())
.build(),
new AbstractModule() {
@Override
protected void configure() {
bindListener(Matchers.any(), new ProvisionListener() {
@Override
public <T> void onProvision(ProvisionInvocation<T> provision) {
Class<?> type = provision.getBinding().getKey().getTypeLiteral().getRawType();
if (type != null && type.getName().startsWith("com.netflix.governator.package1")) {
created.add(type);
}
}
});
}
})
.createInjector()) {
Assert.assertTrue(created.contains(AutoBindSingletonConcrete.class));
injector.getInstance(Key.get(new TypeLiteral<Set<AutoBindSingletonInterface>>() {}));
injector.getInstance(Key.get(AutoBindSingletonInterface.class));
Assert.assertTrue(created.contains(AutoBindSingletonMultiBinding.class));
Assert.assertTrue(created.contains(AutoBindSingletonWithInterface.class));
Assert.assertEquals(injector.getInstance(String.class), "AutoBound");
}
}
@Test
public void confirmNoBindingsForExcludedClass() {
try (LifecycleInjector injector = InjectorBuilder.fromModules(
new ScanningModuleBuilder()
.forPackages("com.netflix.governator.package1")
.addScanner(new AutoBindSingletonAnnotatedClassScanner())
.excludeClasses(AutoBindSingletonConcrete.class)
.build())
.createInjector()) {
Assert.assertNull(injector.getExistingBinding(Key.get(AutoBindSingletonConcrete.class)));
}
}
@Test
public void confirmModuleDedupingWorksWithScannedClasse() {
try (LifecycleInjector injector = InjectorBuilder.fromModules(
new ScanningModuleBuilder()
.forPackages("com.netflix.governator.package1")
.addScanner(new AutoBindSingletonAnnotatedClassScanner())
.excludeClasses(AutoBindSingletonConcrete.class)
.build(),
new FooModule()
)
.createInjector()) {
Assert.assertNull(injector.getExistingBinding(Key.get(AutoBindSingletonConcrete.class)));
}
}
}
| 5,498 |
0 | Create_ds/governator/governator-core/src/test/java/com/netflix | Create_ds/governator/governator-core/src/test/java/com/netflix/governator/AssistedInjectPreDestroyTest.java | package com.netflix.governator;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import com.google.inject.Module;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.netflix.governator.InjectorBuilder;
import com.netflix.governator.LifecycleInjector;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AssistedInjectPreDestroyTest {
private final Logger log = LoggerFactory.getLogger(getClass());
@Test
public void testAssistedInject() throws Exception {
Module assistedInjectModule = new FactoryModuleBuilder()
.implement(AnInterestingClient.class, InterestingClientImpl.class)
.build(InterestingClientFactory.class);
final AnInterestingClient interestingClient;
try (LifecycleInjector injector = InjectorBuilder.fromModule(assistedInjectModule).createInjector()) {
interestingClient = injector.getInstance(InterestingClientFactory.class).create("something");
log.info("Init is all done, I'll pretend to be doing something for a bit");
Thread.sleep(1_000L);
Assert.assertFalse(interestingClient.isClosed());
log.info("Kicking the GC to see if it triggers unintended cleanups");
System.gc();
Thread.sleep(1_000L);
Assert.assertFalse(interestingClient.isClosed());
log.info("Just woke up again, about to close shop");
interestingClient.setOkToClose();
}
// injector is closed by try block exit above, which triggers PreDestroy /
// AutoCloseable methods
Assert.assertTrue(interestingClient.isClosed());
log.info("Done closing shop, bye");
}
}
interface AnInterestingClient {
void setOkToClose();
boolean isClosed();
}
class InterestingClientImpl implements AnInterestingClient {
private static final Logger logger = LoggerFactory.getLogger(InterestingClientImpl.class);
private final AtomicBoolean isOkToClose = new AtomicBoolean(false);
private final AtomicBoolean closedBeforeExpected = new AtomicBoolean(false);
private final AtomicBoolean closed = new AtomicBoolean(false);
@Inject
InterestingClientImpl(@Assisted String aParameter) {
}
@Override
public void setOkToClose() {
if (closedBeforeExpected.get()) {
throw new IllegalStateException("Someone called close before we were ready!");
}
isOkToClose.set(true);
}
@Override
public boolean isClosed() {
return closed.get();
}
@PreDestroy
public void close() {
closed.set(true);
if (!isOkToClose.get()) {
closedBeforeExpected.set(true);
logger.info("Someone called close() on me ({}) and I'm mad about it", this);
} else {
logger.info("Someone called close() on me ({}) and I'm ok with that", this);
}
}
}
interface InterestingClientFactory {
AnInterestingClient create(@Assisted String aParameter);
}
| 5,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.