proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/mapper/LinkMapper.java
|
LinkMapper
|
mapLinks
|
class LinkMapper {
private static final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
private LinkMapper() {
}
/**
* Map the specified links to a json model. If several links share the same relation,
* they are grouped together.
* @param links the links to map
* @return a model for the specified links
*/
public static ObjectNode mapLinks(List<Link> links) {<FILL_FUNCTION_BODY>}
private static void mapLink(Link link, ObjectNode node) {
node.put("href", link.getHref());
if (link.isTemplated()) {
node.put("templated", true);
}
if (link.getDescription() != null) {
node.put("title", link.getDescription());
}
}
}
|
ObjectNode result = nodeFactory.objectNode();
Map<String, List<Link>> byRel = new LinkedHashMap<>();
links.forEach((it) -> byRel.computeIfAbsent(it.getRel(), (k) -> new ArrayList<>()).add(it));
byRel.forEach((rel, l) -> {
if (l.size() == 1) {
ObjectNode root = JsonNodeFactory.instance.objectNode();
mapLink(l.get(0), root);
result.set(rel, root);
}
else {
ArrayNode root = JsonNodeFactory.instance.arrayNode();
l.forEach((link) -> {
ObjectNode node = JsonNodeFactory.instance.objectNode();
mapLink(link, node);
root.add(node);
});
result.set(rel, root);
}
});
return result;
| 210
| 236
| 446
|
<no_super_class>
|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/project/DefaultProjectRequestToDescriptionConverter.java
|
DefaultProjectRequestToDescriptionConverter
|
validatePackaging
|
class DefaultProjectRequestToDescriptionConverter
implements ProjectRequestToDescriptionConverter<ProjectRequest> {
private final ProjectRequestPlatformVersionTransformer platformVersionTransformer;
public DefaultProjectRequestToDescriptionConverter() {
this((version, metadata) -> version);
}
public DefaultProjectRequestToDescriptionConverter(
ProjectRequestPlatformVersionTransformer platformVersionTransformer) {
Assert.notNull(platformVersionTransformer, "PlatformVersionTransformer must not be null");
this.platformVersionTransformer = platformVersionTransformer;
}
@Override
public ProjectDescription convert(ProjectRequest request, InitializrMetadata metadata) {
MutableProjectDescription description = new MutableProjectDescription();
convert(request, description, metadata);
return description;
}
/**
* Validate the specified {@link ProjectRequest request} and initialize the specified
* {@link ProjectDescription description}. Override any attribute of the description
* that are managed by this instance.
* @param request the request to validate
* @param description the description to initialize
* @param metadata the metadata instance to use to apply defaults if necessary
*/
public void convert(ProjectRequest request, MutableProjectDescription description, InitializrMetadata metadata) {
validate(request, metadata);
Version platformVersion = getPlatformVersion(request, metadata);
List<Dependency> resolvedDependencies = getResolvedDependencies(request, platformVersion, metadata);
validateDependencyRange(platformVersion, resolvedDependencies);
description.setApplicationName(request.getApplicationName());
description.setArtifactId(cleanInputValue(request.getArtifactId()));
description.setBaseDirectory(request.getBaseDir());
description.setBuildSystem(getBuildSystem(request, metadata));
description.setDescription(request.getDescription());
description.setGroupId(cleanInputValue(request.getGroupId()));
description.setLanguage(Language.forId(request.getLanguage(), request.getJavaVersion()));
description.setName(cleanInputValue(request.getName()));
description.setPackageName(cleanInputValue(request.getPackageName()));
description.setPackaging(Packaging.forId(request.getPackaging()));
description.setPlatformVersion(platformVersion);
description.setVersion(request.getVersion());
resolvedDependencies.forEach((dependency) -> description.addDependency(dependency.getId(),
MetadataBuildItemMapper.toDependency(dependency)));
}
/**
* Clean input value to rely on US-ascii character as much as possible.
* @param value the input value to clean
* @return a value that can be used as part of an identifier
*/
protected String cleanInputValue(String value) {
return StringUtils.hasText(value) ? Normalizer.normalize(value, Normalizer.Form.NFKD).replaceAll("\\p{M}", "")
: value;
}
private void validate(ProjectRequest request, InitializrMetadata metadata) {
validatePlatformVersion(request, metadata);
validateType(request.getType(), metadata);
validateLanguage(request.getLanguage(), metadata);
validatePackaging(request.getPackaging(), metadata);
validateDependencies(request, metadata);
}
private void validatePlatformVersion(ProjectRequest request, InitializrMetadata metadata) {
Version platformVersion = Version.safeParse(request.getBootVersion());
Platform platform = metadata.getConfiguration().getEnv().getPlatform();
if (platformVersion != null && !platform.isCompatibleVersion(platformVersion)) {
throw new InvalidProjectRequestException("Invalid Spring Boot version '" + platformVersion
+ "', Spring Boot compatibility range is " + platform.determineCompatibilityRangeRequirement());
}
}
private void validateType(String type, InitializrMetadata metadata) {
if (type != null) {
Type typeFromMetadata = metadata.getTypes().get(type);
if (typeFromMetadata == null) {
throw new InvalidProjectRequestException("Unknown type '" + type + "' check project metadata");
}
if (!typeFromMetadata.getTags().containsKey("build")) {
throw new InvalidProjectRequestException(
"Invalid type '" + type + "' (missing build tag) check project metadata");
}
}
}
private void validateLanguage(String language, InitializrMetadata metadata) {
if (language != null) {
DefaultMetadataElement languageFromMetadata = metadata.getLanguages().get(language);
if (languageFromMetadata == null) {
throw new InvalidProjectRequestException("Unknown language '" + language + "' check project metadata");
}
}
}
private void validatePackaging(String packaging, InitializrMetadata metadata) {<FILL_FUNCTION_BODY>}
private void validateDependencies(ProjectRequest request, InitializrMetadata metadata) {
List<String> dependencies = request.getDependencies();
dependencies.forEach((dep) -> {
Dependency dependency = metadata.getDependencies().get(dep);
if (dependency == null) {
throw new InvalidProjectRequestException("Unknown dependency '" + dep + "' check project metadata");
}
});
}
private void validateDependencyRange(Version platformVersion, List<Dependency> resolvedDependencies) {
resolvedDependencies.forEach((dep) -> {
if (!dep.match(platformVersion)) {
throw new InvalidProjectRequestException(
"Dependency '" + dep.getId() + "' is not compatible " + "with Spring Boot " + platformVersion);
}
});
}
private BuildSystem getBuildSystem(ProjectRequest request, InitializrMetadata metadata) {
Map<String, String> typeTags = metadata.getTypes().get(request.getType()).getTags();
String id = typeTags.get("build");
String dialect = typeTags.get("dialect");
return BuildSystem.forIdAndDialect(id, dialect);
}
private Version getPlatformVersion(ProjectRequest request, InitializrMetadata metadata) {
String versionText = (request.getBootVersion() != null) ? request.getBootVersion()
: metadata.getBootVersions().getDefault().getId();
Version version = Version.parse(versionText);
return this.platformVersionTransformer.transform(version, metadata);
}
private List<Dependency> getResolvedDependencies(ProjectRequest request, Version platformVersion,
InitializrMetadata metadata) {
List<String> depIds = request.getDependencies();
return depIds.stream().map((it) -> {
Dependency dependency = metadata.getDependencies().get(it);
return dependency.resolve(platformVersion);
}).collect(Collectors.toList());
}
}
|
if (packaging != null) {
DefaultMetadataElement packagingFromMetadata = metadata.getPackagings().get(packaging);
if (packagingFromMetadata == null) {
throw new InvalidProjectRequestException(
"Unknown packaging '" + packaging + "' check project metadata");
}
}
| 1,639
| 78
| 1,717
|
<no_super_class>
|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/project/MetadataProjectDescriptionCustomizer.java
|
MetadataProjectDescriptionCustomizer
|
customize
|
class MetadataProjectDescriptionCustomizer implements ProjectDescriptionCustomizer {
private static final char[] VALID_MAVEN_SPECIAL_CHARACTERS = new char[] { '_', '-', '.' };
private final InitializrMetadata metadata;
public MetadataProjectDescriptionCustomizer(InitializrMetadata metadata) {
this.metadata = metadata;
}
@Override
public void customize(MutableProjectDescription description) {<FILL_FUNCTION_BODY>}
private String cleanMavenCoordinate(String coordinate, String delimiter) {
String[] elements = coordinate.split("[^\\w\\-.]+");
if (elements.length == 1) {
return coordinate;
}
StringBuilder builder = new StringBuilder();
for (String element : elements) {
if (shouldAppendDelimiter(element, builder)) {
builder.append(delimiter);
}
builder.append(element);
}
return builder.toString();
}
private boolean shouldAppendDelimiter(String element, StringBuilder builder) {
if (builder.length() == 0) {
return false;
}
for (char c : VALID_MAVEN_SPECIAL_CHARACTERS) {
int prevIndex = builder.length() - 1;
if (element.charAt(0) == c || builder.charAt(prevIndex) == c) {
return false;
}
}
return true;
}
private String determineValue(String candidate, Supplier<String> fallback) {
return (StringUtils.hasText(candidate)) ? candidate : fallback.get();
}
}
|
if (!StringUtils.hasText(description.getApplicationName())) {
description
.setApplicationName(this.metadata.getConfiguration().generateApplicationName(description.getName()));
}
String targetArtifactId = determineValue(description.getArtifactId(),
() -> this.metadata.getArtifactId().getContent());
description.setArtifactId(cleanMavenCoordinate(targetArtifactId, "-"));
if (targetArtifactId.equals(description.getBaseDirectory())) {
description.setBaseDirectory(cleanMavenCoordinate(targetArtifactId, "-"));
}
if (!StringUtils.hasText(description.getDescription())) {
description.setDescription(this.metadata.getDescription().getContent());
}
String targetGroupId = determineValue(description.getGroupId(), () -> this.metadata.getGroupId().getContent());
description.setGroupId(cleanMavenCoordinate(targetGroupId, "."));
if (!StringUtils.hasText(description.getName())) {
description.setName(this.metadata.getName().getContent());
}
else if (targetArtifactId.equals(description.getName())) {
description.setName(cleanMavenCoordinate(targetArtifactId, "-"));
}
description.setPackageName(this.metadata.getConfiguration()
.cleanPackageName(description.getPackageName(), this.metadata.getPackageName().getContent()));
if (description.getPlatformVersion() == null) {
description.setPlatformVersion(Version.parse(this.metadata.getBootVersions().getDefault().getId()));
}
if (!StringUtils.hasText(description.getVersion())) {
description.setVersion(this.metadata.getVersion().getContent());
}
| 405
| 437
| 842
|
<no_super_class>
|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/project/ProjectGenerationInvoker.java
|
ProjectGenerationInvoker
|
generateBuild
|
class ProjectGenerationInvoker<R extends ProjectRequest> {
private final ApplicationContext parentApplicationContext;
private final ApplicationEventPublisher eventPublisher;
private final ProjectRequestToDescriptionConverter<R> requestConverter;
private final ProjectAssetGenerator<Path> projectAssetGenerator = new DefaultProjectAssetGenerator();
private final transient Map<Path, List<Path>> temporaryFiles = new ConcurrentHashMap<>();
public ProjectGenerationInvoker(ApplicationContext parentApplicationContext,
ProjectRequestToDescriptionConverter<R> requestConverter) {
this(parentApplicationContext, parentApplicationContext, requestConverter);
}
protected ProjectGenerationInvoker(ApplicationContext parentApplicationContext,
ApplicationEventPublisher eventPublisher, ProjectRequestToDescriptionConverter<R> requestConverter) {
this.parentApplicationContext = parentApplicationContext;
this.eventPublisher = eventPublisher;
this.requestConverter = requestConverter;
}
/**
* Invokes the project generation API that generates the entire project structure for
* the specified {@link ProjectRequest}.
* @param request the project request
* @return the {@link ProjectGenerationResult}
*/
public ProjectGenerationResult invokeProjectStructureGeneration(R request) {
InitializrMetadata metadata = this.parentApplicationContext.getBean(InitializrMetadataProvider.class).get();
try {
ProjectDescription description = this.requestConverter.convert(request, metadata);
ProjectGenerator projectGenerator = new ProjectGenerator((
projectGenerationContext) -> customizeProjectGenerationContext(projectGenerationContext, metadata));
ProjectGenerationResult result = projectGenerator.generate(description,
generateProject(description, request));
addTempFile(result.getRootDirectory(), result.getRootDirectory());
return result;
}
catch (ProjectGenerationException ex) {
publishProjectFailedEvent(request, metadata, ex);
throw ex;
}
}
private ProjectAssetGenerator<ProjectGenerationResult> generateProject(ProjectDescription description, R request) {
return (context) -> {
Path projectDir = getProjectAssetGenerator(description).generate(context);
publishProjectGeneratedEvent(request, context);
return new ProjectGenerationResult(context.getBean(ProjectDescription.class), projectDir);
};
}
/**
* Return the {@link ProjectAssetGenerator} to use to generate the project structure
* for the specified {@link ProjectDescription}.
* @param description the project description
* @return an asset generator for the specified request
*/
protected ProjectAssetGenerator<Path> getProjectAssetGenerator(ProjectDescription description) {
return this.projectAssetGenerator;
}
/**
* Invokes the project generation API that knows how to just write the build file.
* Returns a directory containing the project for the specified
* {@link ProjectRequest}.
* @param request the project request
* @return the generated build content
*/
public byte[] invokeBuildGeneration(R request) {
InitializrMetadata metadata = this.parentApplicationContext.getBean(InitializrMetadataProvider.class).get();
try {
ProjectDescription description = this.requestConverter.convert(request, metadata);
ProjectGenerator projectGenerator = new ProjectGenerator((
projectGenerationContext) -> customizeProjectGenerationContext(projectGenerationContext, metadata));
return projectGenerator.generate(description, generateBuild(request));
}
catch (ProjectGenerationException ex) {
publishProjectFailedEvent(request, metadata, ex);
throw ex;
}
}
private ProjectAssetGenerator<byte[]> generateBuild(R request) {
return (context) -> {
byte[] content = generateBuild(context);
publishProjectGeneratedEvent(request, context);
return content;
};
}
/**
* Create a file in the same directory as the given directory using the directory name
* and extension.
* @param dir the directory used to determine the path and name of the new file
* @param extension the extension to use for the new file
* @return the newly created file
*/
public Path createDistributionFile(Path dir, String extension) {
Path download = dir.resolveSibling(dir.getFileName() + extension);
addTempFile(dir, download);
return download;
}
private void addTempFile(Path group, Path file) {
this.temporaryFiles.compute(group, (path, paths) -> {
List<Path> newPaths = (paths != null) ? paths : new ArrayList<>();
newPaths.add(file);
return newPaths;
});
}
/**
* Clean all the temporary files that are related to this root directory.
* @param dir the directory to clean
* @see #createDistributionFile
*/
public void cleanTempFiles(Path dir) {
List<Path> tempFiles = this.temporaryFiles.remove(dir);
if (!tempFiles.isEmpty()) {
tempFiles.forEach((path) -> {
try {
FileSystemUtils.deleteRecursively(path);
}
catch (IOException ex) {
// Continue
}
});
}
}
private byte[] generateBuild(ProjectGenerationContext context) throws IOException {<FILL_FUNCTION_BODY>}
private void customizeProjectGenerationContext(AnnotationConfigApplicationContext context,
InitializrMetadata metadata) {
context.setParent(this.parentApplicationContext);
context.registerBean(InitializrMetadata.class, () -> metadata);
context.registerBean(BuildItemResolver.class, () -> new MetadataBuildItemResolver(metadata,
context.getBean(ProjectDescription.class).getPlatformVersion()));
context.registerBean(MetadataProjectDescriptionCustomizer.class,
() -> new MetadataProjectDescriptionCustomizer(metadata));
}
private void publishProjectGeneratedEvent(R request, ProjectGenerationContext context) {
InitializrMetadata metadata = context.getBean(InitializrMetadata.class);
ProjectGeneratedEvent event = new ProjectGeneratedEvent(request, metadata);
this.eventPublisher.publishEvent(event);
}
private void publishProjectFailedEvent(R request, InitializrMetadata metadata, Exception cause) {
ProjectFailedEvent event = new ProjectFailedEvent(request, metadata, cause);
this.eventPublisher.publishEvent(event);
}
}
|
ProjectDescription description = context.getBean(ProjectDescription.class);
StringWriter out = new StringWriter();
BuildWriter buildWriter = context.getBeanProvider(BuildWriter.class).getIfAvailable();
if (buildWriter != null) {
buildWriter.writeBuild(out);
return out.toString().getBytes();
}
else {
throw new IllegalStateException("No BuildWriter implementation found for " + description.getLanguage());
}
| 1,579
| 117
| 1,696
|
<no_super_class>
|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/project/ProjectRequest.java
|
ProjectRequest
|
getPackageName
|
class ProjectRequest {
private List<String> dependencies = new ArrayList<>();
private String name;
private String type;
private String description;
private String groupId;
private String artifactId;
private String version;
private String bootVersion;
private String packaging;
private String applicationName;
private String language;
private String packageName;
private String javaVersion;
// The base directory to create in the archive - no baseDir by default
private String baseDir;
public List<String> getDependencies() {
return this.dependencies;
}
public void setDependencies(List<String> dependencies) {
this.dependencies = dependencies;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getGroupId() {
return this.groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getArtifactId() {
return this.artifactId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public String getBootVersion() {
return this.bootVersion;
}
public void setBootVersion(String bootVersion) {
this.bootVersion = bootVersion;
}
public String getPackaging() {
return this.packaging;
}
public void setPackaging(String packaging) {
this.packaging = packaging;
}
public String getApplicationName() {
return this.applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getLanguage() {
return this.language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getPackageName() {<FILL_FUNCTION_BODY>}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getJavaVersion() {
return this.javaVersion;
}
public void setJavaVersion(String javaVersion) {
this.javaVersion = javaVersion;
}
public String getBaseDir() {
return this.baseDir;
}
public void setBaseDir(String baseDir) {
this.baseDir = baseDir;
}
}
|
if (StringUtils.hasText(this.packageName)) {
return this.packageName;
}
if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) {
return getGroupId() + "." + getArtifactId();
}
return null;
| 710
| 80
| 790
|
<no_super_class>
|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/project/WebProjectRequest.java
|
WebProjectRequest
|
initialize
|
class WebProjectRequest extends ProjectRequest {
private final Map<String, Object> parameters = new LinkedHashMap<>();
/**
* Return the additional parameters that can be used to further identify the request.
* @return the parameters
*/
public Map<String, Object> getParameters() {
return this.parameters;
}
/**
* Initialize the state of this request with defaults defined in the
* {@link InitializrMetadata metadata}.
* @param metadata the metadata to use
*/
public void initialize(InitializrMetadata metadata) {<FILL_FUNCTION_BODY>}
}
|
BeanWrapperImpl bean = new BeanWrapperImpl(this);
metadata.defaults().forEach((key, value) -> {
if (bean.isWritableProperty(key)) {
// We want to be able to infer a package name if none has been
// explicitly set
if (!key.equals("packageName")) {
bean.setPropertyValue(key, value);
}
}
});
| 147
| 106
| 253
|
<methods>public non-sealed void <init>() ,public java.lang.String getApplicationName() ,public java.lang.String getArtifactId() ,public java.lang.String getBaseDir() ,public java.lang.String getBootVersion() ,public List<java.lang.String> getDependencies() ,public java.lang.String getDescription() ,public java.lang.String getGroupId() ,public java.lang.String getJavaVersion() ,public java.lang.String getLanguage() ,public java.lang.String getName() ,public java.lang.String getPackageName() ,public java.lang.String getPackaging() ,public java.lang.String getType() ,public java.lang.String getVersion() ,public void setApplicationName(java.lang.String) ,public void setArtifactId(java.lang.String) ,public void setBaseDir(java.lang.String) ,public void setBootVersion(java.lang.String) ,public void setDependencies(List<java.lang.String>) ,public void setDescription(java.lang.String) ,public void setGroupId(java.lang.String) ,public void setJavaVersion(java.lang.String) ,public void setLanguage(java.lang.String) ,public void setName(java.lang.String) ,public void setPackageName(java.lang.String) ,public void setPackaging(java.lang.String) ,public void setType(java.lang.String) ,public void setVersion(java.lang.String) <variables>private java.lang.String applicationName,private java.lang.String artifactId,private java.lang.String baseDir,private java.lang.String bootVersion,private List<java.lang.String> dependencies,private java.lang.String description,private java.lang.String groupId,private java.lang.String javaVersion,private java.lang.String language,private java.lang.String name,private java.lang.String packageName,private java.lang.String packaging,private java.lang.String type,private java.lang.String version
|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/support/Agent.java
|
UserAgentHandler
|
parse
|
class UserAgentHandler {
private static final Pattern TOOL_REGEX = Pattern.compile("([^\\/]*)\\/([^ ]*).*");
private static final Pattern STS_REGEX = Pattern.compile("STS (.*)");
private static final Pattern NETBEANS_REGEX = Pattern.compile("nb-springboot-plugin\\/(.*)");
static Agent parse(String userAgent) {<FILL_FUNCTION_BODY>}
}
|
Matcher matcher = TOOL_REGEX.matcher(userAgent);
if (matcher.matches()) {
String name = matcher.group(1);
for (AgentId id : AgentId.values()) {
if (name.equals(id.name)) {
String version = matcher.group(2);
return new Agent(id, version);
}
}
}
matcher = STS_REGEX.matcher(userAgent);
if (matcher.matches()) {
return new Agent(AgentId.STS, matcher.group(1));
}
matcher = NETBEANS_REGEX.matcher(userAgent);
if (matcher.matches()) {
return new Agent(AgentId.NETBEANS, matcher.group(1));
}
if (userAgent.equals(AgentId.INTELLIJ_IDEA.name)) {
return new Agent(AgentId.INTELLIJ_IDEA, null);
}
if (userAgent.contains("Mozilla/5.0")) { // Super heuristics
return new Agent(AgentId.BROWSER, null);
}
return null;
| 124
| 304
| 428
|
<no_super_class>
|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/support/DefaultDependencyMetadataProvider.java
|
DefaultDependencyMetadataProvider
|
get
|
class DefaultDependencyMetadataProvider implements DependencyMetadataProvider {
@Override
@Cacheable(cacheNames = "initializr.dependency-metadata", key = "#p1")
public DependencyMetadata get(InitializrMetadata metadata, Version bootVersion) {<FILL_FUNCTION_BODY>}
}
|
Map<String, Dependency> dependencies = new LinkedHashMap<>();
for (Dependency dependency : metadata.getDependencies().getAll()) {
if (dependency.match(bootVersion)) {
dependencies.put(dependency.getId(), dependency.resolve(bootVersion));
}
}
Map<String, Repository> repositories = new LinkedHashMap<>();
for (Dependency dependency : dependencies.values()) {
if (dependency.getRepository() != null) {
repositories.put(dependency.getRepository(),
metadata.getConfiguration().getEnv().getRepositories().get(dependency.getRepository()));
}
}
Map<String, BillOfMaterials> boms = new LinkedHashMap<>();
for (Dependency dependency : dependencies.values()) {
if (dependency.getBom() != null) {
boms.put(dependency.getBom(),
metadata.getConfiguration().getEnv().getBoms().get(dependency.getBom()).resolve(bootVersion));
}
}
// Each resolved bom may require additional repositories
for (BillOfMaterials bom : boms.values()) {
for (String id : bom.getRepositories()) {
repositories.put(id, metadata.getConfiguration().getEnv().getRepositories().get(id));
}
}
return new DependencyMetadata(bootVersion, dependencies, repositories, boms);
| 74
| 363
| 437
|
<no_super_class>
|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/support/SpringBootMetadataReader.java
|
SpringBootMetadataReader
|
getBootVersions
|
class SpringBootMetadataReader {
private static final Comparator<DefaultMetadataElement> VERSION_METADATA_ELEMENT_COMPARATOR = new VersionMetadataElementComparator();
private final JsonNode content;
/**
* Parse the content of the metadata at the specified url.
* @param objectMapper the object mapper
* @param restTemplate the rest template
* @param url the metadata URL
* @throws IOException on load error
*/
SpringBootMetadataReader(ObjectMapper objectMapper, RestTemplate restTemplate, String url) throws IOException {
this.content = objectMapper.readTree(restTemplate.getForObject(url, String.class));
}
/**
* Return the boot versions parsed by this instance.
* @return the versions
*/
List<DefaultMetadataElement> getBootVersions() {<FILL_FUNCTION_BODY>}
private DefaultMetadataElement parseVersionMetadata(JsonNode node) {
String versionId = node.get("version").textValue();
Version version = VersionParser.DEFAULT.safeParse(versionId);
if (version == null) {
return null;
}
DefaultMetadataElement versionMetadata = new DefaultMetadataElement();
versionMetadata.setId(versionId);
versionMetadata.setName(determineDisplayName(version));
versionMetadata.setDefault(node.get("current").booleanValue());
return versionMetadata;
}
private String determineDisplayName(Version version) {
StringBuilder sb = new StringBuilder();
sb.append(version.getMajor()).append(".").append(version.getMinor()).append(".").append(version.getPatch());
if (version.getQualifier() != null) {
sb.append(determineSuffix(version.getQualifier()));
}
return sb.toString();
}
private String determineSuffix(Qualifier qualifier) {
String id = qualifier.getId();
if (id.equals("RELEASE")) {
return "";
}
StringBuilder sb = new StringBuilder(" (");
if (id.contains("SNAPSHOT")) {
sb.append("SNAPSHOT");
}
else {
sb.append(id);
if (qualifier.getVersion() != null) {
sb.append(qualifier.getVersion());
}
}
sb.append(")");
return sb.toString();
}
private static final class VersionMetadataElementComparator implements Comparator<DefaultMetadataElement> {
private static final VersionParser versionParser = VersionParser.DEFAULT;
@Override
public int compare(DefaultMetadataElement o1, DefaultMetadataElement o2) {
Version o1Version = versionParser.parse(o1.getId());
Version o2Version = versionParser.parse(o2.getId());
return o1Version.compareTo(o2Version);
}
}
}
|
ArrayNode releases = (ArrayNode) this.content.get("_embedded").get("releases");
List<DefaultMetadataElement> list = new ArrayList<>();
for (JsonNode node : releases) {
DefaultMetadataElement versionMetadata = parseVersionMetadata(node);
if (versionMetadata != null) {
list.add(versionMetadata);
}
}
list.sort(VERSION_METADATA_ELEMENT_COMPARATOR.reversed());
return list;
| 725
| 127
| 852
|
<no_super_class>
|
spring-io_initializr
|
initializr/initializr-web/src/main/java/io/spring/initializr/web/support/SpringIoInitializrMetadataUpdateStrategy.java
|
SpringIoInitializrMetadataUpdateStrategy
|
update
|
class SpringIoInitializrMetadataUpdateStrategy implements InitializrMetadataUpdateStrategy {
private static final Log logger = LogFactory.getLog(SpringIoInitializrMetadataUpdateStrategy.class);
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
public SpringIoInitializrMetadataUpdateStrategy(RestTemplate restTemplate, ObjectMapper objectMapper) {
this.restTemplate = restTemplate;
this.objectMapper = objectMapper;
}
@Override
public InitializrMetadata update(InitializrMetadata current) {<FILL_FUNCTION_BODY>}
/**
* Fetch the available Spring Boot versions using the specified service url.
* @param url the url to the spring-boot project metadata
* @return the spring boot versions metadata or {@code null} if it could not be
* retrieved
*/
protected List<DefaultMetadataElement> fetchSpringBootVersions(String url) {
if (StringUtils.hasText(url)) {
try {
logger.info("Fetching Spring Boot metadata from " + url);
return new SpringBootMetadataReader(this.objectMapper, this.restTemplate, url).getBootVersions();
}
catch (Exception ex) {
logger.warn("Failed to fetch Spring Boot metadata", ex);
}
}
return null;
}
}
|
String url = current.getConfiguration().getEnv().getSpringBootMetadataUrl();
List<DefaultMetadataElement> bootVersions = fetchSpringBootVersions(url);
if (bootVersions != null && !bootVersions.isEmpty()) {
if (bootVersions.stream().noneMatch(DefaultMetadataElement::isDefault)) {
// No default specified
bootVersions.get(0).setDefault(true);
}
current.updateSpringBootVersions(bootVersions);
}
return current;
| 329
| 134
| 463
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/Base64Variants.java
|
Base64Variants
|
valueOf
|
class Base64Variants
{
final static String STD_BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* This variant is what most people would think of "the standard"
* Base64 encoding.
*<p>
* See <a href="http://en.wikipedia.org/wiki/Base64">wikipedia Base64 entry</a> for details.
*<p>
* Note that although this can be thought of as the standard variant,
* it is <b>not</b> the default for Jackson: no-linefeeds alternative
* is instead used because of JSON requirement of escaping all linefeeds.
*<p>
* Writes padding on output; requires padding when reading (may change later with a call to {@link Base64Variant#withWritePadding})
*/
public final static Base64Variant MIME;
static {
MIME = new Base64Variant("MIME", STD_BASE64_ALPHABET, true, '=', 76);
}
/**
* Slightly non-standard modification of {@link #MIME} which does not
* use linefeeds (max line length set to infinite). Useful when linefeeds
* wouldn't work well (possibly in attributes), or for minor space savings
* (save 1 linefeed per 76 data chars, ie. ~1.4% savings).
*<p>
* Writes padding on output; requires padding when reading (may change later with a call to {@link Base64Variant#withWritePadding})
*/
public final static Base64Variant MIME_NO_LINEFEEDS;
static {
MIME_NO_LINEFEEDS = new Base64Variant(MIME, "MIME-NO-LINEFEEDS", Integer.MAX_VALUE);
}
/**
* This variant is the one that predates {@link #MIME}: it is otherwise
* identical, except that it mandates shorter line length.
*<p>
* Writes padding on output; requires padding when reading (may change later with a call to {@link Base64Variant#withWritePadding})
*/
public final static Base64Variant PEM = new Base64Variant(MIME, "PEM", true, '=', 64);
/**
* This non-standard variant is usually used when encoded data needs to be
* passed via URLs (such as part of GET request). It differs from the
* base {@link #MIME} variant in multiple ways.
* First, no padding is used: this also means that it generally can not
* be written in multiple separate but adjacent chunks (which would not
* be the usual use case in any case). Also, no linefeeds are used (max
* line length set to infinite). And finally, two characters (plus and
* slash) that would need quoting in URLs are replaced with more
* optimal alternatives (hyphen and underscore, respectively).
*<p>
* Does not write padding on output; does not accept padding when reading (may change later with a call to {@link Base64Variant#withWritePadding})
*/
public final static Base64Variant MODIFIED_FOR_URL;
static {
StringBuilder sb = new StringBuilder(STD_BASE64_ALPHABET);
// Replace plus with hyphen, slash with underscore (and no padding)
sb.setCharAt(sb.indexOf("+"), '-');
sb.setCharAt(sb.indexOf("/"), '_');
// And finally, let's not split lines either, wouldn't work too well with URLs
MODIFIED_FOR_URL = new Base64Variant("MODIFIED-FOR-URL", sb.toString(), false, Base64Variant.PADDING_CHAR_NONE, Integer.MAX_VALUE);
}
/**
* Method used to get the default variant -- {@link #MIME_NO_LINEFEEDS} -- for cases
* where caller does not explicitly specify the variant.
* We will prefer no-linefeed version because linefeeds in JSON values
* must be escaped, making linefeed-containing variants sub-optimal.
*
* @return Default variant ({@code MIME_NO_LINEFEEDS})
*/
public static Base64Variant getDefaultVariant() {
return MIME_NO_LINEFEEDS;
}
/**
* Lookup method for finding one of standard variants by name.
* If name does not match any of standard variant names,
* a {@link IllegalArgumentException} is thrown.
*
* @param name Name of base64 variant to return
*
* @return Standard base64 variant that matches given {@code name}
*
* @throws IllegalArgumentException if no standard variant with given name exists
*/
public static Base64Variant valueOf(String name) throws IllegalArgumentException
{<FILL_FUNCTION_BODY>}
}
|
if (MIME._name.equals(name)) {
return MIME;
}
if (MIME_NO_LINEFEEDS._name.equals(name)) {
return MIME_NO_LINEFEEDS;
}
if (PEM._name.equals(name)) {
return PEM;
}
if (MODIFIED_FOR_URL._name.equals(name)) {
return MODIFIED_FOR_URL;
}
if (name == null) {
name = "<null>";
} else {
name = "'"+name+"'";
}
throw new IllegalArgumentException("No Base64Variant with name "+name);
| 1,280
| 176
| 1,456
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/ErrorReportConfiguration.java
|
Builder
|
validateMaxErrorTokenLength
|
class Builder {
private int maxErrorTokenLength;
private int maxRawContentLength;
/**
* @param maxErrorTokenLength Maximum error token length setting to use
*
* @return This factory instance (to allow call chaining)
*
* @throws IllegalArgumentException if {@code maxErrorTokenLength} is less than 0
*/
public Builder maxErrorTokenLength(final int maxErrorTokenLength) {
validateMaxErrorTokenLength(maxErrorTokenLength);
this.maxErrorTokenLength = maxErrorTokenLength;
return this;
}
/**
* @param maxRawContentLength Maximum raw content setting to use
*
* @see ErrorReportConfiguration#_maxRawContentLength
*
* @return This builder instance (to allow call chaining)
*/
public Builder maxRawContentLength(final int maxRawContentLength) {
validateMaxRawContentLength(maxRawContentLength);
this.maxRawContentLength = maxRawContentLength;
return this;
}
Builder() {
this(DEFAULT_MAX_ERROR_TOKEN_LENGTH, DEFAULT_MAX_RAW_CONTENT_LENGTH);
}
Builder(final int maxErrorTokenLength, final int maxRawContentLength) {
this.maxErrorTokenLength = maxErrorTokenLength;
this.maxRawContentLength = maxRawContentLength;
}
Builder(ErrorReportConfiguration src) {
this.maxErrorTokenLength = src._maxErrorTokenLength;
this.maxRawContentLength = src._maxRawContentLength;
}
public ErrorReportConfiguration build() {
return new ErrorReportConfiguration(maxErrorTokenLength, maxRawContentLength);
}
}
/*
/**********************************************************************
/* Life-cycle
/**********************************************************************
*/
protected ErrorReportConfiguration(final int maxErrorTokenLength, final int maxRawContentLength) {
_maxErrorTokenLength = maxErrorTokenLength;
_maxRawContentLength = maxRawContentLength;
}
public static Builder builder() {
return new Builder();
}
/**
* @return the default {@link ErrorReportConfiguration} (when none is set on the {@link JsonFactory} explicitly)
* @see #overrideDefaultErrorReportConfiguration(ErrorReportConfiguration)
*/
public static ErrorReportConfiguration defaults() {
return DEFAULT;
}
/**
* @return New {@link Builder} initialized with settings of configuration instance
*/
public Builder rebuild() {
return new Builder(this);
}
/*
/**********************************************************************
/* Accessors
/**********************************************************************
*/
/**
* Accessor for {@link #_maxErrorTokenLength}
*
* @return Maximum length of token to include in error messages
* @see Builder#maxErrorTokenLength(int)
*/
public int getMaxErrorTokenLength() {
return _maxErrorTokenLength;
}
/**
* Accessor for {@link #_maxRawContentLength}
*
* @return Maximum length of token to include in error messages
* @see Builder#maxRawContentLength(int)
*/
public int getMaxRawContentLength() {
return _maxRawContentLength;
}
/*
/**********************************************************************
/* Convenience methods for validation
/**********************************************************************
*/
/**
* Convenience method that can be used verify valid {@link #_maxErrorTokenLength}.
* If invalid value is passed in, {@link IllegalArgumentException} is thrown.
*
* @param maxErrorTokenLength Maximum length of token to include in error messages
*/
static void validateMaxErrorTokenLength(int maxErrorTokenLength) throws IllegalArgumentException {<FILL_FUNCTION_BODY>
|
if (maxErrorTokenLength < 0) {
throw new IllegalArgumentException(
String.format("Value of maxErrorTokenLength (%d) cannot be negative", maxErrorTokenLength));
}
| 934
| 50
| 984
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/JsonProcessingException.java
|
JsonProcessingException
|
getMessage
|
class JsonProcessingException extends JacksonException
{
private final static long serialVersionUID = 123; // eclipse complains otherwise
protected JsonLocation _location;
protected JsonProcessingException(String msg, JsonLocation loc, Throwable rootCause) {
super(msg, rootCause);
_location = loc;
}
protected JsonProcessingException(String msg) {
super(msg);
}
protected JsonProcessingException(String msg, JsonLocation loc) {
this(msg, loc, null);
}
protected JsonProcessingException(String msg, Throwable rootCause) {
this(msg, null, rootCause);
}
protected JsonProcessingException(Throwable rootCause) {
this(null, null, rootCause);
}
/*
/**********************************************************************
/* Extended API
/**********************************************************************
*/
@Override
public JsonLocation getLocation() { return _location; }
/**
* Method that allows to remove context information from this exception's message.
* Useful when you are parsing security-sensitive data and don't want original data excerpts
* to be present in Jackson parser error messages.
*
* @since 2.9
*/
public void clearLocation() { _location = null; }
/**
* Method that allows accessing the original "message" argument,
* without additional decorations (like location information)
* that overridden {@link #getMessage} adds.
*
* @return Original message passed in constructor
*
* @since 2.1
*/
@Override
public String getOriginalMessage() { return super.getMessage(); }
/**
* Method that allows accessing underlying processor that triggered
* this exception; typically either {@link JsonParser} or {@link JsonGenerator}
* for exceptions that originate from streaming API.
* Note that it is possible that `null` may be returned if code throwing
* exception either has no access to processor; or has not been retrofitted
* to set it; this means that caller needs to take care to check for nulls.
* Subtypes override this method with co-variant return type, for more
* type-safe access.
*
* @return Originating processor, if available; null if not.
*
* @since 2.7
*/
@Override
public Object getProcessor() { return null; }
/*
/**********************************************************************
/* Methods for sub-classes to use, override
/**********************************************************************
*/
/**
* Accessor that sub-classes can override to append additional
* information right after the main message, but before
* source location information.
*
* @return Message suffix assigned, if any; {@code null} if none
*/
protected String getMessageSuffix() { return null; }
/*
/**********************************************************************
/* Overrides of standard methods
/**********************************************************************
*/
/**
* Default implementation overridden so that we can add location information
*
* @return Original {@code message} preceded by optional prefix and followed by
* location information, message and location information separated by a linefeed
*/
@Override public String getMessage() {<FILL_FUNCTION_BODY>}
@Override public String toString() { return getClass().getName()+": "+getMessage(); }
}
|
String msg = super.getMessage();
if (msg == null) {
msg = "N/A";
}
JsonLocation loc = getLocation();
String suffix = getMessageSuffix();
// mild optimization, if nothing extra is needed:
if (loc != null || suffix != null) {
StringBuilder sb = new StringBuilder(100);
sb.append(msg);
if (suffix != null) {
sb.append(suffix);
}
if (loc != null) {
sb.append('\n');
sb.append(" at ");
sb.append(loc.toString());
}
msg = sb.toString();
}
return msg;
| 846
| 181
| 1,027
|
<methods>public abstract com.fasterxml.jackson.core.JsonLocation getLocation() ,public abstract java.lang.String getOriginalMessage() ,public abstract java.lang.Object getProcessor() <variables>private static final long serialVersionUID
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/JsonpCharacterEscapes.java
|
JsonpCharacterEscapes
|
getEscapeSequence
|
class JsonpCharacterEscapes extends CharacterEscapes
{
private static final long serialVersionUID = 1L;
private static final int[] asciiEscapes = CharacterEscapes.standardAsciiEscapesForJSON();
private static final SerializedString escapeFor2028 = new SerializedString("\\u2028");
private static final SerializedString escapeFor2029 = new SerializedString("\\u2029");
private static final JsonpCharacterEscapes sInstance = new JsonpCharacterEscapes();
public static JsonpCharacterEscapes instance() {
return sInstance;
}
@Override
public SerializableString getEscapeSequence(int ch)
{<FILL_FUNCTION_BODY>}
@Override
public int[] getEscapeCodesForAscii() {
return asciiEscapes;
}
}
|
switch (ch) {
case 0x2028:
return escapeFor2028;
case 0x2029:
return escapeFor2029;
default:
return null;
}
| 219
| 64
| 283
|
<methods>public non-sealed void <init>() ,public abstract int[] getEscapeCodesForAscii() ,public abstract com.fasterxml.jackson.core.SerializableString getEscapeSequence(int) ,public static int[] standardAsciiEscapesForJSON() <variables>public static final int ESCAPE_CUSTOM,public static final int ESCAPE_NONE,public static final int ESCAPE_STANDARD
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/StreamReadConstraints.java
|
Builder
|
maxNestingDepth
|
class Builder {
private long maxDocLen;
private int maxNestingDepth;
private int maxNumLen;
private int maxStringLen;
private int maxNameLen;
/**
* Sets the maximum nesting depth. The depth is a count of objects and arrays that have not
* been closed, `{` and `[` respectively.
*
* @param maxNestingDepth the maximum depth
*
* @return this builder
* @throws IllegalArgumentException if the maxNestingDepth is set to a negative value
*/
public Builder maxNestingDepth(final int maxNestingDepth) {<FILL_FUNCTION_BODY>}
/**
* Sets the maximum allowed document length (for positive values over 0) or
* indicate that any length is acceptable ({@code 0} or negative number).
* The length is in input units of the input source, that is, in
* {@code byte}s or {@code char}s.
*
* @param maxDocLen the maximum allowed document if positive number above 0; otherwise
* ({@code 0} or negative number) means "unlimited".
*
* @return this builder
*
* @since 2.16
*/
public Builder maxDocumentLength(long maxDocLen) {
// Negative values and 0 mean "unlimited", mark with -1L
if (maxDocLen <= 0L) {
maxDocLen = -1L;
}
this.maxDocLen = maxDocLen;
return this;
}
/**
* Sets the maximum number length (in chars or bytes, depending on input context).
* The default is 1000.
*
* @param maxNumLen the maximum number length (in chars or bytes, depending on input context)
*
* @return this builder
* @throws IllegalArgumentException if the maxNumLen is set to a negative value
*/
public Builder maxNumberLength(final int maxNumLen) {
if (maxNumLen < 0) {
throw new IllegalArgumentException("Cannot set maxNumberLength to a negative value");
}
this.maxNumLen = maxNumLen;
return this;
}
/**
* Sets the maximum string length (in chars or bytes, depending on input context).
* The default is 20,000,000. This limit is not exact, the limit is applied when we increase
* internal buffer sizes and an exception will happen at sizes greater than this limit. Some
* text values that are a little bigger than the limit may be treated as valid but no text
* values with sizes less than or equal to this limit will be treated as invalid.
* <p>
* Setting this value to lower than the {@link #maxNumberLength(int)} is not recommended.
* </p>
*<p>
* NOTE: Jackson 2.15.0 initially used a lower setting (5_000_000).
*
* @param maxStringLen the maximum string length (in chars or bytes, depending on input context)
*
* @return this builder
* @throws IllegalArgumentException if the maxStringLen is set to a negative value
*/
public Builder maxStringLength(final int maxStringLen) {
if (maxStringLen < 0) {
throw new IllegalArgumentException("Cannot set maxStringLen to a negative value");
}
this.maxStringLen = maxStringLen;
return this;
}
/**
* Sets the maximum name length (in chars or bytes, depending on input context).
* The default is 50,000. This limit is not exact, the limit is applied when we increase
* internal buffer sizes and an exception will happen at sizes greater than this limit. Some
* text values that are a little bigger than the limit may be treated as valid but no text
* values with sizes less than or equal to this limit will be treated as invalid.
*
* @param maxNameLen the maximum string length (in chars or bytes, depending on input context)
*
* @return this builder
* @throws IllegalArgumentException if the maxStringLen is set to a negative value
* @since 2.16.0
*/
public Builder maxNameLength(final int maxNameLen) {
if (maxNameLen < 0) {
throw new IllegalArgumentException("Cannot set maxNameLen to a negative value");
}
this.maxNameLen = maxNameLen;
return this;
}
Builder() {
this(DEFAULT_MAX_DEPTH, DEFAULT_MAX_DOC_LEN,
DEFAULT_MAX_NUM_LEN, DEFAULT_MAX_STRING_LEN, DEFAULT_MAX_NAME_LEN);
}
Builder(final int maxNestingDepth, final long maxDocLen,
final int maxNumLen, final int maxStringLen, final int maxNameLen) {
this.maxNestingDepth = maxNestingDepth;
this.maxDocLen = maxDocLen;
this.maxNumLen = maxNumLen;
this.maxStringLen = maxStringLen;
this.maxNameLen = maxNameLen;
}
Builder(StreamReadConstraints src) {
maxNestingDepth = src._maxNestingDepth;
maxDocLen = src._maxDocLen;
maxNumLen = src._maxNumLen;
maxStringLen = src._maxStringLen;
maxNameLen = src._maxNameLen;
}
public StreamReadConstraints build() {
return new StreamReadConstraints(maxNestingDepth, maxDocLen,
maxNumLen, maxStringLen, maxNameLen);
}
}
|
if (maxNestingDepth < 0) {
throw new IllegalArgumentException("Cannot set maxNestingDepth to a negative value");
}
this.maxNestingDepth = maxNestingDepth;
return this;
| 1,402
| 59
| 1,461
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/StreamWriteConstraints.java
|
Builder
|
maxNestingDepth
|
class Builder {
private int maxNestingDepth;
/**
* Sets the maximum nesting depth. The depth is a count of objects and arrays that have not
* been closed, `{` and `[` respectively.
*
* @param maxNestingDepth the maximum depth
*
* @return this builder
* @throws IllegalArgumentException if the maxNestingDepth is set to a negative value
*/
public Builder maxNestingDepth(final int maxNestingDepth) {<FILL_FUNCTION_BODY>}
Builder() {
this(DEFAULT_MAX_DEPTH);
}
Builder(final int maxNestingDepth) {
this.maxNestingDepth = maxNestingDepth;
}
Builder(StreamWriteConstraints src) {
maxNestingDepth = src._maxNestingDepth;
}
public StreamWriteConstraints build() {
return new StreamWriteConstraints(maxNestingDepth);
}
}
|
if (maxNestingDepth < 0) {
throw new IllegalArgumentException("Cannot set maxNestingDepth to a negative value");
}
this.maxNestingDepth = maxNestingDepth;
return this;
| 252
| 59
| 311
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/Version.java
|
Version
|
compareTo
|
class Version
implements Comparable<Version>, java.io.Serializable
{
private static final long serialVersionUID = 1L;
private final static Version UNKNOWN_VERSION = new Version(0, 0, 0, null, null, null);
protected final int _majorVersion;
protected final int _minorVersion;
protected final int _patchLevel;
protected final String _groupId;
protected final String _artifactId;
/**
* Additional information for snapshot versions; null for non-snapshot
* (release) versions.
*/
protected final String _snapshotInfo;
/**
* @param major Major version number
* @param minor Minor version number
* @param patchLevel patch level of version
* @param snapshotInfo Optional additional string qualifier
*
* @since 2.1
* @deprecated Use variant that takes group and artifact ids
*/
@Deprecated
public Version(int major, int minor, int patchLevel, String snapshotInfo)
{
this(major, minor, patchLevel, snapshotInfo, null, null);
}
public Version(int major, int minor, int patchLevel, String snapshotInfo,
String groupId, String artifactId)
{
_majorVersion = major;
_minorVersion = minor;
_patchLevel = patchLevel;
_snapshotInfo = snapshotInfo;
_groupId = (groupId == null) ? "" : groupId;
_artifactId = (artifactId == null) ? "" : artifactId;
}
/**
* Method returns canonical "not known" version, which is used as version
* in cases where actual version information is not known (instead of null).
*
* @return Version instance to use as a placeholder when actual version is not known
* (or not relevant)
*/
public static Version unknownVersion() { return UNKNOWN_VERSION; }
/**
* @return {@code True} if this instance is the one returned by
* call to {@link #unknownVersion()}
*
* @since 2.7 to replace misspelled {@link #isUknownVersion()}
*/
public boolean isUnknownVersion() { return (this == UNKNOWN_VERSION); }
public boolean isSnapshot() {
return (_snapshotInfo != null) && !_snapshotInfo.isEmpty();
}
/**
* @return {@code True} if this instance is the one returned by
* call to {@link #unknownVersion()}
*
* @deprecated Since 2.7 use correctly spelled method {@link #isUnknownVersion()}
*/
@Deprecated
public boolean isUknownVersion() { return isUnknownVersion(); }
public int getMajorVersion() { return _majorVersion; }
public int getMinorVersion() { return _minorVersion; }
public int getPatchLevel() { return _patchLevel; }
public String getGroupId() { return _groupId; }
public String getArtifactId() { return _artifactId; }
public String toFullString() {
return _groupId + '/' + _artifactId + '/' + toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(_majorVersion).append('.');
sb.append(_minorVersion).append('.');
sb.append(_patchLevel);
if (isSnapshot()) {
sb.append('-').append(_snapshotInfo);
}
return sb.toString();
}
@Override
public int hashCode() {
return _artifactId.hashCode() ^ _groupId.hashCode()
^ Objects.hashCode(_snapshotInfo)
+ _majorVersion - _minorVersion + _patchLevel;
}
@Override
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o.getClass() != getClass()) return false;
Version other = (Version) o;
return (other._majorVersion == _majorVersion)
&& (other._minorVersion == _minorVersion)
&& (other._patchLevel == _patchLevel)
&& Objects.equals(other._snapshotInfo, _snapshotInfo)
&& other._artifactId.equals(_artifactId)
&& other._groupId.equals(_groupId)
;
}
@Override
public int compareTo(Version other)
{<FILL_FUNCTION_BODY>}
}
|
if (other == this) return 0;
int diff = _groupId.compareTo(other._groupId);
if (diff == 0) {
diff = _artifactId.compareTo(other._artifactId);
if (diff == 0) {
diff = _majorVersion - other._majorVersion;
if (diff == 0) {
diff = _minorVersion - other._minorVersion;
if (diff == 0) {
diff = _patchLevel - other._patchLevel;
if (diff == 0) {
// Snapshot: non-snapshot AFTER snapshot, otherwise alphabetical
if (isSnapshot()) {
if (other.isSnapshot()) {
diff = _snapshotInfo.compareTo(other._snapshotInfo);
} else {
diff = -1;
}
} else if (other.isSnapshot()) {
diff = 1;
} else {
diff = 0;
}
}
}
}
}
}
return diff;
| 1,120
| 252
| 1,372
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/exc/StreamReadException.java
|
StreamReadException
|
getMessage
|
class StreamReadException
extends JsonProcessingException
{
final static long serialVersionUID = 2L;
protected transient JsonParser _processor;
/**
* Optional payload that can be assigned to pass along for error reporting
* or handling purposes. Core streaming parser implementations DO NOT
* initialize this; it is up to using applications and frameworks to
* populate it.
*/
protected RequestPayload _requestPayload;
// @since 2.15
protected StreamReadException(String msg) {
this(null, msg, null, null);
}
protected StreamReadException(JsonParser p, String msg) {
this(p, msg, _currentLocation(p), null);
}
protected StreamReadException(JsonParser p, String msg, Throwable rootCause) {
this(p, msg, _currentLocation(p), rootCause);
}
protected StreamReadException(JsonParser p, String msg, JsonLocation loc) {
this(p, msg, loc, null);
}
protected StreamReadException(String msg, JsonLocation loc, Throwable rootCause) {
this(null, msg, loc, rootCause);
}
// Canonical constructor
// @since 2.13
protected StreamReadException(JsonParser p, String msg, JsonLocation loc,
Throwable rootCause) {
super(msg, loc, rootCause);
_processor = p;
}
/**
* Fluent method that may be used to assign originating {@link JsonParser},
* to be accessed using {@link #getProcessor()}.
*<p>
* NOTE: `this` instance is modified and no new instance is constructed.
*
* @param p Parser instance to assign to this exception
*
* @return This exception instance to allow call chaining
*/
public abstract StreamReadException withParser(JsonParser p);
/**
* Fluent method that may be used to assign payload to this exception,
* to let recipient access it for diagnostics purposes.
*<p>
* NOTE: `this` instance is modified and no new instance is constructed.
*
* @param payload Payload to assign to this exception
*
* @return This exception instance to allow call chaining
*/
public abstract StreamReadException withRequestPayload(RequestPayload payload);
@Override
public JsonParser getProcessor() {
return _processor;
}
/**
* Method that may be called to find payload that was being parsed, if
* one was specified for parser that threw this Exception.
*
* @return request body, if payload was specified; `null` otherwise
*/
public RequestPayload getRequestPayload() {
return _requestPayload;
}
/**
* The method returns the String representation of the request payload if
* one was specified for parser that threw this Exception.
*
* @return request body as String, if payload was specified; `null` otherwise
*/
public String getRequestPayloadAsString() {
return (_requestPayload != null) ? _requestPayload.toString() : null;
}
/**
* Overriding the getMessage() to include the request body
*/
@Override
public String getMessage() {<FILL_FUNCTION_BODY>}
// @since 2.17
protected static JsonLocation _currentLocation(JsonParser p) {
return (p == null) ? null : p.currentLocation();
}
}
|
String msg = super.getMessage();
if (_requestPayload != null) {
msg += "\nRequest payload : " + _requestPayload.toString();
}
return msg;
| 878
| 50
| 928
|
<methods>public void clearLocation() ,public com.fasterxml.jackson.core.JsonLocation getLocation() ,public java.lang.String getMessage() ,public java.lang.String getOriginalMessage() ,public java.lang.Object getProcessor() ,public java.lang.String toString() <variables>protected com.fasterxml.jackson.core.JsonLocation _location,private static final long serialVersionUID
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/filter/JsonPointerBasedFilter.java
|
JsonPointerBasedFilter
|
includeElement
|
class JsonPointerBasedFilter extends TokenFilter
{
protected final JsonPointer _pathToMatch;
/**
* If true include all array elements by ignoring the array index match and advancing
* the JsonPointer to the next level
*
* @since 2.16
*/
protected final boolean _includeAllElements;
public JsonPointerBasedFilter(String ptrExpr) {
this(JsonPointer.compile(ptrExpr), false);
}
/**
* @param pathToMatch Content to extract
*/
public JsonPointerBasedFilter(JsonPointer pathToMatch) {
this(pathToMatch, false);
}
/**
* @param pathToMatch Content to extract
* @param includeAllElements if true array indexes in <code>ptrExpr</code> are ignored
* and all elements will be matched. default: false
*
* @since 2.16
*/
public JsonPointerBasedFilter(JsonPointer pathToMatch, boolean includeAllElements) {
_pathToMatch = pathToMatch;
_includeAllElements = includeAllElements;
}
/**
* Overridable factory method use for creating new instances by
* default {@link #includeElement} and {@link #includeProperty} methods:
* needs to be overridden if sub-classing this class.
*
* @param pathToMatch Remaining path for filter to match
* @param includeAllElements Whether to just include all array elements
* of matching Array-valued path automatically
*
* @since 2.16
*/
protected JsonPointerBasedFilter construct(JsonPointer pathToMatch, boolean includeAllElements) {
return new JsonPointerBasedFilter(pathToMatch, includeAllElements);
}
@Override
public TokenFilter includeElement(int index) {<FILL_FUNCTION_BODY>}
@Override
public TokenFilter includeProperty(String name) {
JsonPointer next = _pathToMatch.matchProperty(name);
if (next == null) {
return null;
}
if (next.matches()) {
return TokenFilter.INCLUDE_ALL;
}
return construct(next, _includeAllElements);
}
@Override
public TokenFilter filterStartArray() {
return this;
}
@Override
public TokenFilter filterStartObject() {
return this;
}
@Override
protected boolean _includeScalar() {
// should only occur for root-level scalars, path "/"
return _pathToMatch.matches();
}
@Override
public String toString() {
return "[JsonPointerFilter at: "+_pathToMatch+"]";
}
}
|
JsonPointer next;
if (_includeAllElements && !_pathToMatch.mayMatchElement()) {
next = _pathToMatch.tail();
} else {
next = _pathToMatch.matchElement(index);
}
if (next == null) {
return null;
}
if (next.matches()) {
return TokenFilter.INCLUDE_ALL;
}
return construct(next, _includeAllElements);
| 681
| 117
| 798
|
<methods>public void filterFinishArray() ,public void filterFinishObject() ,public com.fasterxml.jackson.core.filter.TokenFilter filterStartArray() ,public com.fasterxml.jackson.core.filter.TokenFilter filterStartObject() ,public boolean includeBinary() ,public boolean includeBoolean(boolean) ,public com.fasterxml.jackson.core.filter.TokenFilter includeElement(int) ,public boolean includeEmbeddedValue(java.lang.Object) ,public boolean includeEmptyArray(boolean) ,public boolean includeEmptyObject(boolean) ,public boolean includeNull() ,public boolean includeNumber(int) ,public boolean includeNumber(long) ,public boolean includeNumber(float) ,public boolean includeNumber(double) ,public boolean includeNumber(java.math.BigDecimal) ,public boolean includeNumber(java.math.BigInteger) ,public com.fasterxml.jackson.core.filter.TokenFilter includeProperty(java.lang.String) ,public boolean includeRawValue() ,public com.fasterxml.jackson.core.filter.TokenFilter includeRootValue(int) ,public boolean includeString(java.lang.String) ,public boolean includeString(java.io.Reader, int) ,public boolean includeValue(com.fasterxml.jackson.core.JsonParser) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.fasterxml.jackson.core.filter.TokenFilter INCLUDE_ALL
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/format/DataFormatDetector.java
|
DataFormatDetector
|
toString
|
class DataFormatDetector
{
/**
* By default we will look ahead at most 64 bytes; in most cases,
* much less (4 bytes or so) is needed, but we will allow bit more
* leniency to support data formats that need more complex heuristics.
*/
public final static int DEFAULT_MAX_INPUT_LOOKAHEAD = 64;
/**
* Ordered list of factories which both represent data formats to
* detect (in precedence order, starting with highest) and are used
* for actual detection.
*/
protected final JsonFactory[] _detectors;
/**
* Strength of match we consider to be good enough to be used
* without checking any other formats.
* Default value is {@link MatchStrength#SOLID_MATCH},
*/
protected final MatchStrength _optimalMatch;
/**
* Strength of minimal match we accept as the answer, unless
* better matches are found.
* Default value is {@link MatchStrength#WEAK_MATCH},
*/
protected final MatchStrength _minimalMatch;
/**
* Maximum number of leading bytes of the input that we can read
* to determine data format.
*<p>
* Default value is {@link #DEFAULT_MAX_INPUT_LOOKAHEAD}.
*/
protected final int _maxInputLookahead;
/*
/**********************************************************
/* Construction
/**********************************************************
*/
public DataFormatDetector(JsonFactory... detectors) {
this(detectors, MatchStrength.SOLID_MATCH, MatchStrength.WEAK_MATCH,
DEFAULT_MAX_INPUT_LOOKAHEAD);
}
public DataFormatDetector(Collection<JsonFactory> detectors) {
this(detectors.toArray(new JsonFactory[0]));
}
private DataFormatDetector(JsonFactory[] detectors,
MatchStrength optMatch, MatchStrength minMatch, int maxInputLookahead) {
_detectors = detectors;
_optimalMatch = optMatch;
_minimalMatch = minMatch;
_maxInputLookahead = maxInputLookahead;
}
/**
* Method that will return a detector instance that uses given
* optimal match level (match that is considered sufficient to return, without
* trying to find stronger matches with other formats).
*
* @param optMatch Optimal match level to use
*
* @return Format detector instance with specified optimal match level
*/
public DataFormatDetector withOptimalMatch(MatchStrength optMatch) {
if (optMatch == _optimalMatch) {
return this;
}
return new DataFormatDetector(_detectors, optMatch, _minimalMatch, _maxInputLookahead);
}
/**
* Method that will return a detector instance that uses given
* minimal match level; match that may be returned unless a stronger match
* is found with other format detectors.
*
* @param minMatch Minimum match level to use
*
* @return Format detector instance with specified minimum match level
*/
public DataFormatDetector withMinimalMatch(MatchStrength minMatch) {
if (minMatch == _minimalMatch) {
return this;
}
return new DataFormatDetector(_detectors, _optimalMatch, minMatch, _maxInputLookahead);
}
/**
* Method that will return a detector instance that allows detectors to
* read up to specified number of bytes when determining format match strength.
*
* @param lookaheadBytes Amount of look-ahead allowed
*
* @return Format detector instance with specified lookahead settings
*/
public DataFormatDetector withMaxInputLookahead(int lookaheadBytes) {
if (lookaheadBytes == _maxInputLookahead) {
return this;
}
return new DataFormatDetector(_detectors, _optimalMatch, _minimalMatch, lookaheadBytes);
}
/*
/**********************************************************
/* Public API
/**********************************************************
*/
/**
* Method to call to find format that content (accessible via given
* {@link InputStream}) given has, as per configuration of this detector
* instance.
*
* @param in InputStream from which to read initial content
*
* @return Matcher object which contains result; never null, even in cases
* where no match (with specified minimal match strength) is found.
*
* @throws IOException for read I/O problems
*/
public DataFormatMatcher findFormat(InputStream in) throws IOException {
return _findFormat(new InputAccessor.Std(in, new byte[_maxInputLookahead]));
}
/**
* Method to call to find format that given content (full document)
* has, as per configuration of this detector instance.
*
* @param fullInputData Full contents to use for format detection
*
* @return Matcher object which contains result; never null, even in cases
* where no match (with specified minimal match strength) is found.
*
* @throws IOException for read I/O problems
*/
public DataFormatMatcher findFormat(byte[] fullInputData) throws IOException {
return _findFormat(new InputAccessor.Std(fullInputData));
}
/**
* Method to call to find format that given content (full document)
* has, as per configuration of this detector instance.
*
* @param fullInputData Full contents to use for format detection
* @param offset Offset of the first content byte
* @param len Length of content
*
* @return Matcher object which contains result; never null, even in cases
* where no match (with specified minimal match strength) is found.
*
* @throws IOException for read I/O problems
*
* @since 2.1
*/
public DataFormatMatcher findFormat(byte[] fullInputData, int offset, int len) throws IOException {
return _findFormat(new InputAccessor.Std(fullInputData, offset, len));
}
/*
/**********************************************************
/* Overrides
/**********************************************************
*/
@Override public String toString() {<FILL_FUNCTION_BODY>}
/*
/**********************************************************
/* Internal methods
/**********************************************************
*/
private DataFormatMatcher _findFormat(InputAccessor.Std acc) throws IOException {
JsonFactory bestMatch = null;
MatchStrength bestMatchStrength = null;
for (JsonFactory f : _detectors) {
acc.reset();
MatchStrength strength = f.hasFormat(acc);
// if not better than what we have so far (including minimal level limit), skip
if (strength == null || strength.ordinal() < _minimalMatch.ordinal()) {
continue;
}
// also, needs to better match than before
if (bestMatch != null) {
if (bestMatchStrength.ordinal() >= strength.ordinal()) {
continue;
}
}
// finally: if it's good enough match, we are done
bestMatch = f;
bestMatchStrength = strength;
if (strength.ordinal() >= _optimalMatch.ordinal()) {
break;
}
}
return acc.createMatcher(bestMatch, bestMatchStrength);
}
}
|
StringBuilder sb = new StringBuilder();
sb.append('[');
final int len = _detectors.length;
if (len > 0) {
sb.append(_detectors[0].getFormatName());
for (int i = 1; i < len; ++i) {
sb.append(", ");
sb.append(_detectors[i].getFormatName());
}
}
sb.append(']');
return sb.toString();
| 1,868
| 121
| 1,989
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/format/DataFormatMatcher.java
|
DataFormatMatcher
|
createParserWithMatch
|
class DataFormatMatcher
{
protected final InputStream _originalStream;
/**
* Content read during format matching process
*/
protected final byte[] _bufferedData;
/**
* Pointer to the first byte in buffer available for reading
*/
protected final int _bufferedStart;
/**
* Number of bytes available in buffer.
*/
protected final int _bufferedLength;
/**
* Factory that produced sufficient match (if any)
*/
protected final JsonFactory _match;
/**
* Strength of match with {@link #_match}
*/
protected final MatchStrength _matchStrength;
protected DataFormatMatcher(InputStream in, byte[] buffered,
int bufferedStart, int bufferedLength,
JsonFactory match, MatchStrength strength)
{
_originalStream = in;
_bufferedData = buffered;
_bufferedStart = bufferedStart;
_bufferedLength = bufferedLength;
_match = match;
_matchStrength = strength;
// can't have negative offset or length
if ((bufferedStart | bufferedLength) < 0
|| (bufferedStart + bufferedLength) > buffered.length) {
throw new IllegalArgumentException(String.format("Illegal start/length (%d/%d) wrt input array of %d bytes",
bufferedStart, bufferedLength, buffered.length));
}
}
/*
/**********************************************************
/* Public API, simple accessors
/**********************************************************
*/
/**
* Accessor to use to see if any formats matched well enough with
* the input data.
*
* @return Whether format has a match
*/
public boolean hasMatch() { return _match != null; }
/**
* Method for accessing strength of the match, if any; if no match,
* will return {@link MatchStrength#INCONCLUSIVE}.
*
* @return Strength of match
*/
public MatchStrength getMatchStrength() {
return (_matchStrength == null) ? MatchStrength.INCONCLUSIVE : _matchStrength;
}
/**
* Accessor for {@link JsonFactory} that represents format that data matched.
*
* @return Relevant {@link JsonFactory} to indicate matched format
*/
public JsonFactory getMatch() { return _match; }
/**
* Accessor for getting brief textual name of matched format if any (null
* if none). Equivalent to:
*<pre>
* return hasMatch() ? getMatch().getFormatName() : null;
*</pre>
*
* @return Name of the format that is acceptable match, if any; {@code null} if none
*/
public String getMatchedFormatName() {
return hasMatch() ? getMatch().getFormatName() : null;
}
/*
/**********************************************************
/* Public API, factory methods
/**********************************************************
*/
// Convenience method for trying to construct a {@link JsonParser} for
// parsing content which is assumed to be in detected data format.
// If no match was found, returns null.
public JsonParser createParserWithMatch() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Method to use for accessing input for which format detection has been done.
* This <b>must</b> be used instead of using stream passed to detector
* unless given stream itself can do buffering.
* Stream will return all content that was read during matching process, as well
* as remaining contents of the underlying stream.
*
* @return InputStream to use for reading actual content using format detected
*/
public InputStream getDataStream() {
if (_originalStream == null) {
return new ByteArrayInputStream(_bufferedData, _bufferedStart, _bufferedLength);
}
return new MergedStream(null, _originalStream, _bufferedData, _bufferedStart, _bufferedLength);
}
}
|
if (_match == null) {
return null;
}
if (_originalStream == null) {
return _match.createParser(_bufferedData, _bufferedStart, _bufferedLength);
}
return _match.createParser(getDataStream());
| 1,012
| 69
| 1,081
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/io/BigDecimalParser.java
|
BigDecimalParser
|
_parseFailure
|
class BigDecimalParser
{
final static int MAX_CHARS_TO_REPORT = 1000;
private BigDecimalParser() {}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @param valueStr
* @return BigDecimal value
* @throws NumberFormatException
*/
public static BigDecimal parse(String valueStr) {
return parse(valueStr.toCharArray());
}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @return BigDecimal value
* @throws NumberFormatException
*/
public static BigDecimal parse(final char[] chars, final int off, final int len) {
try {
if (len < 500) {
return new BigDecimal(chars, off, len);
}
return JavaBigDecimalParser.parseBigDecimal(chars, off, len);
// 20-Aug-2022, tatu: Although "new BigDecimal(...)" only throws NumberFormatException
// operations by "parseBigDecimal()" can throw "ArithmeticException", so handle both:
} catch (ArithmeticException | NumberFormatException e) {
throw _parseFailure(e, new String(chars, off, len));
}
}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @param chars
* @return BigDecimal value
* @throws NumberFormatException
*/
public static BigDecimal parse(char[] chars) {
return parse(chars, 0, chars.length);
}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @param valueStr
* @return BigDecimal value
* @throws NumberFormatException
*/
public static BigDecimal parseWithFastParser(final String valueStr) {
try {
return JavaBigDecimalParser.parseBigDecimal(valueStr);
} catch (ArithmeticException | NumberFormatException e) {
throw _parseFailure(e, valueStr);
}
}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @return BigDecimal value
* @throws NumberFormatException
*/
public static BigDecimal parseWithFastParser(final char[] ch, final int off, final int len) {
try {
return JavaBigDecimalParser.parseBigDecimal(ch, off, len);
} catch (ArithmeticException | NumberFormatException e) {
throw _parseFailure(e, new String(ch, off, len));
}
}
private static NumberFormatException _parseFailure(Exception e, String fullValue) {<FILL_FUNCTION_BODY>}
private static String _getValueDesc(String fullValue) {
final int len = fullValue.length();
if (len <= MAX_CHARS_TO_REPORT) {
return String.format("\"%s\"", fullValue);
}
return String.format("\"%s\" (truncated to %d chars (from %d))",
fullValue.substring(0, MAX_CHARS_TO_REPORT),
MAX_CHARS_TO_REPORT, len);
}
}
|
String desc = e.getMessage();
// 05-Feb-2021, tatu: Alas, JDK mostly has null message so:
if (desc == null) {
desc = "Not a valid number representation";
}
String valueToReport = _getValueDesc(fullValue);
return new NumberFormatException("Value " + valueToReport
+ " can not be deserialized as `java.math.BigDecimal`, reason: " + desc);
| 1,116
| 118
| 1,234
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/io/BigIntegerParser.java
|
BigIntegerParser
|
parseWithFastParser
|
class BigIntegerParser
{
private BigIntegerParser() {}
public static BigInteger parseWithFastParser(final String valueStr) {
try {
return JavaBigIntegerParser.parseBigInteger(valueStr);
} catch (NumberFormatException nfe) {
final String reportNum = valueStr.length() <= MAX_CHARS_TO_REPORT ?
valueStr : valueStr.substring(0, MAX_CHARS_TO_REPORT) + " [truncated]";
throw new NumberFormatException("Value \"" + reportNum
+ "\" can not be represented as `java.math.BigInteger`, reason: " + nfe.getMessage());
}
}
public static BigInteger parseWithFastParser(final String valueStr, final int radix) {<FILL_FUNCTION_BODY>}
}
|
try {
return JavaBigIntegerParser.parseBigInteger(valueStr, radix);
} catch (NumberFormatException nfe) {
final String reportNum = valueStr.length() <= MAX_CHARS_TO_REPORT ?
valueStr : valueStr.substring(0, MAX_CHARS_TO_REPORT) + " [truncated]";
throw new NumberFormatException("Value \"" + reportNum
+ "\" can not be represented as `java.math.BigInteger` with radix " + radix +
", reason: " + nfe.getMessage());
}
| 203
| 146
| 349
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/io/MergedStream.java
|
MergedStream
|
_free
|
class MergedStream extends InputStream
{
final private IOContext _ctxt;
final private InputStream _in;
private byte[] _b;
private int _ptr;
final private int _end;
public MergedStream(IOContext ctxt, InputStream in, byte[] buf, int start, int end) {
_ctxt = ctxt;
_in = in;
_b = buf;
_ptr = start;
_end = end;
}
@Override
public int available() throws IOException {
if (_b != null) {
return _end - _ptr;
}
return _in.available();
}
@Override public void close() throws IOException {
_free();
_in.close();
}
@Override public synchronized void mark(int readlimit) {
if (_b == null) { _in.mark(readlimit); }
}
@Override public boolean markSupported() {
// Only supports marks past the initial rewindable section...
return (_b == null) && _in.markSupported();
}
@Override public int read() throws IOException {
if (_b != null) {
int c = _b[_ptr++] & 0xFF;
if (_ptr >= _end) {
_free();
}
return c;
}
return _in.read();
}
@Override public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (_b != null) {
int avail = _end - _ptr;
if (len > avail) {
len = avail;
}
System.arraycopy(_b, _ptr, b, off, len);
_ptr += len;
if (_ptr >= _end) {
_free();
}
return len;
}
return _in.read(b, off, len);
}
@Override
public synchronized void reset() throws IOException {
if (_b == null) { _in.reset(); }
}
@Override
public long skip(long n) throws IOException {
long count = 0L;
if (_b != null) {
int amount = _end - _ptr;
if (amount > n) { // all in pushed back segment?
_ptr += (int) n;
return n;
}
_free();
count += amount;
n -= amount;
}
if (n > 0) { count += _in.skip(n); }
return count;
}
private void _free() {<FILL_FUNCTION_BODY>}
}
|
byte[] buf = _b;
if (buf != null) {
_b = null;
if (_ctxt != null) {
_ctxt.releaseReadIOBuffer(buf);
}
}
| 711
| 59
| 770
|
<methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/io/SegmentedStringWriter.java
|
SegmentedStringWriter
|
append
|
class SegmentedStringWriter
extends Writer
implements BufferRecycler.Gettable
{
final private TextBuffer _buffer;
public SegmentedStringWriter(BufferRecycler br) {
super();
_buffer = new TextBuffer(br);
}
/*
/**********************************************************************
/* BufferRecycler.Gettable implementation
/**********************************************************************
*/
@Override
public BufferRecycler bufferRecycler() {
return _buffer.bufferRecycler();
}
/*
/**********************************************************************
/* java.io.Writer implementation
/**********************************************************************
*/
@Override
public Writer append(char c) throws IOException {
write(c);
return this;
}
@Override
public Writer append(CharSequence csq) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Writer append(CharSequence csq, int start, int end) throws IOException {
String str = csq.subSequence(start, end).toString();
_buffer.append(str, 0, str.length());
return this;
}
@Override
public void close() { } // NOP
@Override
public void flush() { } // NOP
@Override
public void write(char[] cbuf) throws IOException {
_buffer.append(cbuf, 0, cbuf.length);
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
_buffer.append(cbuf, off, len);
}
@Override
public void write(int c) throws IOException {
_buffer.append((char) c);
}
@Override
public void write(String str) throws IOException {
_buffer.append(str, 0, str.length());
}
@Override
public void write(String str, int off, int len) throws IOException {
_buffer.append(str, off, len);
}
/*
/**********************************************************************
/* Extended API
/**********************************************************************
*/
/**
* Main access method that will construct a String that contains
* all the contents, release all internal buffers we may have,
* and return result String.
* Note that the method is not idempotent -- if called second time,
* will just return an empty String.
*
* @return String that contains all aggregated content
* @throws IOException if there are general I/O or parse issues, including if the text is too large,
* see {@link com.fasterxml.jackson.core.StreamReadConstraints.Builder#maxStringLength(int)}
*/
public String getAndClear() throws IOException {
String result = _buffer.contentsAsString();
_buffer.releaseBuffers();
return result;
}
}
|
String str = csq.toString();
_buffer.append(str, 0, str.length());
return this;
| 723
| 34
| 757
|
<methods>public java.io.Writer append(java.lang.CharSequence) throws java.io.IOException,public java.io.Writer append(char) throws java.io.IOException,public java.io.Writer append(java.lang.CharSequence, int, int) throws java.io.IOException,public abstract void close() throws java.io.IOException,public abstract void flush() throws java.io.IOException,public static java.io.Writer nullWriter() ,public void write(int) throws java.io.IOException,public void write(char[]) throws java.io.IOException,public void write(java.lang.String) throws java.io.IOException,public abstract void write(char[], int, int) throws java.io.IOException,public void write(java.lang.String, int, int) throws java.io.IOException<variables>private static final int WRITE_BUFFER_SIZE,protected java.lang.Object lock,private char[] writeBuffer
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/json/DupDetector.java
|
DupDetector
|
isDup
|
class DupDetector
{
/**
* We need to store a back-reference here to parser/generator.
*/
protected final Object _source;
protected String _firstName;
protected String _secondName;
/**
* Lazily constructed set of names already seen within this context.
*/
protected HashSet<String> _seen;
private DupDetector(Object src) {
_source = src;
}
public static DupDetector rootDetector(JsonParser p) {
return new DupDetector(p);
}
public static DupDetector rootDetector(JsonGenerator g) {
return new DupDetector(g);
}
public DupDetector child() {
return new DupDetector(_source);
}
public void reset() {
_firstName = null;
_secondName = null;
_seen = null;
}
public JsonLocation findLocation() {
// ugly but:
if (_source instanceof JsonParser) {
return ((JsonParser)_source).currentLocation();
}
// do generators have a way to provide Location? Apparently not...
return null;
}
/**
* @return Source object (parser / generator) used to construct this detector
*
* @since 2.7
*/
public Object getSource() {
return _source;
}
/**
* Method called to check whether a newly encountered property name would
* be a duplicate within this context, and if not, update the state to remember
* having seen the property name for checking more property names
*
* @param name Property seen
*
* @return {@code True} if the property had already been seen before in this context
*
* @throws JsonParseException to report possible operation problem (default implementation
* never throws it)
*/
public boolean isDup(String name) throws JsonParseException
{<FILL_FUNCTION_BODY>}
}
|
if (_firstName == null) {
_firstName = name;
return false;
}
if (name.equals(_firstName)) {
return true;
}
if (_secondName == null) {
_secondName = name;
return false;
}
if (name.equals(_secondName)) {
return true;
}
if (_seen == null) {
_seen = new HashSet<>(16); // 16 is default, seems reasonable
_seen.add(_firstName);
_seen.add(_secondName);
}
return !_seen.add(name);
| 501
| 160
| 661
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/json/async/NonBlockingByteBufferJsonParser.java
|
NonBlockingByteBufferJsonParser
|
feedInput
|
class NonBlockingByteBufferJsonParser
extends NonBlockingUtf8JsonParserBase
implements ByteBufferFeeder
{
private ByteBuffer _inputBuffer = ByteBuffer.wrap(NO_BYTES);
public NonBlockingByteBufferJsonParser(IOContext ctxt, int parserFeatures,
ByteQuadsCanonicalizer sym) {
super(ctxt, parserFeatures, sym);
}
@Override
public NonBlockingInputFeeder getNonBlockingInputFeeder() {
return this;
}
@Override
public void feedInput(final ByteBuffer byteBuffer) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int releaseBuffered(final OutputStream out) throws IOException {
final int avail = _inputEnd - _inputPtr;
if (avail > 0) {
final WritableByteChannel channel = Channels.newChannel(out);
channel.write(_inputBuffer);
}
return avail;
}
@Override
protected byte getNextSignedByteFromBuffer() {
return _inputBuffer.get(_inputPtr++);
}
@Override
protected int getNextUnsignedByteFromBuffer() {
return _inputBuffer.get(_inputPtr++) & 0xFF;
}
@Override
protected byte getByteFromBuffer(final int ptr) {
return _inputBuffer.get(ptr);
}
}
|
// Must not have remaining input
if (_inputPtr < _inputEnd) {
_reportError("Still have %d undecoded bytes, should not call 'feedInput'", _inputEnd - _inputPtr);
}
final int start = byteBuffer.position();
final int end = byteBuffer.limit();
if (end < start) {
_reportError("Input end (%d) may not be before start (%d)", end, start);
}
// and shouldn't have been marked as end-of-input
if (_endOfInput) {
_reportError("Already closed, can not feed more input");
}
// Time to update pointers first
_currInputProcessed += _origBufferLen;
// 06-Sep-2023, tatu: [core#1046] Enforce max doc length limit
streamReadConstraints().validateDocumentLength(_currInputProcessed);
// Also need to adjust row start, to work as if it extended into the past wrt new buffer
_currInputRowStart = start - (_inputEnd - _currInputRowStart);
// And then update buffer settings
_currBufferStart = start;
_inputBuffer = byteBuffer;
_inputPtr = start;
_inputEnd = end;
_origBufferLen = end - start;
| 356
| 336
| 692
|
<methods>public void endOfInput() ,public final boolean needMoreInput() ,public com.fasterxml.jackson.core.JsonToken nextToken() throws java.io.IOException<variables>private static final int FEAT_MASK_ALLOW_JAVA_COMMENTS,private static final int FEAT_MASK_ALLOW_MISSING,private static final int FEAT_MASK_ALLOW_SINGLE_QUOTES,private static final int FEAT_MASK_ALLOW_UNQUOTED_NAMES,private static final int FEAT_MASK_ALLOW_YAML_COMMENTS,private static final int FEAT_MASK_LEADING_ZEROS,private static final int FEAT_MASK_TRAILING_COMMA,protected static final int[] _icLatin1,private static final int[] _icUTF8,protected int _origBufferLen
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/json/async/NonBlockingJsonParser.java
|
NonBlockingJsonParser
|
feedInput
|
class NonBlockingJsonParser
extends NonBlockingUtf8JsonParserBase
implements ByteArrayFeeder
{
private byte[] _inputBuffer = NO_BYTES;
public NonBlockingJsonParser(IOContext ctxt, int parserFeatures,
ByteQuadsCanonicalizer sym) {
super(ctxt, parserFeatures, sym);
}
@Override
public ByteArrayFeeder getNonBlockingInputFeeder() {
return this;
}
@Override
public void feedInput(final byte[] buf, final int start, final int end) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int releaseBuffered(final OutputStream out) throws IOException {
final int avail = _inputEnd - _inputPtr;
if (avail > 0) {
out.write(_inputBuffer, _inputPtr, avail);
}
return avail;
}
@Override
protected byte getNextSignedByteFromBuffer() {
return _inputBuffer[_inputPtr++];
}
@Override
protected int getNextUnsignedByteFromBuffer() {
return _inputBuffer[_inputPtr++] & 0xFF;
}
@Override
protected byte getByteFromBuffer(final int ptr) {
return _inputBuffer[ptr];
}
}
|
// Must not have remaining input
if (_inputPtr < _inputEnd) {
_reportError("Still have %d undecoded bytes, should not call 'feedInput'", _inputEnd - _inputPtr);
}
if (end < start) {
_reportError("Input end (%d) may not be before start (%d)", end, start);
}
// and shouldn't have been marked as end-of-input
if (_endOfInput) {
_reportError("Already closed, can not feed more input");
}
// Time to update pointers first
_currInputProcessed += _origBufferLen;
// 06-Sep-2023, tatu: [core#1046] Enforce max doc length limit
streamReadConstraints().validateDocumentLength(_currInputProcessed);
// Also need to adjust row start, to work as if it extended into the past wrt new buffer
_currInputRowStart = start - (_inputEnd - _currInputRowStart);
// And then update buffer settings
_currBufferStart = start;
_inputBuffer = buf;
_inputPtr = start;
_inputEnd = end;
_origBufferLen = end - start;
| 335
| 311
| 646
|
<methods>public void endOfInput() ,public final boolean needMoreInput() ,public com.fasterxml.jackson.core.JsonToken nextToken() throws java.io.IOException<variables>private static final int FEAT_MASK_ALLOW_JAVA_COMMENTS,private static final int FEAT_MASK_ALLOW_MISSING,private static final int FEAT_MASK_ALLOW_SINGLE_QUOTES,private static final int FEAT_MASK_ALLOW_UNQUOTED_NAMES,private static final int FEAT_MASK_ALLOW_YAML_COMMENTS,private static final int FEAT_MASK_LEADING_ZEROS,private static final int FEAT_MASK_TRAILING_COMMA,protected static final int[] _icLatin1,private static final int[] _icUTF8,protected int _origBufferLen
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/sym/Name.java
|
Name
|
equals
|
class Name
{
protected final String _name;
protected final int _hashCode;
protected Name(String name, int hashCode) {
_name = name;
_hashCode = hashCode;
}
public String getName() { return _name; }
/*
/**********************************************************
/* Methods for package/core parser
/**********************************************************
*/
public abstract boolean equals(int q1);
public abstract boolean equals(int q1, int q2);
public abstract boolean equals(int q1, int q2, int q3);
public abstract boolean equals(int[] quads, int qlen);
/*
/**********************************************************
/* Overridden standard methods
/**********************************************************
*/
@Override public String toString() { return _name; }
@Override public final int hashCode() { return _hashCode; }
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
}
|
// Canonical instances, can usually just do identity comparison
return (o == this);
| 255
| 24
| 279
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/sym/Name2.java
|
Name2
|
equals
|
class Name2 extends Name
{
private final int q1, q2;
Name2(String name, int hash, int quad1, int quad2) {
super(name, hash);
q1 = quad1;
q2 = quad2;
}
@Override
public boolean equals(int quad) { return false; }
@Override
public boolean equals(int quad1, int quad2) { return (quad1 == q1) && (quad2 == q2); }
@Override public boolean equals(int quad1, int quad2, int q3) { return false; }
@Override
public boolean equals(int[] quads, int qlen) {<FILL_FUNCTION_BODY>}
}
|
return (qlen == 2 && quads[0] == q1 && quads[1] == q2);
| 185
| 27
| 212
|
<methods>public abstract boolean equals(int) ,public abstract boolean equals(int, int) ,public abstract boolean equals(int, int, int) ,public abstract boolean equals(int[], int) ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public final int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed int _hashCode,protected final non-sealed java.lang.String _name
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/sym/Name3.java
|
Name3
|
equals
|
class Name3 extends Name
{
private final int q1, q2, q3;
Name3(String name, int hash, int i1, int i2, int i3) {
super(name, hash);
q1 = i1;
q2 = i2;
q3 = i3;
}
// Implies quad length == 1, never matches
@Override
public boolean equals(int quad) { return false; }
// Implies quad length == 2, never matches
@Override
public boolean equals(int quad1, int quad2) { return false; }
@Override
public boolean equals(int quad1, int quad2, int quad3) {
return (q1 == quad1) && (q2 == quad2) && (q3 == quad3);
}
@Override
public boolean equals(int[] quads, int qlen) {<FILL_FUNCTION_BODY>}
}
|
return (qlen == 3) && (quads[0] == q1) && (quads[1] == q2) && (quads[2] == q3);
| 238
| 45
| 283
|
<methods>public abstract boolean equals(int) ,public abstract boolean equals(int, int) ,public abstract boolean equals(int, int, int) ,public abstract boolean equals(int[], int) ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public final int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed int _hashCode,protected final non-sealed java.lang.String _name
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/sym/NameN.java
|
NameN
|
equals
|
class NameN extends Name
{
private final int q1, q2, q3, q4; // first four quads
private final int qlen; // total number of quads (4 + q.length)
private final int[] q;
NameN(String name, int hash, int q1, int q2, int q3, int q4,
int[] quads, int quadLen) {
super(name, hash);
this.q1 = q1;
this.q2 = q2;
this.q3 = q3;
this.q4 = q4;
q = quads;
qlen = quadLen;
}
public static NameN construct(String name, int hash, int[] q, int qlen)
{
/* We have specialized implementations for shorter
* names, so let's not allow runt instances here
*/
if (qlen < 4) {
throw new IllegalArgumentException();
}
int q1 = q[0];
int q2 = q[1];
int q3 = q[2];
int q4 = q[3];
int rem = qlen - 4;
int[] buf;
if (rem > 0) {
buf = Arrays.copyOfRange(q, 4, qlen);
} else {
buf = null;
}
return new NameN(name, hash, q1, q2, q3, q4, buf, qlen);
}
// Implies quad length == 1, never matches
@Override
public boolean equals(int quad) { return false; }
// Implies quad length == 2, never matches
@Override
public boolean equals(int quad1, int quad2) { return false; }
// Implies quad length == 3, never matches
@Override
public boolean equals(int quad1, int quad2, int quad3) { return false; }
@Override
public boolean equals(int[] quads, int len) {<FILL_FUNCTION_BODY>}
private final boolean _equals2(int[] quads)
{
final int end = qlen-4;
for (int i = 0; i < end; ++i) {
if (quads[i+4] != q[i]) {
return false;
}
}
return true;
}
}
|
if (len != qlen) { return false; }
// Will always have >= 4 quads, can unroll
if (quads[0] != q1) return false;
if (quads[1] != q2) return false;
if (quads[2] != q3) return false;
if (quads[3] != q4) return false;
switch (len) {
default:
return _equals2(quads);
case 8:
if (quads[7] != q[3]) return false;
case 7:
if (quads[6] != q[2]) return false;
case 6:
if (quads[5] != q[1]) return false;
case 5:
if (quads[4] != q[0]) return false;
case 4:
}
return true;
| 597
| 233
| 830
|
<methods>public abstract boolean equals(int) ,public abstract boolean equals(int, int) ,public abstract boolean equals(int, int, int) ,public abstract boolean equals(int[], int) ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public final int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed int _hashCode,protected final non-sealed java.lang.String _name
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/util/BufferRecyclers.java
|
BufferRecyclers
|
getBufferRecycler
|
class BufferRecyclers
{
/**
* System property that is checked to see if recycled buffers (see {@link BufferRecycler})
* should be tracked, for purpose of forcing release of all such buffers, typically
* during major garbage-collection.
*
* @since 2.9.6
*/
public final static String SYSTEM_PROPERTY_TRACK_REUSABLE_BUFFERS
= "com.fasterxml.jackson.core.util.BufferRecyclers.trackReusableBuffers";
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
/**
* Flag that indicates whether {@link BufferRecycler} instances should be tracked.
*/
private final static ThreadLocalBufferManager _bufferRecyclerTracker;
static {
boolean trackReusableBuffers = false;
try {
trackReusableBuffers = "true".equals(System.getProperty(SYSTEM_PROPERTY_TRACK_REUSABLE_BUFFERS));
} catch (SecurityException e) { }
_bufferRecyclerTracker = trackReusableBuffers ? ThreadLocalBufferManager.instance() : null;
}
/*
/**********************************************************
/* BufferRecyclers for parsers, generators
/**********************************************************
*/
/**
* This <code>ThreadLocal</code> contains a {@link java.lang.ref.SoftReference}
* to a {@link BufferRecycler} used to provide a low-cost
* buffer recycling between reader and writer instances.
*/
final protected static ThreadLocal<SoftReference<BufferRecycler>> _recyclerRef
= new ThreadLocal<>();
/**
* Main accessor to call for accessing possibly recycled {@link BufferRecycler} instance.
*
* @return {@link BufferRecycler} to use
*
* @deprecated Since 2.16 should use {@link RecyclerPool} abstraction instead
* of calling static methods of this class
*/
@Deprecated // since 2.16
public static BufferRecycler getBufferRecycler()
{<FILL_FUNCTION_BODY>}
/**
* Specialized method that will release all recycled {@link BufferRecycler} if
* (and only if) recycler tracking has been enabled
* (see {@link #SYSTEM_PROPERTY_TRACK_REUSABLE_BUFFERS}).
* This method is usually called on shutdown of the container like Application Server
* to ensure that no references are reachable via {@link ThreadLocal}s as this may cause
* unintentional retention of sizable amounts of memory. It may also be called regularly
* if GC for some reason does not clear up {@link SoftReference}s aggressively enough.
*
* @return Number of buffers released, if tracking enabled (zero or more); -1 if tracking not enabled.
*
* @since 2.9.6
*/
public static int releaseBuffers() {
if (_bufferRecyclerTracker != null) {
return _bufferRecyclerTracker.releaseBuffers();
}
return -1;
}
/*
/**********************************************************************
/* Obsolete things re-introduced in 2.12.5 after accidental direct
/* removal from 2.10.0
/**********************************************************************
*/
/**
* Not to be used any more.
*
* @return {@code JsonStringEncoder} instance to use.
*
* @deprecated Since 2.10 call {@link JsonStringEncoder#getInstance()} instead.
* NOTE: was accidentally removed but reintroduced as deprecated in 2.12.5,
* to be removed from 3.0)
*/
@Deprecated
public static JsonStringEncoder getJsonStringEncoder() {
return JsonStringEncoder.getInstance();
}
/**
* Not to be used any more.
*
* @param text String to encode
* @return String encoded as UTF-8 bytes.
*
* @deprecated Since 2.10 call {@link JsonStringEncoder#getInstance()} and then
* {@code encodeAsUTF8()}) instead.
* NOTE: was accidentally removed but reintroduced as deprecated in 2.12.5,
* to be removed from 3.0)
*/
@Deprecated
public static byte[] encodeAsUTF8(String text) {
return JsonStringEncoder.getInstance().encodeAsUTF8(text);
}
/**
* Not to be used any more:
*
* @param rawText String to quote
*
* @return Quoted text as {@code char[]}
*
* @deprecated Since 2.10 call {@link JsonStringEncoder#getInstance()} and then
* {@code quoteAsString()}) instead.
* NOTE: was accidentally removed but reintroduced as deprecated in 2.12.5,
* to be removed from 3.0)
*/
@Deprecated
public static char[] quoteAsJsonText(String rawText) {
return JsonStringEncoder.getInstance().quoteAsString(rawText);
}
/**
* Not to be used any more.
*
* @param input Textual content to quote
* @param output Builder to append quoted content
*
* @deprecated Since 2.10 call {@link JsonStringEncoder#getInstance()} and then
* {@code quoteAsString()}) instead.
* NOTE: was accidentally removed but reintroduced as deprecated in 2.12.5,
* to be removed from 3.0)
*/
@Deprecated
public static void quoteAsJsonText(CharSequence input, StringBuilder output) {
JsonStringEncoder.getInstance().quoteAsString(input, output);
}
/**
* Not to be used any more.
*
* @param rawText String to quote
*
* @return Quoted text as {@code byte[]}
*
* @deprecated Since 2.10 call {@link JsonStringEncoder#getInstance()} (and then
* {@code quoteAsUTF8()}) instead.
* NOTE: was accidentally removed but reintroduced as deprecated in 2.12.5,
* to be removed from 3.0)
*/
@Deprecated
public static byte[] quoteAsJsonUTF8(String rawText) {
return JsonStringEncoder.getInstance().quoteAsUTF8(rawText);
}
}
|
SoftReference<BufferRecycler> ref = _recyclerRef.get();
BufferRecycler br = (ref == null) ? null : ref.get();
if (br == null) {
br = new BufferRecycler();
if (_bufferRecyclerTracker != null) {
ref = _bufferRecyclerTracker.wrapAndTrack(br);
} else {
ref = new SoftReference<>(br);
}
_recyclerRef.set(ref);
}
return br;
| 1,661
| 137
| 1,798
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/util/DefaultIndenter.java
|
DefaultIndenter
|
writeIndentation
|
class DefaultIndenter
extends DefaultPrettyPrinter.NopIndenter
{
private static final long serialVersionUID = 1L;
public final static String SYS_LF;
static {
String lf;
try {
lf = System.getProperty("line.separator");
} catch (Throwable t) {
lf = "\n"; // fallback when security manager denies access
}
SYS_LF = lf;
}
public static final DefaultIndenter SYSTEM_LINEFEED_INSTANCE = new DefaultIndenter(" ", SYS_LF);
/**
* We expect to rarely get indentation deeper than this number of levels,
* and try not to pre-generate more indentations than needed.
*/
private final static int INDENT_LEVELS = 16;
private final char[] indents;
private final int charsPerLevel;
private final String eol;
/**
* Indent with two spaces and the system's default line feed
*/
public DefaultIndenter() {
this(" ", SYS_LF);
}
/**
* Create an indenter which uses the <code>indent</code> string to indent one level
* and the <code>eol</code> string to separate lines.
*
* @param indent Indentation String to prepend for a single level of indentation
* @param eol End-of-line marker to use after indented line
*/
public DefaultIndenter(String indent, String eol)
{
charsPerLevel = indent.length();
indents = new char[indent.length() * INDENT_LEVELS];
int offset = 0;
for (int i=0; i<INDENT_LEVELS; i++) {
indent.getChars(0, indent.length(), indents, offset);
offset += indent.length();
}
this.eol = eol;
}
public DefaultIndenter withLinefeed(String lf)
{
if (lf.equals(eol)) {
return this;
}
return new DefaultIndenter(getIndent(), lf);
}
public DefaultIndenter withIndent(String indent)
{
if (indent.equals(getIndent())) {
return this;
}
return new DefaultIndenter(indent, eol);
}
@Override
public boolean isInline() { return false; }
@Override
public void writeIndentation(JsonGenerator jg, int level) throws IOException
{<FILL_FUNCTION_BODY>}
public String getEol() {
return eol;
}
public String getIndent() {
return new String(indents, 0, charsPerLevel);
}
}
|
jg.writeRaw(eol);
if (level > 0) { // should we err on negative values (as there's some flaw?)
level *= charsPerLevel;
while (level > indents.length) { // unlike to happen but just in case
jg.writeRaw(indents, 0, indents.length);
level -= indents.length;
}
jg.writeRaw(indents, 0, level);
}
| 725
| 119
| 844
|
<methods>public non-sealed void <init>() ,public boolean isInline() ,public void writeIndentation(com.fasterxml.jackson.core.JsonGenerator, int) throws java.io.IOException<variables>public static final com.fasterxml.jackson.core.util.DefaultPrettyPrinter.NopIndenter instance
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/util/InternCache.java
|
InternCache
|
intern
|
class InternCache
extends ConcurrentHashMap<String,String> // since 2.3
{
private static final long serialVersionUID = 1L;
/**
* Size to use is somewhat arbitrary, so let's choose something that's
* neither too small (low hit ratio) nor too large (waste of memory).
*<p>
* One consideration is possible attack via colliding {@link String#hashCode};
* because of this, limit to reasonably low setting.
*<p>
* Increased to 200 (from 100) in 2.18
*/
private final static int DEFAULT_MAX_ENTRIES = 280;
public final static InternCache instance = new InternCache();
/**
* As minor optimization let's try to avoid "flush storms",
* cases where multiple threads might try to concurrently
* flush the map.
*/
private final ReentrantLock lock = new ReentrantLock();
public InternCache() { this(DEFAULT_MAX_ENTRIES, 0.8f, 4); }
public InternCache(int maxSize, float loadFactor, int concurrency) {
super(maxSize, loadFactor, concurrency);
}
public String intern(String input) {<FILL_FUNCTION_BODY>}
}
|
String result = get(input);
if (result != null) { return result; }
/* 18-Sep-2013, tatu: We used to use LinkedHashMap, which has simple LRU
* method. No such functionality exists with CHM; and let's use simplest
* possible limitation: just clear all contents. This because otherwise
* we are simply likely to keep on clearing same, commonly used entries.
*/
if (size() >= DEFAULT_MAX_ENTRIES) {
/* As of 2.18, the limit is not strictly enforced, but we do try to
* clear entries if we have reached the limit. We do not expect to
* go too much over the limit, and if we do, it's not a huge problem.
* If some other thread has the lock, we will not clear but the lock should
* not be held for long, so another thread should be able to clear in the near future.
*/
if (lock.tryLock()) {
try {
if (size() >= DEFAULT_MAX_ENTRIES) {
clear();
}
} finally {
lock.unlock();
}
}
}
result = input.intern();
put(result, result);
return result;
| 332
| 316
| 648
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends java.lang.String>) ,public void <init>(int, float) ,public void <init>(int, float, int) ,public void clear() ,public java.lang.String compute(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public java.lang.String computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends java.lang.String>) ,public java.lang.String computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public boolean contains(java.lang.Object) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Enumeration<java.lang.String> elements() ,public Set<Entry<java.lang.String,java.lang.String>> entrySet() ,public boolean equals(java.lang.Object) ,public void forEach(BiConsumer<? super java.lang.String,? super java.lang.String>) ,public void forEach(long, BiConsumer<? super java.lang.String,? super java.lang.String>) ,public void forEach(long, BiFunction<? super java.lang.String,? super java.lang.String,? extends U>, Consumer<? super U>) ,public void forEachEntry(long, Consumer<? super Entry<java.lang.String,java.lang.String>>) ,public void forEachEntry(long, Function<Entry<java.lang.String,java.lang.String>,? extends U>, Consumer<? super U>) ,public void forEachKey(long, Consumer<? super java.lang.String>) ,public void forEachKey(long, Function<? super java.lang.String,? extends U>, Consumer<? super U>) ,public void forEachValue(long, Consumer<? super java.lang.String>) ,public void forEachValue(long, Function<? super java.lang.String,? extends U>, Consumer<? super U>) ,public java.lang.String get(java.lang.Object) ,public java.lang.String getOrDefault(java.lang.Object, java.lang.String) ,public int hashCode() ,public boolean isEmpty() ,public KeySetView<java.lang.String,java.lang.String> keySet() ,public KeySetView<java.lang.String,java.lang.String> keySet(java.lang.String) ,public Enumeration<java.lang.String> keys() ,public long mappingCount() ,public java.lang.String merge(java.lang.String, java.lang.String, BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public static KeySetView<K,java.lang.Boolean> newKeySet() ,public static KeySetView<K,java.lang.Boolean> newKeySet(int) ,public java.lang.String put(java.lang.String, java.lang.String) ,public void putAll(Map<? extends java.lang.String,? extends java.lang.String>) ,public java.lang.String putIfAbsent(java.lang.String, java.lang.String) ,public U reduce(long, BiFunction<? super java.lang.String,? super java.lang.String,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public Entry<java.lang.String,java.lang.String> reduceEntries(long, BiFunction<Entry<java.lang.String,java.lang.String>,Entry<java.lang.String,java.lang.String>,? extends Entry<java.lang.String,java.lang.String>>) ,public U reduceEntries(long, Function<Entry<java.lang.String,java.lang.String>,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public double reduceEntriesToDouble(long, ToDoubleFunction<Entry<java.lang.String,java.lang.String>>, double, java.util.function.DoubleBinaryOperator) ,public int reduceEntriesToInt(long, ToIntFunction<Entry<java.lang.String,java.lang.String>>, int, java.util.function.IntBinaryOperator) ,public long reduceEntriesToLong(long, ToLongFunction<Entry<java.lang.String,java.lang.String>>, long, java.util.function.LongBinaryOperator) ,public java.lang.String reduceKeys(long, BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public U reduceKeys(long, Function<? super java.lang.String,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public double reduceKeysToDouble(long, ToDoubleFunction<? super java.lang.String>, double, java.util.function.DoubleBinaryOperator) ,public int reduceKeysToInt(long, ToIntFunction<? super java.lang.String>, int, java.util.function.IntBinaryOperator) ,public long reduceKeysToLong(long, ToLongFunction<? super java.lang.String>, long, java.util.function.LongBinaryOperator) ,public double reduceToDouble(long, ToDoubleBiFunction<? super java.lang.String,? super java.lang.String>, double, java.util.function.DoubleBinaryOperator) ,public int reduceToInt(long, ToIntBiFunction<? super java.lang.String,? super java.lang.String>, int, java.util.function.IntBinaryOperator) ,public long reduceToLong(long, ToLongBiFunction<? super java.lang.String,? super java.lang.String>, long, java.util.function.LongBinaryOperator) ,public java.lang.String reduceValues(long, BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public U reduceValues(long, Function<? super java.lang.String,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public double reduceValuesToDouble(long, ToDoubleFunction<? super java.lang.String>, double, java.util.function.DoubleBinaryOperator) ,public int reduceValuesToInt(long, ToIntFunction<? super java.lang.String>, int, java.util.function.IntBinaryOperator) ,public long reduceValuesToLong(long, ToLongFunction<? super java.lang.String>, long, java.util.function.LongBinaryOperator) ,public java.lang.String remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public java.lang.String replace(java.lang.String, java.lang.String) ,public boolean replace(java.lang.String, java.lang.String, java.lang.String) ,public void replaceAll(BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public U search(long, BiFunction<? super java.lang.String,? super java.lang.String,? extends U>) ,public U searchEntries(long, Function<Entry<java.lang.String,java.lang.String>,? extends U>) ,public U searchKeys(long, Function<? super java.lang.String,? extends U>) ,public U searchValues(long, Function<? super java.lang.String,? extends U>) ,public int size() ,public java.lang.String toString() ,public Collection<java.lang.String> values() <variables>private static final int ABASE,private static final int ASHIFT,private static final long BASECOUNT,private static final long CELLSBUSY,private static final long CELLVALUE,private static final int DEFAULT_CAPACITY,private static final int DEFAULT_CONCURRENCY_LEVEL,static final int HASH_BITS,private static final float LOAD_FACTOR,private static final int MAXIMUM_CAPACITY,static final int MAX_ARRAY_SIZE,private static final int MAX_RESIZERS,private static final int MIN_TRANSFER_STRIDE,static final int MIN_TREEIFY_CAPACITY,static final int MOVED,static final int NCPU,static final int RESERVED,private static final int RESIZE_STAMP_BITS,private static final int RESIZE_STAMP_SHIFT,private static final long SIZECTL,private static final long TRANSFERINDEX,static final int TREEBIN,static final int TREEIFY_THRESHOLD,private static final jdk.internal.misc.Unsafe U,static final int UNTREEIFY_THRESHOLD,private volatile transient long baseCount,private volatile transient int cellsBusy,private volatile transient java.util.concurrent.ConcurrentHashMap.CounterCell[] counterCells,private transient EntrySetView<java.lang.String,java.lang.String> entrySet,private transient KeySetView<java.lang.String,java.lang.String> keySet,private volatile transient Node<java.lang.String,java.lang.String>[] nextTable,private static final java.io.ObjectStreamField[] serialPersistentFields,private static final long serialVersionUID,private volatile transient int sizeCtl,volatile transient Node<java.lang.String,java.lang.String>[] table,private volatile transient int transferIndex,private transient ValuesView<java.lang.String,java.lang.String> values
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/util/JacksonFeatureSet.java
|
JacksonFeatureSet
|
fromDefaults
|
class JacksonFeatureSet<F extends JacksonFeature>
implements java.io.Serializable // since 2.16
{
private static final long serialVersionUID = 1L;
protected int _enabled;
/**
* Constructor for creating instance with specific bitmask, wherein
* {@code 1} bit means matching {@link JacksonFeature} is enabled and
* {@code 0} disabled.
*
* @param bitmask Bitmask for features that are enabled
*/
protected JacksonFeatureSet(int bitmask) {
_enabled = bitmask;
}
/**
* "Default" factory which will calculate settings based on default-enabled
* status of all features.
*
* @param <F> Self-reference type for convenience
*
* @param allFeatures Set of all features (enabled or disabled): usually from
* {@code Enum.values()}
*
* @return Feature set instance constructed
*/
public static <F extends JacksonFeature> JacksonFeatureSet<F> fromDefaults(F[] allFeatures) {<FILL_FUNCTION_BODY>}
public static <F extends JacksonFeature> JacksonFeatureSet<F> fromBitmask(int bitmask) {
return new JacksonFeatureSet<>(bitmask);
}
/**
* Mutant factory for getting a set in which specified feature is enabled:
* will either return this instance (if no change), or newly created set (if there
* is change).
*
* @param feature Feature to enable in set returned
*
* @return Newly created set of state of feature changed; {@code this} if not
*/
public JacksonFeatureSet<F> with(F feature) {
int newMask = _enabled | feature.getMask();
return (newMask == _enabled) ? this : new JacksonFeatureSet<>(newMask);
}
/**
* Mutant factory for getting a set in which specified feature is disabled:
* will either return this instance (if no change), or newly created set (if there
* is change).
*
* @param feature Feature to disable in set returned
*
* @return Newly created set of state of feature changed; {@code this} if not
*/
public JacksonFeatureSet<F> without(F feature) {
int newMask = _enabled & ~feature.getMask();
return (newMask == _enabled) ? this : new JacksonFeatureSet<>(newMask);
}
/**
* Main accessor for checking whether given feature is enabled in this feature set.
*
* @param feature Feature to check
*
* @return True if feature is enabled in this set; false otherwise
*/
public boolean isEnabled(F feature) {
return (feature.getMask() & _enabled) != 0;
}
/**
* Accessor for underlying bitmask
*
* @return Bitmask of enabled features
*/
public int asBitmask() {
return _enabled;
}
}
|
// first sanity check
if (allFeatures.length > 31) {
final String desc = allFeatures[0].getClass().getName();
throw new IllegalArgumentException(String.format(
"Can not use type `%s` with JacksonFeatureSet: too many entries (%d > 31)",
desc, allFeatures.length));
}
int flags = 0;
for (F f : allFeatures) {
if (f.enabledByDefault()) {
flags |= f.getMask();
}
}
return new JacksonFeatureSet<>(flags);
| 734
| 142
| 876
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/util/JsonParserSequence.java
|
JsonParserSequence
|
nextToken
|
class JsonParserSequence extends JsonParserDelegate
{
/**
* Parsers other than the first one (which is initially assigned
* as delegate)
*/
protected final JsonParser[] _parsers;
/**
* Configuration that determines whether state of parsers is first verified
* to see if parser already points to a token (that is,
* {@link JsonParser#hasCurrentToken()} returns <code>true</code>), and if so
* that token is first return before {@link JsonParser#nextToken} is called.
* If enabled, this check is made; if disabled, no check is made and
* {@link JsonParser#nextToken} is always called for all parsers.
*<p>
* Default setting is <code>false</code> (for backwards-compatibility)
* so that possible existing token is not considered for parsers.
*
* @since 2.8
*/
protected final boolean _checkForExistingToken;
/**
* Index of the next parser in {@link #_parsers}.
*/
protected int _nextParserIndex;
/**
* Flag used to indicate that `JsonParser.nextToken()` should not be called,
* due to parser already pointing to a token.
*
* @since 2.8
*/
protected boolean _hasToken;
/*
*******************************************************
* Construction
*******************************************************
*/
@Deprecated // since 2.8
protected JsonParserSequence(JsonParser[] parsers) {
this(false, parsers);
}
// @since 2.8
protected JsonParserSequence(boolean checkForExistingToken, JsonParser[] parsers)
{
super(parsers[0]);
_checkForExistingToken = checkForExistingToken;
_hasToken = checkForExistingToken && delegate.hasCurrentToken();
_parsers = parsers;
_nextParserIndex = 1;
}
/**
* Method that will construct a sequence (possibly a sequence) that
* contains all given sub-parsers.
* All parsers given are checked to see if they are sequences: and
* if so, they will be "flattened", that is, contained parsers are
* directly added in a new sequence instead of adding sequences
* within sequences. This is done to minimize delegation depth,
* ideally only having just a single level of delegation.
*
* @param checkForExistingToken Flag passed to be assigned as
* {@link #_checkForExistingToken} for resulting sequence
* @param first First parser to traverse
* @param second Second parser to traverse
*
* @return Sequence instance constructed
*/
public static JsonParserSequence createFlattened(boolean checkForExistingToken,
JsonParser first, JsonParser second)
{
if (!(first instanceof JsonParserSequence || second instanceof JsonParserSequence)) {
return new JsonParserSequence(checkForExistingToken,
new JsonParser[] { first, second });
}
ArrayList<JsonParser> p = new ArrayList<>();
if (first instanceof JsonParserSequence) {
((JsonParserSequence) first).addFlattenedActiveParsers(p);
} else {
p.add(first);
}
if (second instanceof JsonParserSequence) {
((JsonParserSequence) second).addFlattenedActiveParsers(p);
} else {
p.add(second);
}
return new JsonParserSequence(checkForExistingToken,
p.toArray(new JsonParser[p.size()]));
}
@Deprecated // since 2.8
public static JsonParserSequence createFlattened(JsonParser first, JsonParser second) {
return createFlattened(false, first, second);
}
@SuppressWarnings("resource")
protected void addFlattenedActiveParsers(List<JsonParser> listToAddIn)
{
for (int i = _nextParserIndex-1, len = _parsers.length; i < len; ++i) {
JsonParser p = _parsers[i];
if (p instanceof JsonParserSequence) {
((JsonParserSequence) p).addFlattenedActiveParsers(listToAddIn);
} else {
listToAddIn.add(p);
}
}
}
/*
/*******************************************************
/* Overridden methods, needed: cases where default
/* delegation does not work
/*******************************************************
*/
@Override
public void close() throws IOException {
do { delegate.close(); } while (switchToNext());
}
@Override
public JsonToken nextToken() throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Need to override, re-implement similar to how method defined in
* {@link com.fasterxml.jackson.core.base.ParserMinimalBase}, to keep
* state correct here.
*/
@Override
public JsonParser skipChildren() throws IOException
{
if ((delegate.currentToken() != JsonToken.START_OBJECT)
&& (delegate.currentToken() != JsonToken.START_ARRAY)) {
return this;
}
int open = 1;
// Since proper matching of start/end markers is handled
// by nextToken(), we'll just count nesting levels here
while (true) {
JsonToken t = nextToken();
if (t == null) { // not ideal but for now, just return
return this;
}
if (t.isStructStart()) {
++open;
} else if (t.isStructEnd()) {
if (--open == 0) {
return this;
}
}
}
}
/*
/*******************************************************
/* Additional extended API
/*******************************************************
*/
/**
* Method that is most useful for debugging or testing;
* returns actual number of underlying parsers sequence
* was constructed with (nor just ones remaining active)
*
* @return Number of actual underlying parsers this sequence has
*/
public int containedParsersCount() {
return _parsers.length;
}
/*
/*******************************************************
/* Helper methods
/*******************************************************
*/
/**
* Method that will switch active delegate parser from the current one
* to the next parser in sequence, if there is another parser left:
* if so, the next parser will become the active delegate parser.
*
* @return True if switch succeeded; false otherwise
*
* @since 2.8
*/
protected boolean switchToNext()
{
if (_nextParserIndex < _parsers.length) {
delegate = _parsers[_nextParserIndex++];
return true;
}
return false;
}
protected JsonToken switchAndReturnNext() throws IOException
{
while (_nextParserIndex < _parsers.length) {
delegate = _parsers[_nextParserIndex++];
if (_checkForExistingToken && delegate.hasCurrentToken()) {
return delegate.getCurrentToken();
}
JsonToken t = delegate.nextToken();
if (t != null) {
return t;
}
}
return null;
}
}
|
if (delegate == null) {
return null;
}
if (_hasToken) {
_hasToken = false;
return delegate.currentToken();
}
JsonToken t = delegate.nextToken();
if (t == null) {
return switchAndReturnNext();
}
return t;
| 1,869
| 85
| 1,954
|
<methods>public void <init>(com.fasterxml.jackson.core.JsonParser) ,public void assignCurrentValue(java.lang.Object) ,public boolean canParseAsync() ,public boolean canReadObjectId() ,public boolean canReadTypeId() ,public boolean canUseSchema(com.fasterxml.jackson.core.FormatSchema) ,public void clearCurrentToken() ,public void close() throws java.io.IOException,public com.fasterxml.jackson.core.JsonLocation currentLocation() ,public java.lang.String currentName() throws java.io.IOException,public com.fasterxml.jackson.core.JsonToken currentToken() ,public int currentTokenId() ,public com.fasterxml.jackson.core.JsonLocation currentTokenLocation() ,public java.lang.Object currentValue() ,public com.fasterxml.jackson.core.JsonParser delegate() ,public com.fasterxml.jackson.core.JsonParser disable(com.fasterxml.jackson.core.JsonParser.Feature) ,public com.fasterxml.jackson.core.JsonParser enable(com.fasterxml.jackson.core.JsonParser.Feature) ,public void finishToken() throws java.io.IOException,public java.math.BigInteger getBigIntegerValue() throws java.io.IOException,public byte[] getBinaryValue(com.fasterxml.jackson.core.Base64Variant) throws java.io.IOException,public boolean getBooleanValue() throws java.io.IOException,public byte getByteValue() throws java.io.IOException,public com.fasterxml.jackson.core.ObjectCodec getCodec() ,public com.fasterxml.jackson.core.JsonLocation getCurrentLocation() ,public java.lang.String getCurrentName() throws java.io.IOException,public com.fasterxml.jackson.core.JsonToken getCurrentToken() ,public int getCurrentTokenId() ,public java.lang.Object getCurrentValue() ,public java.math.BigDecimal getDecimalValue() throws java.io.IOException,public double getDoubleValue() throws java.io.IOException,public java.lang.Object getEmbeddedObject() throws java.io.IOException,public int getFeatureMask() ,public float getFloatValue() throws java.io.IOException,public java.lang.Object getInputSource() ,public int getIntValue() throws java.io.IOException,public com.fasterxml.jackson.core.JsonToken getLastClearedToken() ,public long getLongValue() throws java.io.IOException,public com.fasterxml.jackson.core.async.NonBlockingInputFeeder getNonBlockingInputFeeder() ,public com.fasterxml.jackson.core.JsonParser.NumberType getNumberType() throws java.io.IOException,public com.fasterxml.jackson.core.JsonParser.NumberTypeFP getNumberTypeFP() throws java.io.IOException,public java.lang.Number getNumberValue() throws java.io.IOException,public java.lang.Object getNumberValueDeferred() throws java.io.IOException,public java.lang.Number getNumberValueExact() throws java.io.IOException,public java.lang.Object getObjectId() throws java.io.IOException,public com.fasterxml.jackson.core.JsonStreamContext getParsingContext() ,public JacksonFeatureSet<com.fasterxml.jackson.core.StreamReadCapability> getReadCapabilities() ,public com.fasterxml.jackson.core.FormatSchema getSchema() ,public short getShortValue() throws java.io.IOException,public java.lang.String getText() throws java.io.IOException,public int getText(java.io.Writer) throws java.io.IOException, java.lang.UnsupportedOperationException,public char[] getTextCharacters() throws java.io.IOException,public int getTextLength() throws java.io.IOException,public int getTextOffset() throws java.io.IOException,public com.fasterxml.jackson.core.JsonLocation getTokenLocation() ,public java.lang.Object getTypeId() throws java.io.IOException,public boolean getValueAsBoolean() throws java.io.IOException,public boolean getValueAsBoolean(boolean) throws java.io.IOException,public double getValueAsDouble() throws java.io.IOException,public double getValueAsDouble(double) throws java.io.IOException,public int getValueAsInt() throws java.io.IOException,public int getValueAsInt(int) throws java.io.IOException,public long getValueAsLong() throws java.io.IOException,public long getValueAsLong(long) throws java.io.IOException,public java.lang.String getValueAsString() throws java.io.IOException,public java.lang.String getValueAsString(java.lang.String) throws java.io.IOException,public boolean hasCurrentToken() ,public boolean hasTextCharacters() ,public boolean hasToken(com.fasterxml.jackson.core.JsonToken) ,public boolean hasTokenId(int) ,public boolean isClosed() ,public boolean isEnabled(com.fasterxml.jackson.core.JsonParser.Feature) ,public boolean isExpectedNumberIntToken() ,public boolean isExpectedStartArrayToken() ,public boolean isExpectedStartObjectToken() ,public boolean isNaN() throws java.io.IOException,public com.fasterxml.jackson.core.JsonToken nextToken() throws java.io.IOException,public com.fasterxml.jackson.core.JsonToken nextValue() throws java.io.IOException,public void overrideCurrentName(java.lang.String) ,public com.fasterxml.jackson.core.JsonParser overrideFormatFeatures(int, int) ,public com.fasterxml.jackson.core.JsonParser overrideStdFeatures(int, int) ,public int readBinaryValue(com.fasterxml.jackson.core.Base64Variant, java.io.OutputStream) throws java.io.IOException,public boolean requiresCustomCodec() ,public void setCodec(com.fasterxml.jackson.core.ObjectCodec) ,public void setCurrentValue(java.lang.Object) ,public com.fasterxml.jackson.core.JsonParser setFeatureMask(int) ,public void setSchema(com.fasterxml.jackson.core.FormatSchema) ,public com.fasterxml.jackson.core.JsonParser skipChildren() throws java.io.IOException,public com.fasterxml.jackson.core.StreamReadConstraints streamReadConstraints() ,public com.fasterxml.jackson.core.Version version() <variables>protected com.fasterxml.jackson.core.JsonParser delegate
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/util/JsonRecyclerPools.java
|
BoundedPool
|
construct
|
class BoundedPool extends BoundedPoolBase<BufferRecycler>
{
private static final long serialVersionUID = 1L;
protected static final BoundedPool GLOBAL = new BoundedPool(SERIALIZATION_SHARED);
// // // Life-cycle (constructors, factory methods)
protected BoundedPool(int capacityAsId) {
super(capacityAsId);
}
public static BoundedPool construct(int capacity) {<FILL_FUNCTION_BODY>}
@Override
public BufferRecycler createPooled() {
return new BufferRecycler();
}
// // // JDK serialization support
// Make sure to re-link to global/shared or non-shared.
protected Object readResolve() {
return _resolveToShared(GLOBAL).orElseGet(() -> construct(_serialization));
}
}
|
if (capacity <= 0) {
throw new IllegalArgumentException("capacity must be > 0, was: "+capacity);
}
return new BoundedPool(capacity);
| 227
| 48
| 275
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/util/RequestPayload.java
|
RequestPayload
|
toString
|
class RequestPayload
implements java.io.Serializable // just in case, even though likely included as transient
{
private static final long serialVersionUID = 1L;
// request payload as byte[]
protected byte[] _payloadAsBytes;
// request payload as String
protected CharSequence _payloadAsText;
// Charset if the request payload is set in bytes
protected String _charset;
public RequestPayload(byte[] bytes, String charset) {
if (bytes == null) {
throw new IllegalArgumentException();
}
_payloadAsBytes = bytes;
_charset = (charset == null || charset.isEmpty()) ? "UTF-8" : charset;
}
public RequestPayload(CharSequence str) {
if (str == null) {
throw new IllegalArgumentException();
}
_payloadAsText = str;
}
/**
* Returns the raw request payload object i.e, either byte[] or String
*
* @return Object which is a raw request payload i.e, either byte[] or
* String
*/
public Object getRawPayload() {
if (_payloadAsBytes != null) {
return _payloadAsBytes;
}
return _payloadAsText;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
if (_payloadAsBytes != null) {
try {
return new String(_payloadAsBytes, _charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return _payloadAsText.toString();
| 347
| 70
| 417
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/util/ThreadLocalBufferManager.java
|
ThreadLocalBufferManager
|
releaseBuffers
|
class ThreadLocalBufferManager
{
/**
* A lock to make sure releaseBuffers is only executed by one thread at a time
* since it iterates over and modifies the allSoftBufRecyclers.
*/
private final ReentrantLock RELEASE_LOCK = new ReentrantLock();
/**
* A set of all SoftReferences to all BufferRecyclers to be able to release them on shutdown.
* 'All' means the ones created by this class, in this classloader.
* There may be more from other classloaders.
* We use a HashSet to have quick O(1) add and remove operations.
*<p>
* NOTE: assumption is that {@link SoftReference} has its {@code equals()} and
* {@code hashCode()} implementations defined so that they use object identity, so
* we do not need to use something like {@link IdentityHashMap}
*/
private final Map<SoftReference<BufferRecycler>,Boolean> _trackedRecyclers
= new ConcurrentHashMap<>();
/**
* Queue where gc will put just-cleared SoftReferences, previously referencing BufferRecyclers.
* We use it to remove the cleared softRefs from the above set.
*/
private final ReferenceQueue<BufferRecycler> _refQueue = new ReferenceQueue<>();
/*
/**********************************************************
/* Public API
/**********************************************************
*/
/**
* Returns the lazily initialized singleton instance
*/
public static ThreadLocalBufferManager instance() {
return ThreadLocalBufferManagerHolder.manager;
}
/**
* Releases the buffers retained in ThreadLocals. To be called for instance on shutdown event of applications which make use of
* an environment like an appserver which stays alive and uses a thread pool that causes ThreadLocals created by the
* application to survive much longer than the application itself.
* It will clear all bufRecyclers from the SoftRefs and release all SoftRefs itself from our set.
*/
public int releaseBuffers() {<FILL_FUNCTION_BODY>}
public SoftReference<BufferRecycler> wrapAndTrack(BufferRecycler br) {
SoftReference<BufferRecycler> newRef;
newRef = new SoftReference<>(br, _refQueue);
// also retain softRef to br in a set to be able to release it on shutdown
_trackedRecyclers.put(newRef, true);
// gc may have cleared one or more SoftRefs, clean them up to avoid a memleak
removeSoftRefsClearedByGc();
return newRef;
}
/*
/**********************************************************
/* Internal methods
/**********************************************************
*/
/**
* Remove cleared (inactive) SoftRefs from our set. Gc may have cleared one or more,
* and made them inactive.
*/
private void removeSoftRefsClearedByGc() {
SoftReference<?> clearedSoftRef;
while ((clearedSoftRef = (SoftReference<?>) _refQueue.poll()) != null) {
// uses reference-equality, quick, and O(1) removal by HashSet
_trackedRecyclers.remove(clearedSoftRef);
}
}
/**
* ThreadLocalBufferManagerHolder uses the thread-safe initialize-on-demand, holder class idiom that implicitly
* incorporates lazy initialization by declaring a static variable within a static Holder inner class
*/
private static final class ThreadLocalBufferManagerHolder {
static final ThreadLocalBufferManager manager = new ThreadLocalBufferManager();
}
}
|
int count = 0;
RELEASE_LOCK.lock();
try {
// does this need to be in sync block too? Looping over Map definitely has to but...
removeSoftRefsClearedByGc(); // make sure the refQueue is empty
for (SoftReference<BufferRecycler> ref : _trackedRecyclers.keySet()) {
ref.clear(); // possibly already cleared by gc, nothing happens in that case
++count;
}
_trackedRecyclers.clear(); //release cleared SoftRefs
} finally {
RELEASE_LOCK.unlock();
}
return count;
| 903
| 156
| 1,059
|
<no_super_class>
|
FasterXML_jackson-core
|
jackson-core/src/main/java/com/fasterxml/jackson/core/util/VersionUtil.java
|
VersionUtil
|
versionFor
|
class VersionUtil
{
private final static Pattern V_SEP = Pattern.compile("[-_./;:]");
/*
/**********************************************************************
/* Instance life-cycle
/**********************************************************************
*/
protected VersionUtil() { }
@Deprecated // since 2.9
public Version version() { return Version.unknownVersion(); }
/*
/**********************************************************************
/* Static load methods
/**********************************************************************
*/
/**
* Loads version information by introspecting a class named
* "PackageVersion" in the same package as the given class.
*<p>
* If the class could not be found or does not have a public
* static Version field named "VERSION", returns "empty" {@link Version}
* returned by {@link Version#unknownVersion()}.
*
* @param cls Class for which to look version information
*
* @return Version information discovered if any;
* {@link Version#unknownVersion()} if none
*/
public static Version versionFor(Class<?> cls)
{<FILL_FUNCTION_BODY>}
/**
* Alias of {@link #versionFor(Class)}.
*
* @param cls Class for which to look version information
*
* @return Version information discovered if any;
* {@link Version#unknownVersion()} if none
*
* @deprecated Since 2.12 simply use {@link #versionFor(Class)} instead
*/
@Deprecated
public static Version packageVersionFor(Class<?> cls) {
return versionFor(cls);
}
/**
* Will attempt to load the maven version for the given groupId and
* artifactId. Maven puts a pom.properties file in
* META-INF/maven/groupId/artifactId, containing the groupId,
* artifactId and version of the library.
*
* @param cl the ClassLoader to load the pom.properties file from
* @param groupId the groupId of the library
* @param artifactId the artifactId of the library
* @return The version
*
* @deprecated Since 2.6: functionality not used by any official Jackson component, should be
* moved out if anyone needs it
*/
@SuppressWarnings("resource")
@Deprecated // since 2.6
public static Version mavenVersionFor(ClassLoader cl, String groupId, String artifactId)
{
InputStream pomProperties = cl.getResourceAsStream("META-INF/maven/"
+ groupId.replaceAll("\\.", "/")+ "/" + artifactId + "/pom.properties");
if (pomProperties != null) {
try {
Properties props = new Properties();
props.load(pomProperties);
String versionStr = props.getProperty("version");
String pomPropertiesArtifactId = props.getProperty("artifactId");
String pomPropertiesGroupId = props.getProperty("groupId");
return parseVersion(versionStr, pomPropertiesGroupId, pomPropertiesArtifactId);
} catch (IOException e) {
// Ignore
} finally {
_close(pomProperties);
}
}
return Version.unknownVersion();
}
/**
* Method used by <code>PackageVersion</code> classes to decode version injected by Maven build.
*
* @param s Version String to parse
* @param groupId Maven group id to include with version
* @param artifactId Maven artifact id to include with version
*
* @return Version instance constructed from parsed components, if successful;
* {@link Version#unknownVersion()} if parsing of components fail
*/
public static Version parseVersion(String s, String groupId, String artifactId)
{
if (s != null && (s = s.trim()).length() > 0) {
String[] parts = V_SEP.split(s);
return new Version(parseVersionPart(parts[0]),
(parts.length > 1) ? parseVersionPart(parts[1]) : 0,
(parts.length > 2) ? parseVersionPart(parts[2]) : 0,
(parts.length > 3) ? parts[3] : null,
groupId, artifactId);
}
return Version.unknownVersion();
}
protected static int parseVersionPart(String s) {
int number = 0;
for (int i = 0, len = s.length(); i < len; ++i) {
char c = s.charAt(i);
if (c > '9' || c < '0') break;
number = (number * 10) + (c - '0');
}
return number;
}
private final static void _close(Closeable c) {
try {
c.close();
} catch (IOException e) { }
}
/*
/**********************************************************************
/* Orphan utility methods
/**********************************************************************
*/
public final static void throwInternal() {
throw new RuntimeException("Internal error: this code path should never get executed");
}
public final static <T> T throwInternalReturnAny() {
throw new RuntimeException("Internal error: this code path should never get executed");
}
}
|
Version v = null;
try {
String versionInfoClassName = cls.getPackage().getName() + ".PackageVersion";
Class<?> vClass = Class.forName(versionInfoClassName, true, cls.getClassLoader());
// However, if class exists, it better work correctly, no swallowing exceptions
try {
v = ((Versioned) vClass.getDeclaredConstructor().newInstance()).version();
} catch (Exception e) {
throw new IllegalArgumentException("Failed to get Versioned out of "+vClass);
}
} catch (Exception e) {
// ok to be missing (not good but acceptable)
;
}
return (v == null) ? Version.unknownVersion() : v;
| 1,318
| 183
| 1,501
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/encrypt/EncryptionService.java
|
EncryptionService
|
replaceAll
|
class EncryptionService {
private final StringEncryptor encryptor;
private final Pattern reCharsREP;
@SuppressWarnings("ReplaceAllDot")
/**
* <p>Constructor for EncryptionService.</p>
*
* @param encryptor a {@link org.jasypt.encryption.StringEncryptor} object
*/
public EncryptionService(final StringEncryptor encryptor) {
this.encryptor = encryptor;
String regExSpecialChars = "<([{\\^-=$!|]})?*+.>";
String regExSpecialCharsRE = regExSpecialChars.replaceAll(".", "\\\\$0");
this.reCharsREP = Pattern.compile("[" + regExSpecialCharsRE + "]");
}
private String quoteRegExSpecialChars(String s) {
Matcher m = reCharsREP.matcher(s);
return m.replaceAll("\\\\$0");
}
/**
* Replace all instance of pattern in the templateText, according to the replacer.
*
* @param templateText the template
* @param sourcePrefix property prefix
* @param sourceSuffix property suffix
* @param targetPrefix property prefix
* @param targetSuffix property suffix
* @param mutator the replacement generator
* @return the replaced content
*/
private String replaceAll(
final String templateText,
final String sourcePrefix,
final String sourceSuffix,
final String targetPrefix,
final String targetSuffix,
final Function<String, String> mutator
) {<FILL_FUNCTION_BODY>}
/**
* Decrypt all placeholders in the input.
*
* @param input the string to scan for placeholders and decrypt
* @return the input with decrypted placeholders.
* @param encryptPrefix a {@link java.lang.String} object
* @param encryptSuffix a {@link java.lang.String} object
* @param decryptPrefix a {@link java.lang.String} object
* @param decryptSuffix a {@link java.lang.String} object
*/
public String decrypt(final String input, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) {
return replaceAll(input, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix, encryptor::decrypt);
}
/**
* Decrypt a value
*
* @param value the value
* @return decrypted value
*/
public String decryptValue(String value) {
return encryptor.decrypt(value);
}
/**
* Encrypt all placeholders in the input.
*
* @param input the string to scan for placeholders and encrypt
* @return the input with encrypted placeholders.
* @param encryptPrefix a {@link java.lang.String} object
* @param encryptSuffix a {@link java.lang.String} object
* @param decryptPrefix a {@link java.lang.String} object
* @param decryptSuffix a {@link java.lang.String} object
*/
public String encrypt(final String input, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) {
return replaceAll(input, decryptPrefix, decryptSuffix, encryptPrefix, encryptSuffix, encryptor::encrypt);
}
/**
* Encrypt a value
*
* @param value the value
* @return encrypted value
*/
public String encryptValue(String value) {
return encryptor.encrypt(value);
}
/**
* <p>getEncryptableProperties.</p>
*
* @return a {@link org.jasypt.properties.EncryptableProperties} object
*/
public EncryptableProperties getEncryptableProperties() {
return new EncryptableProperties(encryptor);
}
}
|
String regex = quoteRegExSpecialChars(sourcePrefix) + "(.*?)" + quoteRegExSpecialChars(sourceSuffix);
Pattern pattern = Pattern.compile(regex, DOTALL);
Matcher matcher = pattern.matcher(templateText);
StringBuffer result = new StringBuffer();
String replacement;
while (matcher.find()) {
String matched = matcher.group(1);
replacement = targetPrefix + mutator.apply(matched) + targetSuffix;
log.debug("Converting value {} to {}", matched, replacement);
matcher.appendReplacement(result, "");
result.append(replacement);
}
matcher.appendTail(result);
return result.toString();
| 1,029
| 187
| 1,216
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/AbstractFileJasyptMojo.java
|
AbstractFileJasyptMojo
|
getFullFilePath
|
class AbstractFileJasyptMojo extends AbstractJasyptMojo {
/**
* The path of the file to operate on.
*/
@Parameter(property = "jasypt.plugin.path",
defaultValue = "file:src/main/resources/application.properties")
private String path = "file:src/main/resources/application.properties";
@Override
void run(EncryptionService encryptionService, ConfigurableApplicationContext context, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix)
throws MojoExecutionException {
run(encryptionService, getFullFilePath(context), encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
}
/**
* Run the encryption task.
*
* @param encryptionService the service for encryption
* @param fullPath the path to operate on
* @param encryptPrefix encryption prefix
* @param encryptSuffix encryption suffix
* @param decryptPrefix decryption prefix
* @param decryptSuffix decryption suffix
*/
abstract void run(EncryptionService encryptionService, Path fullPath, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix)
throws MojoExecutionException;
/**
* Construct the full file path, relative to the active environment.
*
* @param context the context (for retrieving active environments)
* @return the full path
* @throws MojoExecutionException if the file does not exist
*/
private Path getFullFilePath(final ApplicationContext context)
throws MojoExecutionException {<FILL_FUNCTION_BODY>}
}
|
try {
return context.getResource(path).getFile().toPath();
} catch (IOException e) {
throw new MojoExecutionException("Unable to open configuration file", e);
}
| 420
| 53
| 473
|
<methods>public non-sealed void <init>() ,public void execute() throws MojoExecutionException<variables>private java.lang.String decryptPrefix,private java.lang.String decryptSuffix,private java.lang.String encryptPrefix,private java.lang.String encryptSuffix,private org.springframework.core.env.Environment environment
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/AbstractJasyptMojo.java
|
AbstractJasyptMojo
|
execute
|
class AbstractJasyptMojo extends AbstractMojo {
/**
* The encrypted property prefix
*/
@Parameter(property = "jasypt.plugin.encrypt.prefix", defaultValue = "ENC(")
private String encryptPrefix = "ENC(";
/**
* The encrypted property suffix
*/
@Parameter(property = "jasypt.plugin.encrypt.suffix", defaultValue = ")")
private String encryptSuffix = ")";
/**
* The decrypted property prefix
*/
@Parameter(property = "jasypt.plugin.decrypt.prefix", defaultValue = "DEC(")
private String decryptPrefix = "DEC(";
/**
* The decrypted property suffix
*/
@Parameter(property = "jasypt.plugin.decrypt.suffix", defaultValue = ")")
private String decryptSuffix = ")";
private Environment environment;
/**
* <p>Getter for the field <code>environment</code>.</p>
*
* @return a {@link org.springframework.core.env.Environment} object
*/
protected Environment getEnvironment() {
return environment;
}
/** {@inheritDoc} */
@Override
public void execute() throws MojoExecutionException {<FILL_FUNCTION_BODY>}
/**
* Run the encryption task.
*
* @param encryptionService the service for encryption
* @param context app context
*/
abstract void run(EncryptionService encryptionService, ConfigurableApplicationContext context, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix)
throws MojoExecutionException;
}
|
Map<String, Object> defaultProperties = new HashMap<>();
defaultProperties.put("spring.config.location", "optional:file:./src/main/resources/");
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.sources(Application.class)
.bannerMode(Banner.Mode.OFF)
.properties(defaultProperties)
.run();
this.environment = context.getEnvironment();
String[] activeProfiles = context.getEnvironment().getActiveProfiles();
String profiles = activeProfiles.length != 0 ? String.join(",", activeProfiles) : "Default";
log.info("Active Profiles: {}", profiles);
StringEncryptor encryptor = context.getBean(StringEncryptor.class);
run(new EncryptionService(encryptor), context, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
| 426
| 226
| 652
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/AbstractReencryptMojo.java
|
AbstractReencryptMojo
|
run
|
class AbstractReencryptMojo extends AbstractFileJasyptMojo {
/** {@inheritDoc} */
protected void run(final EncryptionService newService, final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws MojoExecutionException {<FILL_FUNCTION_BODY>}
private String decrypt(final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws MojoExecutionException {
log.info("Decrypting file " + path);
try {
String contents = FileService.read(path);
return getOldEncryptionService().decrypt(contents, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
} catch (Exception e) {
throw new MojoExecutionException("Error Decrypting: " + e.getMessage(), e);
}
}
private EncryptionService getOldEncryptionService() {
JasyptEncryptorConfigurationProperties properties = new JasyptEncryptorConfigurationProperties();
configure(properties);
StringEncryptor encryptor = new StringEncryptorBuilder(properties, "jasypt.plugin.old").build();
return new EncryptionService(encryptor);
}
/**
* <p>configure.</p>
*
* @param properties a {@link com.ulisesbocchio.jasyptspringboot.properties.JasyptEncryptorConfigurationProperties} object
*/
protected abstract void configure(JasyptEncryptorConfigurationProperties properties);
/**
* <p>setIfNotNull.</p>
*
* @param setter a {@link java.util.function.Consumer} object
* @param value a T object
* @param <T> a T class
*/
protected <T> void setIfNotNull(Consumer<T> setter, T value) {
if (value != null) {
setter.accept(value);
}
}
}
|
String decryptedContents = decrypt(path, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
log.info("Re-encrypting file " + path);
try {
String encryptedContents = newService.encrypt(decryptedContents, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
FileService.write(path, encryptedContents);
} catch (Exception e) {
throw new MojoExecutionException("Error Re-encrypting: " + e.getMessage(), e);
}
| 503
| 140
| 643
|
<methods>public non-sealed void <init>() <variables>private java.lang.String path
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/AbstractValueJasyptMojo.java
|
AbstractValueJasyptMojo
|
run
|
class AbstractValueJasyptMojo extends AbstractJasyptMojo {
/**
* The decrypted property suffix
*/
@Parameter(property = "jasypt.plugin.value")
private String value = null;
@Override
void run(EncryptionService encryptionService, ConfigurableApplicationContext context, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix)
throws MojoExecutionException {<FILL_FUNCTION_BODY>}
/**
* Run the encryption task.
*
* @param encryptionService the service for encryption
* @param value the value to operate on
* @param encryptPrefix encryption prefix
* @param encryptSuffix encryption suffix
* @param decryptPrefix decryption prefix
* @param decryptSuffix decryption suffix
*/
abstract void run(EncryptionService encryptionService, String value, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix)
throws MojoExecutionException;
}
|
if (value == null) {
throw new MojoExecutionException("No jasypt.plugin.value property provided");
}
run(encryptionService, value, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
| 262
| 65
| 327
|
<methods>public non-sealed void <init>() ,public void execute() throws MojoExecutionException<variables>private java.lang.String decryptPrefix,private java.lang.String decryptSuffix,private java.lang.String encryptPrefix,private java.lang.String encryptSuffix,private org.springframework.core.env.Environment environment
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/DecryptMojo.java
|
DecryptMojo
|
run
|
class DecryptMojo extends AbstractFileJasyptMojo {
/** {@inheritDoc} */
@Override
protected void run(final EncryptionService service, final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws
MojoExecutionException {<FILL_FUNCTION_BODY>}
}
|
log.info("Decrypting file " + path);
try {
String contents = FileService.read(path);
String decryptedContents = service.decrypt(contents, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
log.info("\n" + decryptedContents);
} catch (Exception e) {
throw new MojoExecutionException("Error Decrypting: " + e.getMessage(), e);
}
| 90
| 114
| 204
|
<methods>public non-sealed void <init>() <variables>private java.lang.String path
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/DecryptValueMojo.java
|
DecryptValueMojo
|
run
|
class DecryptValueMojo extends AbstractValueJasyptMojo {
/** {@inheritDoc} */
@Override
protected void run(final EncryptionService service, final String value, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws
MojoExecutionException {<FILL_FUNCTION_BODY>}
}
|
try {
String actualValue = value.startsWith(encryptPrefix) ? value.substring(encryptPrefix.length(), value.length() - encryptSuffix.length()) : value;
log.info("Decrypting value " + actualValue);
String decryptedValue = service.decryptValue(actualValue);
log.info("\n" + decryptedValue);
} catch (Exception e) {
throw new MojoExecutionException("Error Decrypting: " + e.getMessage(), e);
}
| 91
| 129
| 220
|
<methods>public non-sealed void <init>() <variables>private java.lang.String value
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/EncryptMojo.java
|
EncryptMojo
|
run
|
class EncryptMojo extends AbstractFileJasyptMojo {
private static final Logger LOGGER = LoggerFactory.getLogger(EncryptMojo.class);
/** {@inheritDoc} */
@Override
protected void run(final EncryptionService service, final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws
MojoExecutionException {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Encrypting file " + path);
try {
String contents = FileService.read(path);
String encryptedContents = service.encrypt(contents, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
FileService.write(path, encryptedContents);
} catch (Exception e) {
throw new MojoExecutionException("Error Encrypting: " + e.getMessage(), e);
}
| 114
| 115
| 229
|
<methods>public non-sealed void <init>() <variables>private java.lang.String path
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/EncryptValueMojo.java
|
EncryptValueMojo
|
run
|
class EncryptValueMojo extends AbstractValueJasyptMojo {
/** {@inheritDoc} */
@Override
protected void run(final EncryptionService service, final String value, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws
MojoExecutionException {<FILL_FUNCTION_BODY>}
}
|
try {
String actualValue = value.startsWith(decryptPrefix) ? value.substring(decryptPrefix.length(), value.length() - decryptSuffix.length()) : value;
log.info("Encrypting value " + actualValue);
String encryptedValue = encryptPrefix + service.encryptValue(actualValue) + encryptSuffix;
log.info("\n" + encryptedValue);
} catch (Exception e) {
throw new MojoExecutionException("Error Encrypting: " + e.getMessage(), e);
}
| 91
| 138
| 229
|
<methods>public non-sealed void <init>() <variables>private java.lang.String value
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/FileService.java
|
FileService
|
read
|
class FileService {
/**
* Read a file.
*
* @param path the file path
* @return the contents.
* @throws org.apache.maven.plugin.MojoExecutionException if any.
*/
public static String read(final Path path) throws MojoExecutionException {<FILL_FUNCTION_BODY>}
/**
* Write to a file.
*
* @param path the file path
* @param contents the contents to write
* @throws org.apache.maven.plugin.MojoExecutionException if any.
*/
public static void write(final Path path, final String contents) throws MojoExecutionException {
try {
Files.write(path, contents.getBytes());
} catch (IOException e) {
throw new MojoExecutionException("Unable to write file " + path, e);
}
}
/**
* Load a file into properties.
*
* @param path the path
* @param properties the properties to mutate
* @throws org.apache.maven.plugin.MojoExecutionException if any.
*/
public static void load(final Path path, final Properties properties)
throws MojoExecutionException {
try {
properties.load(Files.newInputStream(path));
} catch (IOException e) {
throw new MojoExecutionException("Unable to load file " + path, e);
}
}
}
|
try {
return new String(Files.readAllBytes(path));
} catch (IOException e) {
throw new MojoExecutionException("Unable to read file " + path, e);
}
| 354
| 53
| 407
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/LoadMojo.java
|
LoadMojo
|
run
|
class LoadMojo extends AbstractFileJasyptMojo {
private static final Logger LOGGER = LoggerFactory.getLogger(LoadMojo.class);
/**
* Prefix that will be added before name of each property. Can be useful for distinguishing the
* source of the properties from other maven properties.
*/
@Parameter(property = "jasypt.plugin.keyPrefix")
private String keyPrefix = null;
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
/** {@inheritDoc} */
@Override
protected void run(final EncryptionService service, final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws
MojoExecutionException {<FILL_FUNCTION_BODY>}
}
|
Properties properties = service.getEncryptableProperties();
FileService.load(path, properties);
if (properties.isEmpty()) {
LOGGER.info(" No properties found");
} else {
for (String key : properties.stringPropertyNames()) {
LOGGER.info(" Loaded '" + key + "' property");
}
}
Properties projectProperties = project.getProperties();
for (String key : properties.stringPropertyNames()) {
if (keyPrefix != null) {
projectProperties.put(keyPrefix + key, properties.get(key));
} else {
projectProperties.put(key, properties.get(key));
}
}
| 211
| 172
| 383
|
<methods>public non-sealed void <init>() <variables>private java.lang.String path
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/ReencryptMojo.java
|
ReencryptMojo
|
configure
|
class ReencryptMojo extends AbstractReencryptMojo {
@Parameter(property = "jasypt.plugin.old.password") private String oldPassword;
@Parameter(property = "jasypt.plugin.old.private-key-string") private String oldPrivateKeyString;
@Parameter(property = "jasypt.plugin.old.private-key-location") private String oldPrivateKeyLocation;
@Parameter(property = "jasypt.plugin.old.private-key-format") private AsymmetricCryptography.KeyFormat oldPrivateKeyFormat;
@Parameter(property = "jasypt.plugin.old.algorithm") private String oldAlgorithm;
@Parameter(property = "jasypt.plugin.old.key-obtention-iterations") private String oldKeyObtentionIterations;
@Parameter(property = "jasypt.plugin.old.pool-size") private String oldPoolSize;
@Parameter(property = "jasypt.plugin.old.provider-name") private String oldProviderName;
@Parameter(property = "jasypt.plugin.old.provider-class-name") private String oldProviderClassName;
@Parameter(property = "jasypt.plugin.old.salt-generator-classname") private String oldSaltGeneratorClassname;
@Parameter(property = "jasypt.plugin.old.iv-generator-classname") private String oldIvGeneratorClassname;
@Parameter(property = "jasypt.plugin.old.string-output-type") private String oldStringOutputType;
/** {@inheritDoc} */
@Override
protected void configure(JasyptEncryptorConfigurationProperties properties) {<FILL_FUNCTION_BODY>}
}
|
setIfNotNull(properties::setPassword, oldPassword);
setIfNotNull(properties::setPrivateKeyString, oldPrivateKeyString);
setIfNotNull(properties::setPrivateKeyLocation, oldPrivateKeyLocation);
setIfNotNull(properties::setPrivateKeyFormat, oldPrivateKeyFormat);
setIfNotNull(properties::setAlgorithm, oldAlgorithm);
setIfNotNull(properties::setKeyObtentionIterations, oldKeyObtentionIterations);
setIfNotNull(properties::setPoolSize, oldPoolSize);
setIfNotNull(properties::setProviderName, oldProviderName);
setIfNotNull(properties::setProviderClassName, oldProviderClassName);
setIfNotNull(properties::setSaltGeneratorClassname, oldSaltGeneratorClassname);
setIfNotNull(properties::setIvGeneratorClassname, oldIvGeneratorClassname);
setIfNotNull(properties::setStringOutputType, oldStringOutputType);
| 410
| 224
| 634
|
<methods>public non-sealed void <init>() <variables>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-maven-plugin/src/main/java/com/ulisesbocchio/jasyptmavenplugin/mojo/UpgradeMojo.java
|
UpgradeMojo
|
configure
|
class UpgradeMojo extends AbstractReencryptMojo {
@Parameter(property = "jasypt.plugin.old.major-version", defaultValue = "2")
private int oldMajorVersion = 2;
/** {@inheritDoc} */
@Override
protected void configure(JasyptEncryptorConfigurationProperties properties) {<FILL_FUNCTION_BODY>}
private void upgradeFrom2(JasyptEncryptorConfigurationProperties properties) {
properties.setAlgorithm("PBEWithMD5AndDES");
properties.setKeyObtentionIterations("1000");
properties.setPoolSize("1");
properties.setProviderName(null);
properties.setProviderClassName(null);
properties.setSaltGeneratorClassname("org.jasypt.salt.RandomSaltGenerator");
properties.setIvGeneratorClassname("org.jasypt.iv.NoIvGenerator");
properties.setStringOutputType("base64");
}
}
|
Environment environment = getEnvironment();
setIfNotNull(properties::setPassword, environment.getProperty("jasypt.encryptor.password"));
setIfNotNull(properties::setPrivateKeyFormat, environment.getProperty("jasypt.encryptor.private-key-format", AsymmetricCryptography.KeyFormat.class));
setIfNotNull(properties::setPrivateKeyString, environment.getProperty("jasypt.encryptor.private-key-string"));
setIfNotNull(properties::setPrivateKeyLocation, environment.getProperty("jasypt.encryptor.private-key-location"));
if (oldMajorVersion == 2) {
upgradeFrom2(properties);
} else {
throw new RuntimeException("Unrecognised major version " + oldMajorVersion);
}
| 245
| 193
| 438
|
<methods>public non-sealed void <init>() <variables>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/aop/EncryptableMutablePropertySourcesInterceptor.java
|
EncryptableMutablePropertySourcesInterceptor
|
invoke
|
class EncryptableMutablePropertySourcesInterceptor implements MethodInterceptor {
private final EncryptablePropertySourceConverter propertyConverter;
private final EnvCopy envCopy;
/**
* <p>Constructor for EncryptableMutablePropertySourcesInterceptor.</p>
*
* @param propertyConverter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter} object
* @param envCopy a {@link com.ulisesbocchio.jasyptspringboot.configuration.EnvCopy} object
*/
public EncryptableMutablePropertySourcesInterceptor(EncryptablePropertySourceConverter propertyConverter, EnvCopy envCopy) {
this.propertyConverter = propertyConverter;
this.envCopy = envCopy;
}
private Object makeEncryptable(Object propertySource) {
return propertyConverter.makeEncryptable((PropertySource<?>) propertySource);
}
/** {@inheritDoc} */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
String method = invocation.getMethod().getName();
Object[] arguments = invocation.getArguments();
switch (method) {
case "addFirst":
envCopy.addFirst((PropertySource<?>) arguments[0]);
return invocation.getMethod().invoke(invocation.getThis(), makeEncryptable(arguments[0]));
case "addLast":
envCopy.addLast((PropertySource<?>) arguments[0]);
return invocation.getMethod().invoke(invocation.getThis(), makeEncryptable(arguments[0]));
case "addBefore":
envCopy.addBefore((String) arguments[0], (PropertySource<?>) arguments[1]);
return invocation.getMethod().invoke(invocation.getThis(), arguments[0], makeEncryptable(arguments[1]));
case "addAfter":
envCopy.addAfter((String) arguments[0], (PropertySource<?>) arguments[1]);
return invocation.getMethod().invoke(invocation.getThis(), arguments[0], makeEncryptable(arguments[1]));
case "replace":
envCopy.replace((String) arguments[0], (PropertySource<?>) arguments[1]);
return invocation.getMethod().invoke(invocation.getThis(), arguments[0], makeEncryptable(arguments[1]));
case "remove":
envCopy.remove((String) arguments[0]);
return invocation.proceed();
default:
return invocation.proceed();
}
| 277
| 371
| 648
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/aop/EncryptablePropertySourceMethodInterceptor.java
|
EncryptablePropertySourceMethodInterceptor
|
invoke
|
class EncryptablePropertySourceMethodInterceptor<T> extends CachingDelegateEncryptablePropertySource<T> implements MethodInterceptor {
/**
* <p>Constructor for EncryptablePropertySourceMethodInterceptor.</p>
*
* @param delegate a {@link org.springframework.core.env.PropertySource} object
* @param resolver a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver} object
* @param filter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyFilter} object
*/
public EncryptablePropertySourceMethodInterceptor(PropertySource<T> delegate, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter) {
super(delegate, resolver, filter);
}
/** {@inheritDoc} */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
private String getNameArgument(MethodInvocation invocation) {
return (String) invocation.getArguments()[0];
}
private boolean isGetDelegateCall(MethodInvocation invocation) {
return invocation.getMethod().getName().equals("getDelegate");
}
private boolean isRefreshCall(MethodInvocation invocation) {
return invocation.getMethod().getName().equals("refresh");
}
private boolean isGetPropertyCall(MethodInvocation invocation) {
return invocation.getMethod().getName().equals("getProperty")
&& invocation.getMethod().getParameters().length == 1
&& invocation.getMethod().getParameters()[0].getType() == String.class;
}
}
|
if (isRefreshCall(invocation)) {
refresh();
return null;
}
if (isGetDelegateCall(invocation)) {
return getDelegate();
}
if (isGetPropertyCall(invocation)) {
return getProperty(getNameArgument(invocation));
}
return invocation.proceed();
| 424
| 87
| 511
|
<methods>public void <init>(PropertySource<T>, com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver, com.ulisesbocchio.jasyptspringboot.EncryptablePropertyFilter) ,public PropertySource<T> getDelegate() ,public java.lang.Object getProperty(java.lang.String) ,public void refresh() <variables>private final non-sealed Map<java.lang.String,com.ulisesbocchio.jasyptspringboot.caching.CachingDelegateEncryptablePropertySource.CachedValue> cache,private final non-sealed PropertySource<T> delegate,private final non-sealed com.ulisesbocchio.jasyptspringboot.EncryptablePropertyFilter filter,private final non-sealed com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver resolver
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/caching/CachingDelegateEncryptablePropertySource.java
|
CachingDelegateEncryptablePropertySource
|
getProperty
|
class CachingDelegateEncryptablePropertySource<T> extends PropertySource<T> implements EncryptablePropertySource<T> {
private final PropertySource<T> delegate;
private final EncryptablePropertyResolver resolver;
private final EncryptablePropertyFilter filter;
private final Map<String, CachedValue> cache;
/**
* <p>Constructor for CachingDelegateEncryptablePropertySource.</p>
*
* @param delegate a {@link org.springframework.core.env.PropertySource} object
* @param resolver a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver} object
* @param filter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyFilter} object
*/
public CachingDelegateEncryptablePropertySource(PropertySource<T> delegate, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter) {
super(delegate.getName(), delegate.getSource());
Assert.notNull(delegate, "PropertySource delegate cannot be null");
Assert.notNull(resolver, "EncryptablePropertyResolver cannot be null");
Assert.notNull(filter, "EncryptablePropertyFilter cannot be null");
this.delegate = delegate;
this.resolver = resolver;
this.filter = filter;
this.cache = new ConcurrentHashMap<>();
}
/** {@inheritDoc} */
@Override
public PropertySource<T> getDelegate() {
return delegate;
}
/** {@inheritDoc} */
@Override
public Object getProperty(String name) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void refresh() {
log.info("Property Source {} refreshed", delegate.getName());
cache.clear();
}
@AllArgsConstructor
private static class CachedValue {
private final String originValue;
private final String resolvedValue;
}
}
|
//The purpose of this cache is to reduce the cost of decryption,
// so it's not a bad idea to read the original property every time, it's generally fast.
Object originValue = delegate.getProperty(name);
if (!(originValue instanceof String)) {
//Because we read the original property every time, if it isn't a String,
// there's no point in caching it.
return originValue;
}
CachedValue cachedValue = cache.get(name);
if (cachedValue != null && Objects.equals(originValue, cachedValue.originValue)) {
// If the original property has not changed, it is safe to return the cached result.
return cachedValue.resolvedValue;
}
//originValue must be String here
if (filter.shouldInclude(delegate, name)) {
String originStringValue = (String) originValue;
String resolved = resolver.resolvePropertyValue(originStringValue);
CachedValue newCachedValue = new CachedValue(originStringValue, resolved);
//If the mapping relationship in the cache changes during
// the calculation process, then ignore it directly.
if (cachedValue == null) {
cache.putIfAbsent(name, newCachedValue);
} else {
cache.replace(name, cachedValue, newCachedValue);
}
//return the result calculated this time
return resolved;
}
return originValue;
| 495
| 359
| 854
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, T) ,public boolean containsProperty(java.lang.String) ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public abstract java.lang.Object getProperty(java.lang.String) ,public T getSource() ,public int hashCode() ,public static PropertySource<?> named(java.lang.String) ,public java.lang.String toString() <variables>protected final org.apache.commons.logging.Log logger,protected final java.lang.String name,protected final T source
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/caching/RefreshScopeRefreshedEventListener.java
|
RefreshScopeRefreshedEventListener
|
shouldTriggerRefresh
|
class RefreshScopeRefreshedEventListener implements ApplicationListener<ApplicationEvent>, InitializingBean {
/** Constant <code>EVENT_CLASS_NAMES</code> */
public static final List<String> EVENT_CLASS_NAMES = Arrays.asList(
"org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent",
"org.springframework.cloud.context.environment.EnvironmentChangeEvent",
"org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent"
);
private final ConfigurableEnvironment environment;
private final EncryptablePropertySourceConverter converter;
private final List<Class<?>> eventClasses = new ArrayList<>();
private final Map<String, Boolean> eventTriggersCache = new ConcurrentHashMap<>();
private final JasyptEncryptorConfigurationProperties config;
/**
* <p>Constructor for RefreshScopeRefreshedEventListener.</p>
*
* @param environment a {@link org.springframework.core.env.ConfigurableEnvironment} object
* @param converter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter} object
* @param config a {@link com.ulisesbocchio.jasyptspringboot.properties.JasyptEncryptorConfigurationProperties} object
*/
public RefreshScopeRefreshedEventListener(ConfigurableEnvironment environment, EncryptablePropertySourceConverter converter, JasyptEncryptorConfigurationProperties config) {
this.environment = environment;
this.converter = converter;
this.config = config;
}
/** {@inheritDoc} */
@Override
@SneakyThrows
public void onApplicationEvent(ApplicationEvent event) {
// log.info("APPLICATION EVENT: {}", event.getClass().getName());
if (this.shouldTriggerRefresh(event)) {
log.info("Refreshing cached encryptable property sources on {}", event.getClass().getSimpleName());
refreshCachedProperties();
decorateNewSources();
}
}
private boolean shouldTriggerRefresh(ApplicationEvent event) {<FILL_FUNCTION_BODY>}
private void decorateNewSources() {
MutablePropertySources propSources = environment.getPropertySources();
converter.convertPropertySources(propSources);
}
boolean isAssignable(Class<?> clazz, Object value) {
return ClassUtils.isAssignableValue(clazz, value);
}
private void refreshCachedProperties() {
PropertySources propertySources = environment.getPropertySources();
propertySources.forEach(this::refreshPropertySource);
}
@SuppressWarnings("rawtypes")
private void refreshPropertySource(PropertySource<?> propertySource) {
if (propertySource instanceof CompositePropertySource) {
CompositePropertySource cps = (CompositePropertySource) propertySource;
cps.getPropertySources().forEach(this::refreshPropertySource);
} else if (propertySource instanceof EncryptablePropertySource) {
EncryptablePropertySource eps = (EncryptablePropertySource) propertySource;
eps.refresh();
}
}
private Class<?> getClassSafe(String className) {
try {
return ClassUtils.forName(className, null);
} catch (ClassNotFoundException e) {
return null;
}
}
/** {@inheritDoc} */
@Override
public void afterPropertiesSet() throws Exception {
Stream
.concat(EVENT_CLASS_NAMES.stream(), this.config.getRefreshedEventClasses().stream())
.map(this::getClassSafe).filter(Objects::nonNull)
.collect(Collectors.toCollection(() -> this.eventClasses));
}
}
|
String className = event.getClass().getName();
if (!eventTriggersCache.containsKey(className)) {
eventTriggersCache.put(className, eventClasses.stream().anyMatch(clazz -> this.isAssignable(clazz, event)));
}
return eventTriggersCache.get(className);
| 946
| 83
| 1,029
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/condition/OnMissingBeanCondition.java
|
OnMissingBeanCondition
|
getMatchOutcome
|
class OnMissingBeanCondition extends SpringBootCondition implements ConfigurationCondition {
/** {@inheritDoc} */
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public ConfigurationPhase getConfigurationPhase() {
return ConfigurationPhase.REGISTER_BEAN;
}
}
|
Map<String, Object> beanAttributes = metadata.getAnnotationAttributes(Bean.class.getName());
String beanName = ((String[]) beanAttributes.get("name"))[0];
if(!StringUtils.hasLength(beanName)) {
throw new IllegalStateException("OnMissingBeanCondition can't detect bean name!");
}
boolean missingBean = !context.getBeanFactory().containsBean(context.getEnvironment().resolveRequiredPlaceholders(beanName));
return missingBean ? ConditionOutcome.match(beanName + " not found") : ConditionOutcome.noMatch(beanName + " found");
| 107
| 145
| 252
|
<methods>public void <init>() ,public abstract org.springframework.boot.autoconfigure.condition.ConditionOutcome getMatchOutcome(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) ,public final boolean matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) <variables>private final org.apache.commons.logging.Log logger
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/configuration/BeanNamePlaceholderRegistryPostProcessor.java
|
BeanNamePlaceholderRegistryPostProcessor
|
postProcessBeanDefinitionRegistry
|
class BeanNamePlaceholderRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered {
private Environment environment;
BeanNamePlaceholderRegistryPostProcessor(Environment environment) {
this.environment = environment;
}
/** {@inheritDoc} */
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
/** {@inheritDoc} */
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE - 1;
}
}
|
DefaultListableBeanFactory bf = (DefaultListableBeanFactory) registry;
Stream.of(bf.getBeanDefinitionNames())
//Look for beans with placeholders name format: '${placeholder}' or '${placeholder:defaultValue}'
.filter(name -> name.matches("\\$\\{[\\w.-]+(?>:[\\w.-]+)?\\}"))
.forEach(placeholder -> {
String actualName = environment.resolveRequiredPlaceholders(placeholder);
BeanDefinition bd = bf.getBeanDefinition(placeholder);
bf.removeBeanDefinition(placeholder);
bf.registerBeanDefinition(actualName, bd);
log.debug("Registering new name '{}' for Bean definition with placeholder name: {}", actualName, placeholder);
});
| 184
| 200
| 384
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/configuration/EncryptablePropertySourceBeanFactoryPostProcessor.java
|
EncryptablePropertySourceBeanFactoryPostProcessor
|
loadEncryptablePropertySource
|
class EncryptablePropertySourceBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {
private static final String CONFIGURATION_CLASS_ATTRIBUTE =
Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");
private ConfigurableEnvironment env;
/**
* <p>Constructor for EncryptablePropertySourceBeanFactoryPostProcessor.</p>
*
* @param env a {@link org.springframework.core.env.ConfigurableEnvironment} object
*/
public EncryptablePropertySourceBeanFactoryPostProcessor(ConfigurableEnvironment env) {
this.env = env;
}
/** {@inheritDoc} */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
ResourceLoader ac = new DefaultResourceLoader();
MutablePropertySources propertySources = env.getPropertySources();
Stream<AnnotationAttributes> encryptablePropertySourcesMetadata = getEncryptablePropertySourcesMetadata(beanFactory);
EncryptablePropertyResolver propertyResolver = beanFactory.getBean(RESOLVER_BEAN_NAME, EncryptablePropertyResolver.class);
EncryptablePropertyFilter propertyFilter = beanFactory.getBean(FILTER_BEAN_NAME, EncryptablePropertyFilter.class);
List<PropertySourceLoader> loaders = initPropertyLoaders();
encryptablePropertySourcesMetadata.forEach(eps -> loadEncryptablePropertySource(eps, env, ac, propertyResolver, propertyFilter, propertySources, loaders));
}
private List<PropertySourceLoader> initPropertyLoaders() {
return SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader());
}
private void loadEncryptablePropertySource(AnnotationAttributes encryptablePropertySource, ConfigurableEnvironment env, ResourceLoader resourceLoader, EncryptablePropertyResolver resolver, EncryptablePropertyFilter propertyFilter, MutablePropertySources propertySources, List<PropertySourceLoader> loaders) throws BeansException {<FILL_FUNCTION_BODY>}
private PropertySource createPropertySource(AnnotationAttributes attributes, ConfigurableEnvironment environment, ResourceLoader resourceLoader, EncryptablePropertyResolver resolver, EncryptablePropertyFilter propertyFilter, List<PropertySourceLoader> loaders) throws Exception {
String name = generateName(attributes.getString("name"));
String[] locations = attributes.getStringArray("value");
boolean ignoreResourceNotFound = attributes.getBoolean("ignoreResourceNotFound");
CompositePropertySource compositePropertySource = new OriginTrackedCompositePropertySource(name);
Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
for (String location : locations) {
String resolvedLocation = environment.resolveRequiredPlaceholders(location);
Resource resource = resourceLoader.getResource(resolvedLocation);
if (!resource.exists()) {
if (!ignoreResourceNotFound) {
throw new IllegalStateException(String.format("Encryptable Property Source '%s' from location: %s Not Found", name, resolvedLocation));
} else {
log.info("Ignoring NOT FOUND Encryptable Property Source '{}' from locations: {}", name, resolvedLocation);
}
} else {
String actualName = name + "#" + resolvedLocation;
loadPropertySource(loaders, resource, actualName)
.ifPresent(psources -> psources.forEach(compositePropertySource::addPropertySource));
}
}
return new EncryptableEnumerablePropertySourceWrapper<>(compositePropertySource, resolver, propertyFilter);
}
private String generateName(String name) {
return StringUtils.hasLength(name) ? name : "EncryptedPropertySource#" + System.currentTimeMillis();
}
private Stream<AnnotationAttributes> getEncryptablePropertySourcesMetadata(ConfigurableListableBeanFactory beanFactory) {
return getBeanDefinitionsForAnnotation(beanFactory, com.ulisesbocchio.jasyptspringboot.annotation.EncryptablePropertySource.class, EncryptablePropertySources.class);
}
private Stream<AnnotationAttributes> getBeanDefinitionsForAnnotation(ConfigurableListableBeanFactory bf, Class<? extends Annotation> annotation, Class<? extends Annotation> repeatable) {
return Stream.concat(Arrays.stream(bf.getBeanNamesForAnnotation(annotation)), Arrays.stream(bf.getBeanNamesForAnnotation(repeatable)))
.distinct()
.map(bf::getBeanDefinition)
.filter(bd -> bd instanceof AnnotatedBeanDefinition)
.map(bd -> (AnnotatedBeanDefinition) bd)
.filter(bd -> bd.getAttribute(CONFIGURATION_CLASS_ATTRIBUTE) != null && bd instanceof AbstractBeanDefinition)
.map(AnnotatedBeanDefinition::getMetadata)
.filter(am -> am.hasAnnotation(annotation.getName()) || am.hasAnnotation(repeatable.getName()))
.flatMap(am -> Optional
.ofNullable((AnnotationAttributes) am.getAnnotationAttributes(annotation.getName()))
.map(Stream::of)
.orElseGet(() -> Optional
.ofNullable((AnnotationAttributes) am.getAnnotationAttributes(repeatable.getName()))
.map(ram -> Arrays.stream(ram.getAnnotationArray("value")))
.orElseGet(Stream::empty)));
}
private Optional<List<PropertySource<?>>> loadPropertySource(List<PropertySourceLoader> loaders, Resource resource, String sourceName) throws IOException {
return Optional.of(resource)
.filter(this::isFile)
.flatMap(res -> loaders.stream()
.filter(loader -> canLoadFileExtension(loader, resource))
.findFirst()
.map(loader -> load(loader, sourceName, resource)));
}
@SneakyThrows
private List<PropertySource<?>> load(PropertySourceLoader loader, String sourceName, Resource resource) {
return loader.load(sourceName, resource);
}
private boolean canLoadFileExtension(PropertySourceLoader loader, Resource resource) {
return Arrays.stream(loader.getFileExtensions())
.anyMatch(extension -> Objects.requireNonNull(resource.getFilename()).toLowerCase().endsWith("." + extension.toLowerCase()));
}
private boolean isFile(Resource resource) {
return resource != null && resource.exists() && StringUtils
.hasText(StringUtils.getFilenameExtension(resource.getFilename()));
}
/** {@inheritDoc} */
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE - 100;
}
}
|
try {
log.info("Loading Encryptable Property Source '{}'", encryptablePropertySource.getString("name"));
PropertySource ps = createPropertySource(encryptablePropertySource, env, resourceLoader, resolver, propertyFilter, loaders);
propertySources.addLast(ps);
log.info("Created Encryptable Property Source '{}' from locations: {}", ps.getName(), Arrays.asList(encryptablePropertySource.getStringArray("value")));
} catch (Exception e) {
throw new ApplicationContextException("Exception Creating PropertySource", e);
}
| 1,634
| 144
| 1,778
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/configuration/EnvCopy.java
|
EnvCopy
|
replace
|
class EnvCopy {
StandardEnvironment copy;
/**
* <p>Constructor for EnvCopy.</p>
*
* @param environment a {@link org.springframework.core.env.ConfigurableEnvironment} object
*/
public EnvCopy(final ConfigurableEnvironment environment) {
copy = new StandardEnvironment();
Optional
.ofNullable(environment instanceof EncryptableEnvironment ? ((EncryptableEnvironment) environment).getOriginalPropertySources() : environment.getPropertySources())
.ifPresent(sources -> sources.forEach(this::addLast));
}
@SuppressWarnings({"rawtypes"})
private PropertySource<?> getOriginal(PropertySource<?> propertySource) {
return propertySource instanceof EncryptablePropertySource
? ((EncryptablePropertySource) propertySource).getDelegate()
: propertySource;
}
/**
* <p>isAllowed.</p>
*
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
* @return a boolean
*/
public boolean isAllowed(PropertySource<?> propertySource) {
final PropertySource<?> original = getOriginal(propertySource);
return !original.getClass().getName().equals("org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource");
}
/**
* <p>addFirst.</p>
*
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void addFirst(PropertySource<?> propertySource) {
if (isAllowed(propertySource)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().addFirst(original);
}
}
/**
* <p>addLast.</p>
*
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void addLast(PropertySource<?> propertySource) {
if (isAllowed(propertySource)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().addLast(original);
}
}
/**
* <p>addBefore.</p>
*
* @param relativePropertySourceName a {@link java.lang.String} object
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void addBefore(String relativePropertySourceName, PropertySource<?> propertySource) {
if (isAllowed(propertySource)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().addBefore(relativePropertySourceName, original);
}
}
/**
* <p>addAfter.</p>
*
* @param relativePropertySourceName a {@link java.lang.String} object
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) {
if (isAllowed(propertySource)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().addAfter(relativePropertySourceName, original);
}
}
/**
* <p>replace.</p>
*
* @param name a {@link java.lang.String} object
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void replace(String name, PropertySource<?> propertySource) {<FILL_FUNCTION_BODY>}
/**
* <p>remove.</p>
*
* @param name a {@link java.lang.String} object
* @return a {@link org.springframework.core.env.PropertySource} object
*/
public PropertySource<?> remove(String name) {
return copy.getPropertySources().remove(name);
}
/**
* <p>get.</p>
*
* @return a {@link org.springframework.core.env.ConfigurableEnvironment} object
*/
public ConfigurableEnvironment get() {
return copy;
}
}
|
if(isAllowed(propertySource)) {
if(copy.getPropertySources().contains(name)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().replace(name, original);
}
}
| 1,070
| 68
| 1,138
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/configuration/StringEncryptorBuilder.java
|
StringEncryptorBuilder
|
build
|
class StringEncryptorBuilder {
private final JasyptEncryptorConfigurationProperties configProps;
private final String propertyPrefix;
/**
* <p>Constructor for StringEncryptorBuilder.</p>
*
* @param configProps a {@link com.ulisesbocchio.jasyptspringboot.properties.JasyptEncryptorConfigurationProperties} object
* @param propertyPrefix a {@link java.lang.String} object
*/
public StringEncryptorBuilder(JasyptEncryptorConfigurationProperties configProps, String propertyPrefix) {
this.configProps = configProps;
this.propertyPrefix = propertyPrefix;
}
/**
* <p>build.</p>
*
* @return a {@link org.jasypt.encryption.StringEncryptor} object
*/
public StringEncryptor build() {<FILL_FUNCTION_BODY>}
private boolean isGCMConfig() {
return configProps.getGcmSecretKeyString() != null || configProps.getGcmSecretKeyLocation() !=null || configProps.getGcmSecretKeyPassword() != null;
}
private boolean isPBEConfig() {
return configProps.getPassword() != null;
}
private boolean isAsymmetricConfig() {
return configProps.getPrivateKeyString() != null || configProps.getPrivateKeyLocation() != null || configProps.getPublicKeyString() != null || configProps.getPublicKeyLocation() != null;
}
private StringEncryptor createGCMDefault() {
SimpleGCMConfig config = new SimpleGCMConfig();
// config.setAlgorithm(get(configProps::getAlgorithm, propertyPrefix + ".algorithm", "AES/GCM/NoPadding"));
config.setSecretKey(get(configProps::getGcmSecretKeyString, propertyPrefix + ".gcm-secret-key-string", null));
config.setSecretKeyLocation(get(configProps::getGcmSecretKeyLocation, propertyPrefix + ".gcm-secret-key-location", null));
config.setSecretKeyPassword(get(configProps::getGcmSecretKeyPassword, propertyPrefix + ".gcm-key-password", null));
config.setSecretKeySalt(get(configProps::getGcmSecretKeySalt, propertyPrefix + ".gcm-secret-key-salt", null));
config.setSecretKeyAlgorithm(get(configProps::getGcmSecretKeyAlgorithm, propertyPrefix + ".gcm-secret-key-algorithm", "PBKDF2WithHmacSHA256"));
config.setSecretKeyIterations(get(configProps::getKeyObtentionIterationsInt, propertyPrefix + ".key-obtention-iterations", 1000));
config.setIvGeneratorClassName(get(configProps::getIvGeneratorClassname, propertyPrefix + ".iv-generator-classname", "org.jasypt.iv.RandomIvGenerator"));
return new SimpleGCMStringEncryptor(config);
}
private StringEncryptor createAsymmetricDefault() {
SimpleAsymmetricConfig config = new SimpleAsymmetricConfig();
config.setPrivateKey(get(configProps::getPrivateKeyString, propertyPrefix + ".private-key-string", null));
config.setPrivateKeyLocation(get(configProps::getPrivateKeyLocation, propertyPrefix + ".private-key-location", null));
config.setPrivateKeyFormat(get(configProps::getPrivateKeyFormat, propertyPrefix + ".private-key-format", AsymmetricCryptography.KeyFormat.DER));
config.setPublicKey(get(configProps::getPublicKeyString, propertyPrefix + ".public-key-string", null));
config.setPublicKeyLocation(get(configProps::getPublicKeyLocation, propertyPrefix + ".public-key-location", null));
config.setPublicKeyFormat(get(configProps::getPublicKeyFormat, propertyPrefix + ".public-key-format", AsymmetricCryptography.KeyFormat.DER));
return new SimpleAsymmetricStringEncryptor(config);
}
private StringEncryptor createPBEDefault() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(getRequired(configProps::getPassword, propertyPrefix + ".password"));
config.setAlgorithm(get(configProps::getAlgorithm, propertyPrefix + ".algorithm", "PBEWITHHMACSHA512ANDAES_256"));
config.setKeyObtentionIterations(get(configProps::getKeyObtentionIterations, propertyPrefix + ".key-obtention-iterations", "1000"));
config.setPoolSize(get(configProps::getPoolSize, propertyPrefix + ".pool-size", "1"));
config.setProviderName(get(configProps::getProviderName, propertyPrefix + ".provider-name", null));
config.setProviderClassName(get(configProps::getProviderClassName, propertyPrefix + ".provider-class-name", null));
config.setSaltGeneratorClassName(get(configProps::getSaltGeneratorClassname, propertyPrefix + ".salt-generator-classname", "org.jasypt.salt.RandomSaltGenerator"));
config.setIvGeneratorClassName(get(configProps::getIvGeneratorClassname, propertyPrefix + ".iv-generator-classname", "org.jasypt.iv.RandomIvGenerator"));
config.setStringOutputType(get(configProps::getStringOutputType, propertyPrefix + ".string-output-type", "base64"));
encryptor.setConfig(config);
return encryptor;
}
private <T> T getRequired(Supplier<T> supplier, String key) {
T value = supplier.get();
if (value == null) {
throw new IllegalStateException(String.format("Required Encryption configuration property missing: %s", key));
}
return value;
}
private <T> T get(Supplier<T> supplier, String key, T defaultValue) {
T value = supplier.get();
if (value == defaultValue) {
log.info("Encryptor config not found for property {}, using default value: {}", key, value);
}
return value;
}
}
|
if (isPBEConfig()) {
return createPBEDefault();
} else if (isAsymmetricConfig()) {
return createAsymmetricDefault();
} else if (isGCMConfig()) {
return createGCMDefault();
} else {
throw new IllegalStateException("either '" + propertyPrefix + ".password', one of ['" + propertyPrefix + ".private-key-string', '" + propertyPrefix + ".private-key-location'] for asymmetric encryption, or one of ['" + propertyPrefix + ".gcm-secret-key-string', '" + propertyPrefix + ".gcm-secret-key-location', '" + propertyPrefix + ".gcm-secret-key-password'] for AES/GCM encryption must be provided for Password-based or Asymmetric encryption");
}
| 1,552
| 189
| 1,741
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/detector/DefaultPropertyDetector.java
|
DefaultPropertyDetector
|
isEncrypted
|
class DefaultPropertyDetector implements EncryptablePropertyDetector {
private String prefix = "ENC(";
private String suffix = ")";
/**
* <p>Constructor for DefaultPropertyDetector.</p>
*/
public DefaultPropertyDetector() {
}
/**
* <p>Constructor for DefaultPropertyDetector.</p>
*
* @param prefix a {@link java.lang.String} object
* @param suffix a {@link java.lang.String} object
*/
public DefaultPropertyDetector(String prefix, String suffix) {
Assert.notNull(prefix, "Prefix can't be null");
Assert.notNull(suffix, "Suffix can't be null");
this.prefix = prefix;
this.suffix = suffix;
}
/** {@inheritDoc} */
@Override
public boolean isEncrypted(String property) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public String unwrapEncryptedValue(String property) {
return property.substring(
prefix.length(),
(property.length() - suffix.length()));
}
}
|
if (property == null) {
return false;
}
final String trimmedValue = property.trim();
return (trimmedValue.startsWith(prefix) &&
trimmedValue.endsWith(suffix));
| 295
| 59
| 354
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/encryptor/PooledStringEncryptor.java
|
PooledStringEncryptor
|
robin
|
class PooledStringEncryptor implements StringEncryptor {
private final int size;
private final StringEncryptor[] pool;
private final AtomicInteger roundRobin;
/**
* <p>Constructor for PooledStringEncryptor.</p>
*
* @param size a int
* @param encryptorFactory a {@link java.util.function.Supplier} object
*/
public PooledStringEncryptor(int size, Supplier<StringEncryptor> encryptorFactory) {
this.size = size;
this.pool = IntStream.range(0, this.size).boxed().map(v -> {
StringEncryptor encryptor = encryptorFactory.get();
if (encryptor instanceof ThreadSafeStringEncryptor) {
return encryptor;
}
return new ThreadSafeStringEncryptor(encryptor);
}).toArray(StringEncryptor[]::new);
this.roundRobin = new AtomicInteger();
}
private <T> T robin(Function<StringEncryptor, T> producer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public String encrypt(String message) {
return robin(e -> e.encrypt(message));
}
/** {@inheritDoc} */
@Override
public String decrypt(String encryptedMessage) {
return robin(e -> e.decrypt(encryptedMessage));
}
public static class ThreadSafeStringEncryptor implements StringEncryptor {
private final StringEncryptor delegate;
public ThreadSafeStringEncryptor(StringEncryptor delegate) {
this.delegate = delegate;
}
@Override
public synchronized String encrypt(String message) {
return delegate.encrypt(message);
}
@Override
public synchronized String decrypt(String encryptedMessage) {
return delegate.decrypt(encryptedMessage);
}
}
}
|
int position = this.roundRobin.getAndUpdate(value -> (value + 1) % this.size);
return producer.apply(this.pool[position]);
| 506
| 45
| 551
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/encryptor/SimpleAsymmetricConfig.java
|
SimpleAsymmetricConfig
|
loadResource
|
class SimpleAsymmetricConfig {
private String privateKey = null;
private String publicKey = null;
private String privateKeyLocation = null;
private String publicKeyLocation = null;
private Resource privateKeyResource = null;
private Resource publicKeyResource = null;
private ResourceLoader resourceLoader = new DefaultResourceLoader();
private KeyFormat privateKeyFormat = KeyFormat.DER;
private KeyFormat publicKeyFormat = KeyFormat.DER;
private Resource loadResource(Resource asResource, String asString, String asLocation, KeyFormat format, String type) {<FILL_FUNCTION_BODY>}
/**
* <p>loadPrivateKeyResource.</p>
*
* @return a {@link org.springframework.core.io.Resource} object
*/
public Resource loadPrivateKeyResource() {
return loadResource(privateKeyResource, privateKey, privateKeyLocation, privateKeyFormat, "Private");
}
/**
* <p>loadPublicKeyResource.</p>
*
* @return a {@link org.springframework.core.io.Resource} object
*/
public Resource loadPublicKeyResource() {
return loadResource(publicKeyResource, publicKey, publicKeyLocation, publicKeyFormat, "Public");
}
/**
* <p>setKeyFormat.</p>
*
* @param keyFormat a {@link com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat} object
*/
public void setKeyFormat(KeyFormat keyFormat) {
setPublicKeyFormat(keyFormat);
setPrivateKeyFormat(keyFormat);
}
}
|
return Optional.ofNullable(asResource)
.orElseGet(() ->
Optional.ofNullable(asString)
.map(pk -> (Resource) new ByteArrayResource(format == KeyFormat.DER ? Base64.getDecoder().decode(pk) : pk.getBytes(StandardCharsets.UTF_8)))
.orElseGet(() ->
Optional.ofNullable(asLocation)
.map(resourceLoader::getResource)
.orElseThrow(() -> new IllegalArgumentException("Unable to load " + type + " key. Either resource, key as string, or resource location must be provided"))));
| 410
| 155
| 565
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/encryptor/SimpleGCMByteEncryptor.java
|
SimpleGCMByteEncryptor
|
getAESKeyFromPassword
|
class SimpleGCMByteEncryptor implements ByteEncryptor {
/** Constant <code>AES_KEY_SIZE=256</code> */
public static final int AES_KEY_SIZE = 256;
/** Constant <code>AES_KEY_PASSWORD_SALT_LENGTH=16</code> */
public static final int AES_KEY_PASSWORD_SALT_LENGTH = 16;
/** Constant <code>GCM_IV_LENGTH=12</code> */
public static final int GCM_IV_LENGTH = 12;
/** Constant <code>GCM_TAG_LENGTH=128</code> */
public static final int GCM_TAG_LENGTH = 128;
private final Singleton<SecretKey> key;
private final String algorithm;
private final Singleton<IvGenerator> ivGenerator;
/** {@inheritDoc} */
@SneakyThrows
@Override
public byte[] encrypt(byte[] message) {
byte[] iv = this.ivGenerator.get().generateIv(GCM_IV_LENGTH);
Cipher cipher = Cipher.getInstance(this.algorithm);
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
cipher.init(Cipher.ENCRYPT_MODE, key.get(), gcmParameterSpec);
byte[] cipherText = cipher.doFinal(message);
ByteBuffer byteBuffer = ByteBuffer.allocate(GCM_IV_LENGTH + cipherText.length);
byteBuffer.put(iv);
byteBuffer.put(cipherText);
return byteBuffer.array();
}
/** {@inheritDoc} */
@SneakyThrows
@Override
public byte[] decrypt(byte[] encryptedMessage) {
Cipher cipher = Cipher.getInstance(this.algorithm);
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, encryptedMessage, 0, GCM_IV_LENGTH);
cipher.init(Cipher.DECRYPT_MODE, key.get(), gcmParameterSpec);
return cipher.doFinal(encryptedMessage, GCM_IV_LENGTH, encryptedMessage.length - GCM_IV_LENGTH);
}
@SneakyThrows
private SecretKey loadSecretKey(SimpleGCMConfig config) {
if (config.getActualKey() != null) {
return config.getActualKey();
} else if (config.getSecretKeyPassword() != null) {
Assert.notNull(config.getSecretKeySaltGenerator(), "Secret key Salt must be provided with password");
Assert.notNull(config.getSecretKeyAlgorithm(), "Secret key algorithm must be provided with password");
return getAESKeyFromPassword(config.getSecretKeyPasswordChars(), config.getSecretKeySaltGenerator(), config.getSecretKeyIterations(), config.getSecretKeyAlgorithm());
} else {
Assert.state(config.getSecretKey() != null || config.getSecretKeyResource() != null || config.getSecretKeyLocation() != null, "No key provided");
return loadSecretKeyFromResource(config.loadSecretKeyResource());
}
}
@SneakyThrows
private byte[] getResourceBytes(Resource resource) {
return FileCopyUtils.copyToByteArray(resource.getInputStream());
}
@SneakyThrows
private SecretKey loadSecretKeyFromResource(Resource resource) {
byte[] secretKeyBytes = Base64.getDecoder().decode(getResourceBytes(resource));
return new SecretKeySpec(secretKeyBytes, "AES");
}
/**
* <p>generateSecretKey.</p>
*
* @return a {@link javax.crypto.SecretKey} object
*/
@SneakyThrows
public static SecretKey generateSecretKey() {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstanceStrong();
keyGenerator.init(AES_KEY_SIZE, random);
return keyGenerator.generateKey();
}
/**
* <p>generateBase64EncodedSecretKey.</p>
*
* @return a {@link java.lang.String} object
*/
@SneakyThrows
public static String generateBase64EncodedSecretKey() {
SecretKey key = generateSecretKey();
byte[] secretKeyBytes = key.getEncoded();
return Base64.getEncoder().encodeToString(secretKeyBytes);
}
/**
* <p>getAESKeyFromPassword.</p>
*
* @param password an array of {@link char} objects
* @param saltGenerator a {@link org.jasypt.salt.SaltGenerator} object
* @param iterations a int
* @param algorithm a {@link java.lang.String} object
* @return a {@link javax.crypto.SecretKey} object
*/
@SneakyThrows
public static SecretKey getAESKeyFromPassword(char[] password, SaltGenerator saltGenerator, int iterations, String algorithm){<FILL_FUNCTION_BODY>}
/**
* <p>Constructor for SimpleGCMByteEncryptor.</p>
*
* @param config a {@link com.ulisesbocchio.jasyptspringboot.encryptor.SimpleGCMConfig} object
*/
public SimpleGCMByteEncryptor(SimpleGCMConfig config) {
this.key = Singleton.from(this::loadSecretKey, config);
this.ivGenerator = Singleton.from(config::getActualIvGenerator);
this.algorithm = config.getAlgorithm();
}
}
|
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
KeySpec spec = new PBEKeySpec(password, saltGenerator.generateSalt(AES_KEY_PASSWORD_SALT_LENGTH), iterations, AES_KEY_SIZE);
return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
| 1,440
| 85
| 1,525
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/encryptor/SimpleGCMConfig.java
|
SimpleGCMConfig
|
loadResource
|
class SimpleGCMConfig {
private ResourceLoader resourceLoader = new DefaultResourceLoader();
private Resource secretKeyResource;
private String secretKeyLocation;
private String secretKey;
private String secretKeyPassword;
private String secretKeySalt;
private String algorithm = "AES/GCM/NoPadding";
private String secretKeyAlgorithm = "PBKDF2WithHmacSHA256";
private int secretKeyIterations = 1000;
private SecretKey actualKey = null;
private SaltGenerator saltGenerator = null;
private IvGenerator ivGenerator = null;
private String ivGeneratorClassName = "org.jasypt.iv.RandomIvGenerator";
private Resource loadResource(Resource asResource, String asString, String asLocation) {<FILL_FUNCTION_BODY>}
/**
* <p>loadSecretKeyResource.</p>
*
* @return a {@link org.springframework.core.io.Resource} object
*/
public Resource loadSecretKeyResource() {
return loadResource(secretKeyResource, secretKey, secretKeyLocation);
}
/**
* <p>getSecretKeyPasswordChars.</p>
*
* @return an array of {@link char} objects
*/
public char[] getSecretKeyPasswordChars() {
return secretKeyPassword.toCharArray();
}
/**
* <p>getSecretKeySaltGenerator.</p>
*
* @return a {@link org.jasypt.salt.SaltGenerator} object
*/
public SaltGenerator getSecretKeySaltGenerator() {
return saltGenerator != null ?
saltGenerator :
(secretKeySalt == null ?
new ZeroSaltGenerator() :
new FixedBase64ByteArraySaltGenerator(secretKeySalt));
}
@SneakyThrows
private IvGenerator instantiateIvGenerator() {
return (IvGenerator)Class.forName(this.ivGeneratorClassName).newInstance();
}
/**
* <p>getActualIvGenerator.</p>
*
* @return a {@link org.jasypt.iv.IvGenerator} object
*/
public IvGenerator getActualIvGenerator() {
return Optional.ofNullable(ivGenerator).orElseGet(this::instantiateIvGenerator);
}
}
|
return Optional.ofNullable(asResource)
.orElseGet(() ->
Optional.ofNullable(asString)
.map(pk -> (Resource) new ByteArrayResource(pk.getBytes(StandardCharsets.UTF_8)))
.orElseGet(() ->
Optional.ofNullable(asLocation)
.map(resourceLoader::getResource)
.orElseThrow(() -> new IllegalArgumentException("Unable to load secret key. Either resource, key as string, or resource location must be provided"))));
| 598
| 130
| 728
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/encryptor/SimplePBEByteEncryptor.java
|
SimplePBEByteEncryptor
|
encrypt
|
class SimplePBEByteEncryptor implements PBEByteEncryptor {
private String password = null;
private SaltGenerator saltGenerator = null;
private int iterations;
private String algorithm = null;
/** {@inheritDoc} */
@Override
@SneakyThrows
public byte[] encrypt(byte[] message) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
@SneakyThrows
public byte[] decrypt(byte[] encryptedMessage) {
int paramsLength = Byte.toUnsignedInt(encryptedMessage[0]);
int messageLength = encryptedMessage.length - paramsLength - 1;
byte[] params = new byte[paramsLength];
byte[] message = new byte[messageLength];
System.arraycopy(encryptedMessage, 1, params, 0, paramsLength);
System.arraycopy(encryptedMessage, paramsLength + 1, message, 0, messageLength);
// create Key
final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
final PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKey key = factory.generateSecret(keySpec);
// Build parameters
AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(algorithm);
algorithmParameters.init(params);
// Build Cipher
final Cipher cipherDecrypt = Cipher.getInstance(algorithm);
cipherDecrypt.init(
Cipher.DECRYPT_MODE,
key,
algorithmParameters
);
return cipherDecrypt.doFinal(message);
}
/** {@inheritDoc} */
@Override
public void setPassword(String password) {
this.password = password;
}
/**
* <p>Setter for the field <code>saltGenerator</code>.</p>
*
* @param saltGenerator a {@link org.jasypt.salt.SaltGenerator} object
*/
public void setSaltGenerator(SaltGenerator saltGenerator) {
this.saltGenerator = saltGenerator;
}
/**
* <p>Setter for the field <code>iterations</code>.</p>
*
* @param iterations a int
*/
public void setIterations(int iterations) {
this.iterations = iterations;
}
/**
* <p>Setter for the field <code>algorithm</code>.</p>
*
* @param algorithm a {@link java.lang.String} object
*/
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
}
|
// create Key
final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
byte[] salt = saltGenerator.generateSalt(8);
final PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterations);
SecretKey key = factory.generateSecret(keySpec);
// Build cipher.
final Cipher cipherEncrypt = Cipher.getInstance(algorithm);
cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);
// Save parameters
byte[] params = cipherEncrypt.getParameters().getEncoded();
// Encrypted message
byte[] encryptedMessage = cipherEncrypt.doFinal(message);
return ByteBuffer
.allocate(1 + params.length + encryptedMessage.length)
.put((byte) params.length)
.put(params)
.put(encryptedMessage)
.array();
| 666
| 227
| 893
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/environment/EnvironmentInitializer.java
|
EnvironmentInitializer
|
initialize
|
class EnvironmentInitializer {
private final InterceptionMode interceptionMode;
private final List<Class<PropertySource<?>>> skipPropertySourceClasses;
private final EncryptablePropertyResolver resolver;
private final EncryptablePropertyFilter filter;
private final StringEncryptor encryptor;
private final EncryptablePropertyDetector detector;
private final InterceptionMode propertySourceInterceptionMode;
/**
* <p>Constructor for EnvironmentInitializer.</p>
*
* @param interceptionMode a {@link com.ulisesbocchio.jasyptspringboot.InterceptionMode} object
* @param propertySourceInterceptionMode a {@link com.ulisesbocchio.jasyptspringboot.InterceptionMode} object
* @param skipPropertySourceClasses a {@link java.util.List} object
* @param resolver a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver} object
* @param filter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyFilter} object
* @param encryptor a {@link org.jasypt.encryption.StringEncryptor} object
* @param detector a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyDetector} object
*/
public EnvironmentInitializer(InterceptionMode interceptionMode, InterceptionMode propertySourceInterceptionMode, List<Class<PropertySource<?>>> skipPropertySourceClasses, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter, StringEncryptor encryptor, EncryptablePropertyDetector detector) {
this.interceptionMode = interceptionMode;
this.propertySourceInterceptionMode = propertySourceInterceptionMode;
this.skipPropertySourceClasses = skipPropertySourceClasses;
this.resolver = resolver;
this.filter = filter;
this.encryptor = encryptor;
this.detector = detector;
}
void initialize(EncryptableEnvironment environment) {<FILL_FUNCTION_BODY>}
static MutableConfigurablePropertyResolver createPropertyResolver(MutablePropertySources propertySources) {
return new MutableConfigurablePropertyResolver(propertySources, ConfigurationPropertySources::createPropertyResolver);
}
}
|
log.info("Initializing Environment: {}", environment.getClass().getSimpleName());
InterceptionMode actualInterceptionMode = Optional.ofNullable(interceptionMode).orElse(InterceptionMode.WRAPPER);
List<Class<PropertySource<?>>> actualSkipPropertySourceClasses = Optional.ofNullable(skipPropertySourceClasses).orElseGet(Collections::emptyList);
EnvCopy envCopy = new EnvCopy(environment);
EncryptablePropertyFilter actualFilter = Optional.ofNullable(filter).orElseGet(() -> new DefaultLazyPropertyFilter(envCopy.get()));
StringEncryptor actualEncryptor = Optional.ofNullable(encryptor).orElseGet(() -> new DefaultLazyEncryptor(envCopy.get()));
EncryptablePropertyDetector actualDetector = Optional.ofNullable(detector).orElseGet(() -> new DefaultLazyPropertyDetector(envCopy.get()));
EncryptablePropertyResolver actualResolver = Optional.ofNullable(resolver).orElseGet(() -> new DefaultLazyPropertyResolver(actualDetector, actualEncryptor, environment));
EncryptablePropertySourceConverter converter = new EncryptablePropertySourceConverter(actualInterceptionMode, actualSkipPropertySourceClasses, actualResolver, actualFilter);
converter.convertPropertySources(environment.getOriginalPropertySources());
MutablePropertySources encryptableSources = converter.convertMutablePropertySources(propertySourceInterceptionMode, environment.getOriginalPropertySources(), envCopy);
environment.setEncryptablePropertySources(encryptableSources);
| 558
| 375
| 933
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/filter/DefaultLazyPropertyFilter.java
|
DefaultLazyPropertyFilter
|
createDefault
|
class DefaultLazyPropertyFilter implements EncryptablePropertyFilter {
private Singleton<EncryptablePropertyFilter> singleton;
/**
* <p>Constructor for DefaultLazyPropertyFilter.</p>
*
* @param e a {@link org.springframework.core.env.ConfigurableEnvironment} object
* @param customFilterBeanName a {@link java.lang.String} object
* @param isCustom a boolean
* @param bf a {@link org.springframework.beans.factory.BeanFactory} object
*/
public DefaultLazyPropertyFilter(ConfigurableEnvironment e, String customFilterBeanName, boolean isCustom, BeanFactory bf) {
singleton = new Singleton<>(() ->
Optional.of(customFilterBeanName)
.filter(bf::containsBean)
.map(name -> (EncryptablePropertyFilter) bf.getBean(name))
.map(tap(bean -> log.info("Found Custom Filter Bean {} with name: {}", bean, customFilterBeanName)))
.orElseGet(() -> {
if (isCustom) {
throw new IllegalStateException(String.format("Property Filter custom Bean not found with name '%s'", customFilterBeanName));
}
log.info("Property Filter custom Bean not found with name '{}'. Initializing Default Property Filter", customFilterBeanName);
return createDefault(e);
}));
}
/**
* <p>Constructor for DefaultLazyPropertyFilter.</p>
*
* @param environment a {@link org.springframework.core.env.ConfigurableEnvironment} object
*/
public DefaultLazyPropertyFilter(ConfigurableEnvironment environment) {
singleton = new Singleton<>(() -> createDefault(environment));
}
private DefaultPropertyFilter createDefault(ConfigurableEnvironment environment) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public boolean shouldInclude(PropertySource<?> source, String name) {
return singleton.get().shouldInclude(source, name);
}
}
|
JasyptEncryptorConfigurationProperties props = JasyptEncryptorConfigurationProperties.bindConfigProps(environment);
final JasyptEncryptorConfigurationProperties.PropertyConfigurationProperties.FilterConfigurationProperties filterConfig = props.getProperty().getFilter();
return new DefaultPropertyFilter(filterConfig.getIncludeSources(), filterConfig.getExcludeSources(),
filterConfig.getIncludeNames(), filterConfig.getExcludeNames());
| 513
| 104
| 617
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/filter/DefaultPropertyFilter.java
|
DefaultPropertyFilter
|
shouldInclude
|
class DefaultPropertyFilter implements EncryptablePropertyFilter {
private final List<String> includeSourceNames;
private final List<String> excludeSourceNames;
private final List<String> includePropertyNames;
private final List<String> excludePropertyNames;
/**
* <p>Constructor for DefaultPropertyFilter.</p>
*/
public DefaultPropertyFilter() {
includeSourceNames = null;
includePropertyNames = null;
excludeSourceNames = null;
excludePropertyNames = null;
}
/**
* <p>Constructor for DefaultPropertyFilter.</p>
*
* @param includeSourceNames a {@link java.util.List} object
* @param excludeSourceNames a {@link java.util.List} object
* @param includePropertyNames a {@link java.util.List} object
* @param excludePropertyNames a {@link java.util.List} object
*/
public DefaultPropertyFilter(List<String> includeSourceNames, List<String> excludeSourceNames, List<String> includePropertyNames, List<String> excludePropertyNames) {
this.includeSourceNames = includeSourceNames;
this.excludeSourceNames = excludeSourceNames;
this.includePropertyNames = includePropertyNames;
this.excludePropertyNames = excludePropertyNames;
}
/** {@inheritDoc} */
@Override
public boolean shouldInclude(PropertySource<?> source, String name) {<FILL_FUNCTION_BODY>}
private boolean isIncludeAll() {
return isIncludeUnset() && isExcludeUnset();
}
private boolean isIncludeUnset() {
return isEmpty(includeSourceNames) && isEmpty(includePropertyNames);
}
private boolean isExcludeUnset() {
return isEmpty(excludeSourceNames) && isEmpty(excludePropertyNames);
}
private boolean isEmpty(List<String> patterns) {
return patterns == null || patterns.isEmpty();
}
private boolean isMatch(String name, List<String> patterns) {
return name != null && !isEmpty(patterns) && patterns.stream().anyMatch(name::matches);
}
}
|
if (isIncludeAll()) {
return true;
}
if (isMatch(source.getName(), excludeSourceNames) || isMatch(name, excludePropertyNames)) {
return false;
}
return isIncludeUnset() || isMatch(source.getName(), includeSourceNames) || isMatch(name, includePropertyNames);
| 539
| 89
| 628
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/resolver/DefaultPropertyResolver.java
|
DefaultPropertyResolver
|
resolvePropertyValue
|
class DefaultPropertyResolver implements EncryptablePropertyResolver {
private final Environment environment;
private StringEncryptor encryptor;
private EncryptablePropertyDetector detector;
/**
* <p>Constructor for DefaultPropertyResolver.</p>
*
* @param encryptor a {@link org.jasypt.encryption.StringEncryptor} object
* @param environment a {@link org.springframework.core.env.Environment} object
*/
public DefaultPropertyResolver(StringEncryptor encryptor, Environment environment) {
this(encryptor, new DefaultPropertyDetector(), environment);
}
/**
* <p>Constructor for DefaultPropertyResolver.</p>
*
* @param encryptor a {@link org.jasypt.encryption.StringEncryptor} object
* @param detector a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyDetector} object
* @param environment a {@link org.springframework.core.env.Environment} object
*/
public DefaultPropertyResolver(StringEncryptor encryptor, EncryptablePropertyDetector detector, Environment environment) {
this.environment = environment;
Assert.notNull(encryptor, "String encryptor can't be null");
Assert.notNull(detector, "Encryptable Property detector can't be null");
this.encryptor = encryptor;
this.detector = detector;
}
/** {@inheritDoc} */
@Override
public String resolvePropertyValue(String value) {<FILL_FUNCTION_BODY>}
}
|
return Optional.ofNullable(value)
.map(environment::resolvePlaceholders)
.filter(detector::isEncrypted)
.map(resolvedValue -> {
try {
String unwrappedProperty = detector.unwrapEncryptedValue(resolvedValue.trim());
String resolvedProperty = environment.resolvePlaceholders(unwrappedProperty);
return encryptor.decrypt(resolvedProperty);
} catch (EncryptionOperationNotPossibleException e) {
throw new DecryptionException("Unable to decrypt property: " + value + " resolved to: " + resolvedValue + ". Decryption of Properties failed, make sure encryption/decryption " +
"passwords match", e);
}
})
.orElse(value);
| 398
| 184
| 582
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/util/AsymmetricCryptography.java
|
AsymmetricCryptography
|
decodePem
|
class AsymmetricCryptography {
private static final String PRIVATE_KEY_HEADER = "-----BEGIN PRIVATE KEY-----";
private static final String PUBLIC_KEY_HEADER = "-----BEGIN PUBLIC KEY-----";
private static final String PRIVATE_KEY_FOOTER = "-----END PRIVATE KEY-----";
private static final String PUBLIC_KEY_FOOTER = "-----END PUBLIC KEY-----";
private final ResourceLoader resourceLoader;
/**
* <p>Constructor for AsymmetricCryptography.</p>
*
* @param resourceLoader a {@link org.springframework.core.io.ResourceLoader} object
*/
public AsymmetricCryptography(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@SneakyThrows
private byte[] getResourceBytes(Resource resource) {
return FileCopyUtils.copyToByteArray(resource.getInputStream());
}
@SneakyThrows
private byte[] decodePem(byte[] bytes, String... headers) {<FILL_FUNCTION_BODY>}
/**
* <p>getPrivateKey.</p>
*
* @param resourceLocation a {@link java.lang.String} object
* @param format a {@link com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat} object
* @return a {@link java.security.PrivateKey} object
*/
@SneakyThrows
public PrivateKey getPrivateKey(String resourceLocation, KeyFormat format) {
return getPrivateKey(resourceLoader.getResource(resourceLocation), format);
}
/**
* <p>getPrivateKey.</p>
*
* @param resource a {@link org.springframework.core.io.Resource} object
* @param format a {@link com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat} object
* @return a {@link java.security.PrivateKey} object
*/
@SneakyThrows
public PrivateKey getPrivateKey(Resource resource, KeyFormat format) {
byte[] keyBytes = getResourceBytes(resource);
if (format == KeyFormat.PEM) {
keyBytes = decodePem(keyBytes, PRIVATE_KEY_HEADER, PRIVATE_KEY_FOOTER);
}
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
/**
* <p>getPublicKey.</p>
*
* @param resourceLocation a {@link java.lang.String} object
* @param format a {@link com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat} object
* @return a {@link java.security.PublicKey} object
*/
@SneakyThrows
public PublicKey getPublicKey(String resourceLocation, KeyFormat format) {
return getPublicKey(resourceLoader.getResource(resourceLocation), format);
}
/**
* <p>getPublicKey.</p>
*
* @param resource a {@link org.springframework.core.io.Resource} object
* @param format a {@link com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat} object
* @return a {@link java.security.PublicKey} object
*/
@SneakyThrows
public PublicKey getPublicKey(Resource resource, KeyFormat format) {
byte[] keyBytes = getResourceBytes(resource);
if (format == KeyFormat.PEM) {
keyBytes = decodePem(keyBytes, PUBLIC_KEY_HEADER, PUBLIC_KEY_FOOTER);
}
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/**
* <p>encrypt.</p>
*
* @param msg an array of {@link byte} objects
* @param key a {@link java.security.PublicKey} object
* @return an array of {@link byte} objects
*/
@SneakyThrows
public byte[] encrypt(byte[] msg, PublicKey key) {
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(msg);
}
/**
* <p>decrypt.</p>
*
* @param msg an array of {@link byte} objects
* @param key a {@link java.security.PrivateKey} object
* @return an array of {@link byte} objects
*/
@SneakyThrows
public byte[] decrypt(byte[] msg, PrivateKey key) {
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(msg);
}
public enum KeyFormat {
DER,
PEM;
}
}
|
String pem = new String(bytes, StandardCharsets.UTF_8);
for (String header : headers) {
pem = pem.replace(header, "");
}
return Base64.getMimeDecoder().decode(pem);
| 1,321
| 67
| 1,388
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/util/Iterables.java
|
IteratorDecorator
|
maybeFetchNext
|
class IteratorDecorator<U, T> implements Iterator<T> {
private final Iterator<U> source;
private final Function<U, T> transform;
private final Predicate<U> filter;
private T next = null;
public IteratorDecorator(Iterator<U> source, Function<U, T> transform, Predicate<U> filter) {
this.source = source;
this.transform = transform;
this.filter = filter;
}
public boolean hasNext() {
this.maybeFetchNext();
return next != null;
}
public T next() {
if (next == null) {
throw new NoSuchElementException();
}
T val = next;
next = null;
return val;
}
private void maybeFetchNext() {<FILL_FUNCTION_BODY>}
public void remove() {
throw new UnsupportedOperationException();
}
}
|
if (next == null) {
if (source.hasNext()) {
U val = source.next();
if (filter.test(val)) {
next = transform.apply(val);
}
}
}
| 246
| 61
| 307
|
<no_super_class>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/wrapper/EncryptableConfigurationPropertySourcesPropertySource.java
|
EncryptableConfigurationPropertySourcesPropertySource
|
findConfigurationProperty
|
class EncryptableConfigurationPropertySourcesPropertySource extends PropertySource<Iterable<ConfigurationPropertySource>>
implements EncryptablePropertySource<Iterable<ConfigurationPropertySource>> {
private final PropertySource<Iterable<ConfigurationPropertySource>> delegate;
/**
* <p>Constructor for EncryptableConfigurationPropertySourcesPropertySource.</p>
*
* @param delegate a {@link org.springframework.core.env.PropertySource} object
*/
public EncryptableConfigurationPropertySourcesPropertySource(PropertySource<Iterable<ConfigurationPropertySource>> delegate) {
super(delegate.getName(), Iterables.filter(delegate.getSource(), configurationPropertySource -> !configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)));
this.delegate = delegate;
}
/** {@inheritDoc} */
@Override
public PropertySource<Iterable<ConfigurationPropertySource>> getDelegate() {
return delegate;
}
/** {@inheritDoc} */
@Override
public void refresh() {
}
/** {@inheritDoc} */
@Override
public Object getProperty(String name) {
ConfigurationProperty configurationProperty = findConfigurationProperty(name);
return (configurationProperty != null) ? configurationProperty.getValue() : null;
}
/** {@inheritDoc} */
@Override
public Origin getOrigin(String name) {
return Origin.from(findConfigurationProperty(name));
}
private ConfigurationProperty findConfigurationProperty(String name) {
try {
return findConfigurationProperty(ConfigurationPropertyName.of(name));
}
catch (InvalidConfigurationPropertyNameException ex) {
// simulate non-exposed version of ConfigurationPropertyName.of(name, nullIfInvalid)
if(ex.getInvalidCharacters().size() == 1 && ex.getInvalidCharacters().get(0).equals('.')) {
return null;
}
throw ex;
}
}
private ConfigurationProperty findConfigurationProperty(ConfigurationPropertyName name) {<FILL_FUNCTION_BODY>}
}
|
if (name == null) {
return null;
}
for (ConfigurationPropertySource configurationPropertySource : getSource()) {
if (!configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)) {
ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(name);
if (configurationProperty != null) {
return configurationProperty;
}
}
}
return null;
| 516
| 114
| 630
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, Iterable<org.springframework.boot.context.properties.source.ConfigurationPropertySource>) ,public boolean containsProperty(java.lang.String) ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public abstract java.lang.Object getProperty(java.lang.String) ,public Iterable<org.springframework.boot.context.properties.source.ConfigurationPropertySource> getSource() ,public int hashCode() ,public static PropertySource<?> named(java.lang.String) ,public java.lang.String toString() <variables>protected final org.apache.commons.logging.Log logger,protected final java.lang.String name,protected final Iterable<org.springframework.boot.context.properties.source.ConfigurationPropertySource> source
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/wrapper/EncryptableSystemEnvironmentPropertySourceWrapper.java
|
EncryptableSystemEnvironmentPropertySourceWrapper
|
getOrigin
|
class EncryptableSystemEnvironmentPropertySourceWrapper extends SystemEnvironmentPropertySource implements EncryptablePropertySource<Map<String, Object>> {
private final CachingDelegateEncryptablePropertySource<Map<String, Object>> encryptableDelegate;
/**
* <p>Constructor for EncryptableSystemEnvironmentPropertySourceWrapper.</p>
*
* @param delegate a {@link org.springframework.core.env.SystemEnvironmentPropertySource} object
* @param resolver a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver} object
* @param filter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyFilter} object
*/
public EncryptableSystemEnvironmentPropertySourceWrapper(SystemEnvironmentPropertySource delegate, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter) {
super(delegate.getName(), delegate.getSource());
encryptableDelegate = new CachingDelegateEncryptablePropertySource<>(delegate, resolver, filter);
}
/** {@inheritDoc} */
@Override
public Object getProperty(String name) {
return encryptableDelegate.getProperty(name);
}
/** {@inheritDoc} */
@Override
public PropertySource<Map<String, Object>> getDelegate() {
return encryptableDelegate;
}
/** {@inheritDoc} */
@Override
public Origin getOrigin(String key) {<FILL_FUNCTION_BODY>}
}
|
Origin fromSuper = EncryptablePropertySource.super.getOrigin(key);
if (fromSuper != null) {
return fromSuper;
}
String property = resolvePropertyName(key);
if (super.containsProperty(property)) {
return new SystemEnvironmentOrigin(property);
}
return null;
| 369
| 84
| 453
|
<methods>public void <init>(java.lang.String, Map<java.lang.String,java.lang.Object>) ,public boolean containsProperty(java.lang.String) ,public java.lang.Object getProperty(java.lang.String) <variables>
|
ulisesbocchio_jasypt-spring-boot
|
jasypt-spring-boot/jasypt-spring-boot/src/main/java/com/ulisesbocchio/jasyptspringboot/wrapper/OriginTrackedCompositePropertySource.java
|
OriginTrackedCompositePropertySource
|
getOrigin
|
class OriginTrackedCompositePropertySource extends CompositePropertySource implements OriginLookup<String> {
/**
* Create a new {@code CompositePropertySource}.
*
* @param name the name of the property source
*/
public OriginTrackedCompositePropertySource(String name) {
super(name);
}
/** {@inheritDoc} */
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Origin getOrigin(String name) {<FILL_FUNCTION_BODY>}
}
|
for (PropertySource<?> propertySource : getPropertySources()) {
if (propertySource instanceof OriginLookup) {
OriginLookup lookup = (OriginLookup) propertySource;
Origin origin = lookup.getOrigin(name);
if (origin != null) {
return origin;
}
}
}
return null;
| 136
| 92
| 228
|
<methods>public void <init>(java.lang.String) ,public void addFirstPropertySource(PropertySource<?>) ,public void addPropertySource(PropertySource<?>) ,public boolean containsProperty(java.lang.String) ,public java.lang.Object getProperty(java.lang.String) ,public java.lang.String[] getPropertyNames() ,public Collection<PropertySource<?>> getPropertySources() ,public java.lang.String toString() <variables>private final Set<PropertySource<?>> propertySources
|
iluwatar_java-design-patterns
|
java-design-patterns/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java
|
AbstractDocument
|
buildStringRepresentation
|
class AbstractDocument implements Document {
private final Map<String, Object> documentProperties;
protected AbstractDocument(Map<String, Object> properties) {
Objects.requireNonNull(properties, "properties map is required");
this.documentProperties = properties;
}
@Override
public Void put(String key, Object value) {
documentProperties.put(key, value);
return null;
}
@Override
public Object get(String key) {
return documentProperties.get(key);
}
@Override
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> childConstructor) {
return Stream.ofNullable(get(key))
.filter(Objects::nonNull)
.map(el -> (List<Map<String, Object>>) el)
.findAny()
.stream()
.flatMap(Collection::stream)
.map(childConstructor);
}
@Override
public String toString() {
return buildStringRepresentation();
}
private String buildStringRepresentation() {<FILL_FUNCTION_BODY>}
}
|
var builder = new StringBuilder();
builder.append(getClass().getName()).append("[");
// Explaining variable for document properties map
Map<String, Object> documentProperties = this.documentProperties;
// Explaining variable for the size of document properties map
int numProperties = documentProperties.size();
// Explaining variable for tracking the current property index
int currentPropertyIndex = 0;
// Iterate over document properties map
for (Map.Entry<String, Object> entry : documentProperties.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// Append key-value pair
builder.append("[").append(key).append(" : ").append(value).append("]");
// Add comma if not last property
if (++currentPropertyIndex < numProperties) {
builder.append(", ");
}
}
builder.append("]");
return builder.toString();
| 293
| 239
| 532
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Constructing parts and car");
var wheelProperties = Map.of(
Property.TYPE.toString(), "wheel",
Property.MODEL.toString(), "15C",
Property.PRICE.toString(), 100L);
var doorProperties = Map.of(
Property.TYPE.toString(), "door",
Property.MODEL.toString(), "Lambo",
Property.PRICE.toString(), 300L);
var carProperties = Map.of(
Property.MODEL.toString(), "300SL",
Property.PRICE.toString(), 10000L,
Property.PARTS.toString(), List.of(wheelProperties, doorProperties));
var car = new Car(carProperties);
LOGGER.info("Here is our car:");
LOGGER.info("-> model: {}", car.getModel().orElseThrow());
LOGGER.info("-> price: {}", car.getPrice().orElseThrow());
LOGGER.info("-> parts: ");
car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}",
p.getType().orElse(null),
p.getModel().orElse(null),
p.getPrice().orElse(null))
);
| 56
| 330
| 386
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java
|
App
|
run
|
class App implements Runnable {
private final Kingdom kingdom = new Kingdom();
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var app = new App();
app.run();
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
/**
* Creates kingdom.
* @param kingdomType type of Kingdom
*/
public void createKingdom(final Kingdom.FactoryMaker.KingdomType kingdomType) {
final KingdomFactory kingdomFactory = Kingdom.FactoryMaker.makeFactory(kingdomType);
kingdom.setKing(kingdomFactory.createKing());
kingdom.setCastle(kingdomFactory.createCastle());
kingdom.setArmy(kingdomFactory.createArmy());
}
}
|
LOGGER.info("elf kingdom");
createKingdom(Kingdom.FactoryMaker.KingdomType.ELF);
LOGGER.info(kingdom.getArmy().getDescription());
LOGGER.info(kingdom.getCastle().getDescription());
LOGGER.info(kingdom.getKing().getDescription());
LOGGER.info("orc kingdom");
createKingdom(Kingdom.FactoryMaker.KingdomType.ORC);
LOGGER.info(kingdom.getArmy().getDescription());
LOGGER.info(kingdom.getCastle().getDescription());
LOGGER.info(kingdom.getKing().getDescription());
| 216
| 165
| 381
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Kingdom.java
|
FactoryMaker
|
makeFactory
|
class FactoryMaker {
/**
* Enumeration for the different types of Kingdoms.
*/
public enum KingdomType {
ELF, ORC
}
/**
* The factory method to create KingdomFactory concrete objects.
*/
public static KingdomFactory makeFactory(KingdomType type) {<FILL_FUNCTION_BODY>}
}
|
return switch (type) {
case ELF -> new ElfKingdomFactory();
case ORC -> new OrcKingdomFactory();
};
| 94
| 42
| 136
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/active-object/src/main/java/com/iluwatar/activeobject/ActiveCreature.java
|
ActiveCreature
|
eat
|
class ActiveCreature {
private static final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName());
private BlockingQueue<Runnable> requests;
private String name;
private Thread thread; // Thread of execution.
private int status; // status of the thread of execution.
/**
* Constructor and initialization.
*/
protected ActiveCreature(String name) {
this.name = name;
this.status = 0;
this.requests = new LinkedBlockingQueue<>();
thread = new Thread(() -> {
boolean infinite = true;
while (infinite) {
try {
requests.take().run();
} catch (InterruptedException e) {
if (this.status != 0) {
logger.error("Thread was interrupted. --> {}", e.getMessage());
}
infinite = false;
Thread.currentThread().interrupt();
}
}
});
thread.start();
}
/**
* Eats the porridge.
* @throws InterruptedException due to firing a new Runnable.
*/
public void eat() throws InterruptedException {<FILL_FUNCTION_BODY>}
/**
* Roam the wastelands.
* @throws InterruptedException due to firing a new Runnable.
*/
public void roam() throws InterruptedException {
requests.put(() ->
logger.info("{} has started to roam in the wastelands.", name())
);
}
/**
* Returns the name of the creature.
* @return the name of the creature.
*/
public String name() {
return this.name;
}
/**
* Kills the thread of execution.
* @param status of the thread of execution. 0 == OK, the rest is logging an error.
*/
public void kill(int status) {
this.status = status;
this.thread.interrupt();
}
/**
* Returns the status of the thread of execution.
* @return the status of the thread of execution.
*/
public int getStatus() {
return this.status;
}
}
|
requests.put(() -> {
logger.info("{} is eating!", name());
logger.info("{} has finished eating!", name());
});
| 564
| 42
| 606
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/active-object/src/main/java/com/iluwatar/activeobject/App.java
|
App
|
run
|
class App implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(App.class.getName());
private static final int NUM_CREATURES = 3;
/**
* Program entry point.
*
* @param args command line arguments.
*/
public static void main(String[] args) {
var app = new App();
app.run();
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
List<ActiveCreature> creatures = new ArrayList<>();
try {
for (int i = 0; i < NUM_CREATURES; i++) {
creatures.add(new Orc(Orc.class.getSimpleName() + i));
creatures.get(i).eat();
creatures.get(i).roam();
}
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error(e.getMessage());
Thread.currentThread().interrupt();
} finally {
for (int i = 0; i < NUM_CREATURES; i++) {
creatures.get(i).kill(0);
}
}
| 133
| 177
| 310
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java
|
App
|
main
|
class App {
/**
* Program's entry point.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var conUnix = new ConfigureForUnixVisitor();
var conDos = new ConfigureForDosVisitor();
var zoom = new Zoom();
var hayes = new Hayes();
hayes.accept(conDos); // Hayes modem with Dos configurator
zoom.accept(conDos); // Zoom modem with Dos configurator
hayes.accept(conUnix); // Hayes modem with Unix configurator
zoom.accept(conUnix); // Zoom modem with Unix configurator
| 46
| 139
| 185
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java
|
Hayes
|
accept
|
class Hayes implements Modem {
/**
* Accepts all visitors but honors only HayesVisitor.
*/
@Override
public void accept(ModemVisitor modemVisitor) {<FILL_FUNCTION_BODY>}
/**
* Hayes' modem's toString method.
*/
@Override
public String toString() {
return "Hayes modem";
}
}
|
if (modemVisitor instanceof HayesVisitor) {
((HayesVisitor) modemVisitor).visit(this);
} else {
LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem");
}
| 112
| 67
| 179
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java
|
Zoom
|
accept
|
class Zoom implements Modem {
/**
* Accepts all visitors but honors only ZoomVisitor.
*/
@Override
public void accept(ModemVisitor modemVisitor) {<FILL_FUNCTION_BODY>}
/**
* Zoom modem's toString method.
*/
@Override
public String toString() {
return "Zoom modem";
}
}
|
if (modemVisitor instanceof ZoomVisitor) {
((ZoomVisitor) modemVisitor).visit(this);
} else {
LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem");
}
| 110
| 65
| 175
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/adapter/src/main/java/com/iluwatar/adapter/App.java
|
App
|
main
|
class App {
private App() {
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(final String[] args) {<FILL_FUNCTION_BODY>}
}
|
// The captain can only operate rowing boats but with adapter he is able to
// use fishing boats as well
var captain = new Captain(new FishingBoatAdapter());
captain.row();
| 67
| 50
| 117
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java
|
Aggregator
|
getProduct
|
class Aggregator {
@Resource
private ProductInformationClient informationClient;
@Resource
private ProductInventoryClient inventoryClient;
/**
* Retrieves product data.
*
* @return a Product.
*/
@GetMapping("/product")
public Product getProduct() {<FILL_FUNCTION_BODY>}
}
|
var product = new Product();
var productTitle = informationClient.getProductTitle();
var productInventory = inventoryClient.getProductInventories();
//Fallback to error message
product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed"));
//Fallback to default error inventory
product.setProductInventories(requireNonNullElse(productInventory, -1));
return product;
| 93
| 115
| 208
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java
|
ProductInformationClientImpl
|
getProductTitle
|
class ProductInformationClientImpl implements ProductInformationClient {
@Override
public String getProductTitle() {<FILL_FUNCTION_BODY>}
}
|
var request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:51515/information"))
.build();
var client = HttpClient.newHttpClient();
try {
var httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
return httpResponse.body();
} catch (IOException ioe) {
LOGGER.error("IOException Occurred", ioe);
} catch (InterruptedException ie) {
LOGGER.error("InterruptedException Occurred", ie);
Thread.currentThread().interrupt();
}
return null;
| 39
| 163
| 202
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java
|
ProductInventoryClientImpl
|
getProductInventories
|
class ProductInventoryClientImpl implements ProductInventoryClient {
@Override
public Integer getProductInventories() {<FILL_FUNCTION_BODY>}
}
|
var response = "";
var request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:51516/inventories"))
.build();
var client = HttpClient.newHttpClient();
try {
var httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
response = httpResponse.body();
} catch (IOException ioe) {
LOGGER.error("IOException Occurred", ioe);
} catch (InterruptedException ie) {
LOGGER.error("InterruptedException Occurred", ie);
Thread.currentThread().interrupt();
}
if ("".equalsIgnoreCase(response)) {
return null;
} else {
return Integer.parseInt(response);
}
| 42
| 203
| 245
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/ambassador/src/main/java/com/iluwatar/ambassador/App.java
|
App
|
main
|
class App {
/**
* Entry point.
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var host1 = new Client();
var host2 = new Client();
host1.useService(12);
host2.useService(73);
| 43
| 43
| 86
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/ambassador/src/main/java/com/iluwatar/ambassador/Client.java
|
Client
|
useService
|
class Client {
private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador();
long useService(int value) {<FILL_FUNCTION_BODY>}
}
|
var result = serviceAmbassador.doRemoteFunction(value);
LOGGER.info("Service result: {}", result);
return result;
| 46
| 37
| 83
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java
|
RemoteService
|
getRemoteService
|
class RemoteService implements RemoteServiceInterface {
private static final int THRESHOLD = 200;
private static RemoteService service = null;
private final RandomProvider randomProvider;
static synchronized RemoteService getRemoteService() {<FILL_FUNCTION_BODY>}
private RemoteService() {
this(Math::random);
}
/**
* This constructor is used for testing purposes only.
*/
RemoteService(RandomProvider randomProvider) {
this.randomProvider = randomProvider;
}
/**
* Remote function takes a value and multiplies it by 10 taking a random amount of time. Will
* sometimes return -1. This imitates connectivity issues a client might have to account for.
*
* @param value integer value to be multiplied.
* @return if waitTime is less than {@link RemoteService#THRESHOLD}, it returns value * 10,
* otherwise {@link RemoteServiceStatus#FAILURE}.
*/
@Override
public long doRemoteFunction(int value) {
long waitTime = (long) Math.floor(randomProvider.random() * 1000);
try {
sleep(waitTime);
} catch (InterruptedException e) {
LOGGER.error("Thread sleep state interrupted", e);
Thread.currentThread().interrupt();
}
return waitTime <= THRESHOLD ? value * 10
: RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue();
}
}
|
if (service == null) {
service = new RemoteService();
}
return service;
| 373
| 28
| 401
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java
|
ServiceAmbassador
|
safeCall
|
class ServiceAmbassador implements RemoteServiceInterface {
private static final int RETRIES = 3;
private static final int DELAY_MS = 3000;
ServiceAmbassador() {
}
@Override
public long doRemoteFunction(int value) {
return safeCall(value);
}
private long checkLatency(int value) {
var startTime = System.currentTimeMillis();
var result = RemoteService.getRemoteService().doRemoteFunction(value);
var timeTaken = System.currentTimeMillis() - startTime;
LOGGER.info("Time taken (ms): {}", timeTaken);
return result;
}
private long safeCall(int value) {<FILL_FUNCTION_BODY>}
}
|
var retries = 0;
var result = FAILURE.getRemoteServiceStatusValue();
for (int i = 0; i < RETRIES; i++) {
if (retries >= RETRIES) {
return FAILURE.getRemoteServiceStatusValue();
}
if ((result = checkLatency(value)) == FAILURE.getRemoteServiceStatusValue()) {
LOGGER.info("Failed to reach remote: ({})", i + 1);
retries++;
try {
sleep(DELAY_MS);
} catch (InterruptedException e) {
LOGGER.error("Thread sleep state interrupted", e);
Thread.currentThread().interrupt();
}
} else {
break;
}
}
return result;
| 194
| 198
| 392
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/AntiCorruptionLayer.java
|
AntiCorruptionLayer
|
findOrderInLegacySystem
|
class AntiCorruptionLayer {
@Autowired
private LegacyShop legacyShop;
/**
* The method converts the order from the legacy system to the modern system.
* @param id the id of the order
* @return the order in the modern system
*/
public Optional<ModernOrder> findOrderInLegacySystem(String id) {<FILL_FUNCTION_BODY>}
}
|
return legacyShop.findOrder(id).map(o ->
new ModernOrder(
o.getId(),
new Customer(o.getCustomer()),
new Shipment(o.getItem(), o.getQty(), o.getPrice()),
""
)
);
| 107
| 73
| 180
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/ShopException.java
|
ShopException
|
throwIncorrectData
|
class ShopException extends Exception {
public ShopException(String message) {
super(message);
}
/**
* Throws an exception that the order is already placed but has an incorrect data.
*
* @param lhs the incoming order
* @param rhs the existing order
* @return the exception
* @throws ShopException the exception
*/
public static ShopException throwIncorrectData(String lhs, String rhs) throws ShopException {<FILL_FUNCTION_BODY>}
}
|
throw new ShopException("The order is already placed but has an incorrect data:\n"
+ "Incoming order: " + lhs + "\n"
+ "Existing order: " + rhs);
| 129
| 54
| 183
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
iluwatar_java-design-patterns
|
java-design-patterns/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernShop.java
|
ModernShop
|
placeOrder
|
class ModernShop {
@Autowired
private ModernStore store;
@Autowired
private AntiCorruptionLayer acl;
/**
* Places the order in the modern system.
* If the order is already present in the legacy system, then no need to place it again.
*/
public void placeOrder(ModernOrder order) throws ShopException {<FILL_FUNCTION_BODY>}
/**
* Finds the order in the modern system.
*/
public Optional<ModernOrder> findOrder(String orderId) {
return store.get(orderId);
}
}
|
String id = order.getId();
// check if the order is already present in the legacy system
Optional<ModernOrder> orderInObsoleteSystem = acl.findOrderInLegacySystem(id);
if (orderInObsoleteSystem.isPresent()) {
var legacyOrder = orderInObsoleteSystem.get();
if (!order.equals(legacyOrder)) {
throw ShopException.throwIncorrectData(legacyOrder.toString(), order.toString());
}
} else {
store.put(id, order);
}
| 156
| 140
| 296
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java
|
ApiGateway
|
getProductDesktop
|
class ApiGateway {
@Resource
private ImageClient imageClient;
@Resource
private PriceClient priceClient;
/**
* Retrieves product information that desktop clients need.
*
* @return Product information for clients on a desktop
*/
@GetMapping("/desktop")
public DesktopProduct getProductDesktop() {<FILL_FUNCTION_BODY>}
/**
* Retrieves product information that mobile clients need.
*
* @return Product information for clients on a mobile device
*/
@GetMapping("/mobile")
public MobileProduct getProductMobile() {
var mobileProduct = new MobileProduct();
mobileProduct.setPrice(priceClient.getPrice());
return mobileProduct;
}
}
|
var desktopProduct = new DesktopProduct();
desktopProduct.setImagePath(imageClient.getImagePath());
desktopProduct.setPrice(priceClient.getPrice());
return desktopProduct;
| 188
| 49
| 237
|
<no_super_class>
|
iluwatar_java-design-patterns
|
java-design-patterns/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java
|
ImageClientImpl
|
logResponse
|
class ImageClientImpl implements ImageClient {
/**
* Makes a simple HTTP Get request to the Image microservice.
*
* @return The path to the image
*/
@Override
public String getImagePath() {
var httpClient = HttpClient.newHttpClient();
var httpGet = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:50005/image-path"))
.build();
try {
LOGGER.info("Sending request to fetch image path");
var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
logResponse(httpResponse);
return httpResponse.body();
} catch (IOException ioe) {
LOGGER.error("Failure occurred while getting image path", ioe);
} catch (InterruptedException ie) {
LOGGER.error("Failure occurred while getting image path", ie);
Thread.currentThread().interrupt();
}
return null;
}
private void logResponse(HttpResponse<String> httpResponse) {<FILL_FUNCTION_BODY>}
private boolean isSuccessResponse(int responseCode) {
return responseCode >= 200 && responseCode <= 299;
}
}
|
if (isSuccessResponse(httpResponse.statusCode())) {
LOGGER.info("Image path received successfully");
} else {
LOGGER.warn("Image path request failed");
}
| 316
| 50
| 366
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.