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 specifie...
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(); ...
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 DefaultP...
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 = me...
if (!StringUtils.hasText(description.getApplicationName())) { description .setApplicationName(this.metadata.getConfiguration().generateApplicationName(description.getName())); } String targetArtifactId = determineValue(description.getArtifactId(), () -> this.metadata.getArtifactId().getContent()); d...
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 = ...
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 { ...
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 applicat...
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; }...
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.Str...
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...
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(u...
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<>...
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 * @para...
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); } }...
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 SpringIoInitializrMetadataUpd...
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 ...
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 Bas...
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 MOD...
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 IllegalArgumentExcepti...
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); _locatio...
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 s...
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 S...
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 st...
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, `...
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 builde...
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 i...
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) { ...
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 ...
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 ...
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; ...
JsonPointer next; if (_includeAllElements && !_pathToMatch.mayMatchElement()) { next = _pathToMatch.tail(); } else { next = _pathToMatch.matchElement(index); } if (next == null) { return null; } if (next.matches()) { ...
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.jack...
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;...
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].getFormatN...
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; /** ...
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 {@co...
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 " + valueToRep...
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() <= M...
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]"; t...
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; ...
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(b...
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); } /* /*****************************************************************...
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 fl...
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<...
if (_firstName == null) { _firstName = name; return false; } if (name.equals(_firstName)) { return true; } if (_secondName == null) { _secondName = name; return false; } if (name.equals(_secondName)) { ...
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, ByteQuadsCanonical...
// 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) ...
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_QU...
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)...
// 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); ...
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_QU...
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; } /* /********************************************************** /* Meth...
// 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 (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() <...
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; ...
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() <...
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); ...
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: ret...
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() <...
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...
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); } ...
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"; //...
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....
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 considerat...
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...
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 ...
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 JacksonFeatu...
// 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)); } ...
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 alrea...
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() ,p...
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 capacityAsI...
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; ...
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 B...
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())...
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() { } ...
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 ...
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 Encryptio...
String regex = quoteRegExSpecialChars(sourcePrefix) + "(.*?)" + quoteRegExSpecialChars(sourceSuffix); Pattern pattern = Pattern.compile(regex, DOTALL); Matcher matcher = pattern.matcher(templateText); StringBuffer result = new StringBuffer(); String replacement; while (match...
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"; ...
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...
Map<String, Object> defaultProperties = new HashMap<>(); defaultProperties.put("spring.config.location", "optional:file:./src/main/resources/"); ConfigurableApplicationContext context = new SpringApplicationBuilder() .sources(Application.class) .bannerMode(Banne...
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 Stri...
String decryptedContents = decrypt(path, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix); log.info("Re-encrypting file " + path); try { String encryptedContents = newService.encrypt(decryptedContents, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix); ...
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...
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) { ...
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_B...
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...
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, Strin...
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 (Exc...
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_B...
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) + enc...
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 ...
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. */ @Paramet...
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...
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...
setIfNotNull(properties::setPassword, oldPassword); setIfNotNull(properties::setPrivateKeyString, oldPrivateKeyString); setIfNotNull(properties::setPrivateKeyLocation, oldPrivateKeyLocation); setIfNotNull(properties::setPrivateKeyFormat, oldPrivateKeyFormat); setIfNotNull(prope...
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>} priv...
Environment environment = getEnvironment(); setIfNotNull(properties::setPassword, environment.getProperty("jasypt.encryptor.password")); setIfNotNull(properties::setPrivateKeyFormat, environment.getProperty("jasypt.encryptor.private-key-format", AsymmetricCryptography.KeyFormat.class)); ...
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 {@li...
String method = invocation.getMethod().getName(); Object[] arguments = invocation.getArguments(); switch (method) { case "addFirst": envCopy.addFirst((PropertySource<?>) arguments[0]); return invocation.getMethod().invoke(invocation.getThis(), makeEnc...
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 * @par...
if (isRefreshCall(invocation)) { refresh(); return null; } if (isGetDelegateCall(invocation)) { return getDelegate(); } if (isGetPropertyCall(invocation)) { return getProperty(getNameArgument(invocation)); } return ...
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-...
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...
//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 p...
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...
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.RefreshScopeRefreshedEven...
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 Configurat...
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!"); ...
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.ConditionCon...
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 po...
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.-]+)?\\}")...
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;...
try { log.info("Loading Encryptable Property Source '{}'", encryptablePropertySource.getString("name")); PropertySource ps = createPropertySource(encryptablePropertySource, env, resourceLoader, resolver, propertyFilter, loaders); propertySources.addLast(ps); log....
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(); O...
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.JasyptEncryptorConfigurati...
if (isPBEConfig()) { return createPBEDefault(); } else if (isAsymmetricConfig()) { return createAsymmetricDefault(); } else if (isGCMConfig()) { return createGCMDefault(); } else { throw new IllegalStateException("either '" + propertyPrefi...
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...
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.func...
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 ...
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))) ...
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=...
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/NoP...
return Optional.ofNullable(asResource) .orElseGet(() -> Optional.ofNullable(asString) .map(pk -> (Resource) new ByteArrayResource(pk.getBytes(StandardCharsets.UTF_8))) .orElseGet(() -> ...
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_FUNC...
// 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); // ...
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; pri...
log.info("Initializing Environment: {}", environment.getClass().getSimpleName()); InterceptionMode actualInterceptionMode = Optional.ofNullable(interceptionMode).orElse(InterceptionMode.WRAPPER); List<Class<PropertySource<?>>> actualSkipPropertySourceClasses = Optional.ofNullable(skipPropertySo...
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 customFilterBea...
JasyptEncryptorConfigurationProperties props = JasyptEncryptorConfigurationProperties.bindConfigProps(environment); final JasyptEncryptorConfigurationProperties.PropertyConfigurationProperties.FilterConfigurationProperties filterConfig = props.getProperty().getFilter(); return new DefaultProper...
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 DefaultPr...
if (isIncludeAll()) { return true; } if (isMatch(source.getName(), excludeSourceNames) || isMatch(name, excludePropertyNames)) { return false; } return isIncludeUnset() || isMatch(source.getName(), includeSourceNames) || isMatch(name, includePropertyNam...
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.e...
return Optional.ofNullable(value) .map(environment::resolvePlaceholders) .filter(detector::isEncrypted) .map(resolvedValue -> { try { String unwrappedProperty = detector.unwrapEncryptedValue(resolvedValue.trim()); ...
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_K...
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)...
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>Constructo...
if (name == null) { return null; } for (ConfigurationPropertySource configurationPropertySource : getSource()) { if (!configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)) { Confi...
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 ja...
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 EncryptableSystemEnvironmen...
Origin fromSuper = EncryptablePropertySource.super.getOrigin(key); if (fromSuper != null) { return fromSuper; } String property = resolvePropertyName(key); if (super.containsProperty(property)) { return new SystemEnvironmentOrigin(property); } ...
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} ...
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 Collectio...
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 ...
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 = document...
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(),...
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>} /** * Crea...
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.FactoryMak...
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. /** * ...
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...
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) { ...
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...
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 e...
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(); } ...
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 =...
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::ran...
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 startTi...
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("...
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...
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 ShopExce...
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 ShopExcepti...
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)) {...
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...
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() ...
if (isSuccessResponse(httpResponse.statusCode())) { LOGGER.info("Image path received successfully"); } else { LOGGER.warn("Image path request failed"); }
316
50
366
<no_super_class>