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
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-common/src/main/java/io/fabric8/kubernetes/model/jackson/BeanPropertyWriterDelegate.java
BeanPropertyWriterDelegate
serializeAsField
class BeanPropertyWriterDelegate extends BeanPropertyWriter { private static final Logger logger = LoggerFactory.getLogger(BeanPropertyWriterDelegate.class); private final BeanPropertyWriter delegate; private final AnnotatedMember anyGetter; private final transient Supplier<Boolean> logDuplicateWarning; BeanPropertyWriterDelegate(BeanPropertyWriter delegate, AnnotatedMember anyGetter, Supplier<Boolean> logDuplicateWarning) { super(delegate); this.delegate = delegate; this.anyGetter = anyGetter; this.logDuplicateWarning = logDuplicateWarning; } @Override public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {<FILL_FUNCTION_BODY>} @Override public void assignNullSerializer(JsonSerializer<Object> nullSer) { delegate.assignNullSerializer(nullSer); } @Override public void assignSerializer(JsonSerializer<Object> ser) { delegate.assignSerializer(ser); } @Override public void assignTypeSerializer(TypeSerializer typeSer) { delegate.assignTypeSerializer(typeSer); } }
Object valueInAnyGetter = null; if (anyGetter != null) { Object anyGetterValue = anyGetter.getValue(bean); if (anyGetterValue != null) { valueInAnyGetter = ((Map<?, ?>) anyGetterValue).get(delegate.getName()); } } if (valueInAnyGetter == null) { delegate.serializeAsField(bean, gen, prov); } else if (Boolean.TRUE.equals(logDuplicateWarning.get())) { logger.warn("Value in field '{}' ignored in favor of value in additionalProperties ({}) for {}", delegate.getName(), valueInAnyGetter, bean.getClass().getName()); }
299
185
484
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-common/src/main/java/io/fabric8/kubernetes/model/jackson/JsonUnwrappedDeserializer.java
UnwrappedInfo
deserialize
class UnwrappedInfo { final String propertyName; final NameTransformer nameTransformer; final Set<String> beanPropertyNames; public UnwrappedInfo(DeserializationContext context, BeanPropertyDefinition unwrappedProperty) { propertyName = unwrappedProperty.getName(); final JsonUnwrapped annotation = unwrappedProperty.getField().getAnnotation(JsonUnwrapped.class); nameTransformer = NameTransformer.simpleTransformer(annotation.prefix(), annotation.suffix()); beanPropertyNames = new HashSet<>(); // Extract viable property names for deserialization and nested deserialization final Set<Class<?>> processedTypes = new HashSet<>(); extractPropertiesDeep(context, processedTypes, beanPropertyNames, unwrappedProperty); } private static void extractPropertiesDeep(DeserializationContext context, Set<Class<?>> processedTypes, Set<String> properties, BeanPropertyDefinition bean) { final Collection<NamedType> types = context.getConfig().getSubtypeResolver() .collectAndResolveSubtypesByClass(context.getConfig(), context.getConfig().introspect(bean.getPrimaryType()).getClassInfo()); for (NamedType type : types) { if (!processedTypes.add(type.getType())) { continue; } for (BeanPropertyDefinition property : context.getConfig().introspect(context.constructType(type.getType())) .findProperties()) { properties.add(property.getName()); extractPropertiesDeep(context, processedTypes, properties, property); } } } } @Override public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) throws JsonMappingException { return new JsonUnwrappedDeserializer<>(deserializationContext); } @Override public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {<FILL_FUNCTION_BODY>
final ObjectNode node = jsonParser.readValueAsTree(); final ObjectNode ownNode = deserializationContext.getNodeFactory().objectNode(); final Map<UnwrappedInfo, ObjectNode> unwrappedNodes = new HashMap<>(); node.fields().forEachRemaining(entry -> { final String key = entry.getKey(); final JsonNode value = entry.getValue(); boolean replaced = false; for (UnwrappedInfo unwrapped : unwrappedInfos) { final String transformed = unwrapped.nameTransformer.reverse(key); final ObjectNode unwrappedNode = unwrappedNodes.getOrDefault(unwrapped, deserializationContext.getNodeFactory().objectNode()); if (transformed != null && !ownPropertyNames.contains(key) && unwrapped.beanPropertyNames.contains(transformed)) { unwrappedNodes.putIfAbsent(unwrapped, unwrappedNode); unwrappedNode.replace(transformed, value); replaced = true; } } if (!replaced && ownPropertyNames.contains(key)) { ownNode.replace(key, value); } }); for (Map.Entry<UnwrappedInfo, ObjectNode> entry : unwrappedNodes.entrySet()) { ownNode.replace(entry.getKey().propertyName, entry.getValue()); } try (TreeTraversingParser syntheticParser = new TreeTraversingParser(ownNode, jsonParser.getCodec())) { syntheticParser.nextToken(); return beanDeserializer.deserialize(syntheticParser, deserializationContext); }
501
409
910
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-common/src/main/java/io/fabric8/kubernetes/model/jackson/SettableBeanPropertyDelegate.java
SettableBeanPropertyDelegate
deserializeSetAndReturn
class SettableBeanPropertyDelegate extends SettableBeanProperty { private final SettableBeanProperty delegate; private final SettableAnyProperty anySetter; private final transient BooleanSupplier useAnySetter; SettableBeanPropertyDelegate(SettableBeanProperty delegate, SettableAnyProperty anySetter, BooleanSupplier useAnySetter) { super(delegate); this.delegate = delegate; this.anySetter = anySetter; this.useAnySetter = useAnySetter; } /** * {@inheritDoc} */ @Override public SettableBeanProperty withValueDeserializer(JsonDeserializer<?> deser) { return new SettableBeanPropertyDelegate(delegate.withValueDeserializer(deser), anySetter, useAnySetter); } /** * {@inheritDoc} */ @Override public SettableBeanProperty withName(PropertyName newName) { return new SettableBeanPropertyDelegate(delegate.withName(newName), anySetter, useAnySetter); } /** * {@inheritDoc} */ @Override public SettableBeanProperty withNullProvider(NullValueProvider nva) { return new SettableBeanPropertyDelegate(delegate.withNullProvider(nva), anySetter, useAnySetter); } /** * {@inheritDoc} */ @Override public AnnotatedMember getMember() { return delegate.getMember(); } /** * {@inheritDoc} */ @Override public <A extends Annotation> A getAnnotation(Class<A> acls) { return delegate.getAnnotation(acls); } /** * {@inheritDoc} */ @Override public void fixAccess(DeserializationConfig config) { delegate.fixAccess(config); } /** * {@inheritDoc} */ @Override public void markAsIgnorable() { delegate.markAsIgnorable(); } /** * {@inheritDoc} */ @Override public boolean isIgnorable() { return delegate.isIgnorable(); } /** * Method called to deserialize appropriate value, given parser (and context), and set it using appropriate mechanism. * * <p> * Deserialization is first tried through the delegate. In case a {@link MismatchedInputException} is caught, * the field is stored in the bean's {@link SettableAnyProperty} anySetter field if it exists. * * <p> * This allows deserialization processes propagate values that initially don't match the target bean type for the * applicable field. * * <p> * An example use-case is the use of placeholders (e.g. {@code ${aValue}}) in a field. */ @Override public void deserializeAndSet(JsonParser p, DeserializationContext ctxt, Object instance) throws IOException { try { delegate.deserializeAndSet(p, ctxt, instance); } catch (MismatchedInputException ex) { if (shouldUseAnySetter()) { anySetter.set(instance, delegate.getName(), p.getText()); } else { throw ex; } } } /** * {@inheritDoc} */ @Override public Object deserializeSetAndReturn(JsonParser p, DeserializationContext ctxt, Object instance) throws IOException {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override public void set(Object instance, Object value) throws IOException { delegate.set(instance, value); } /** * {@inheritDoc} */ @Override public Object setAndReturn(Object instance, Object value) throws IOException { return delegate.setAndReturn(instance, value); } private boolean shouldUseAnySetter() { if (anySetter == null) { return false; } return useAnySetter.getAsBoolean(); } }
try { return delegate.deserializeSetAndReturn(p, ctxt, instance); } catch (MismatchedInputException ex) { deserializeAndSet(p, ctxt, instance); } return null;
1,047
63
1,110
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-common/src/main/java/io/fabric8/kubernetes/model/jackson/UnmatchedFieldTypeModule.java
UnmatchedFieldTypeModule
updateBuilder
class UnmatchedFieldTypeModule extends SimpleModule { private boolean logWarnings; private boolean restrictToTemplates; private static final ThreadLocal<Boolean> IN_TEMPLATE = ThreadLocal.withInitial(() -> false); public UnmatchedFieldTypeModule() { this(true, true); } public UnmatchedFieldTypeModule(boolean logWarnings, boolean restrictToTemplates) { this.logWarnings = logWarnings; this.restrictToTemplates = restrictToTemplates; setDeserializerModifier(new BeanDeserializerModifier() { @Override public BeanDeserializerBuilder updateBuilder(DeserializationConfig config, BeanDescription beanDesc, BeanDeserializerBuilder builder) { builder.getProperties().forEachRemaining(p -> builder.addOrReplaceProperty( new SettableBeanPropertyDelegate(p, builder.getAnySetter(), UnmatchedFieldTypeModule.this::useAnySetter) { }, true)); return builder; } }); setSerializerModifier(new BeanSerializerModifier() { @Override public BeanSerializerBuilder updateBuilder(SerializationConfig config, BeanDescription beanDesc, BeanSerializerBuilder builder) {<FILL_FUNCTION_BODY>} }); } boolean isLogWarnings() { return logWarnings; } /** * Set if warnings should be logged for ambiguous serializer and deserializer situations. * * @param logWarnings if true, warnings will be logged. */ public void setLogWarnings(boolean logWarnings) { this.logWarnings = logWarnings; } boolean isRestrictToTemplates() { return restrictToTemplates; } boolean useAnySetter() { return !restrictToTemplates || isInTemplate(); } /** * Sets if the DeserializerModifier should only be applied to Templates or object trees contained in Templates. * * @param restrictToTemplates if true, the DeserializerModifier will only be applicable for Templates. */ public void setRestrictToTemplates(boolean restrictToTemplates) { this.restrictToTemplates = restrictToTemplates; } public static boolean isInTemplate() { return Boolean.TRUE.equals(IN_TEMPLATE.get()); } public static void setInTemplate() { IN_TEMPLATE.set(true); } public static void removeInTemplate() { IN_TEMPLATE.remove(); } }
builder.setProperties(builder.getProperties().stream() .map(p -> new BeanPropertyWriterDelegate(p, builder.getBeanDescription().findAnyGetter(), UnmatchedFieldTypeModule.this::isLogWarnings)) .collect(Collectors.toList())); return builder;
666
78
744
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-common/src/main/java/io/fabric8/kubernetes/model/jackson/UnwrappedTypeResolverBuilder.java
UnwrappedTypeResolverBuilder
buildTypeSerializer
class UnwrappedTypeResolverBuilder extends StdTypeResolverBuilder { @Override public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType, Collection<NamedType> subtypes) {<FILL_FUNCTION_BODY>} }
// To force Jackson to go through all the properties return null;
63
20
83
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-common/src/main/java/io/fabric8/kubernetes/model/util/Helper.java
Helper
loadJson
class Helper { private Helper() { throw new IllegalStateException("Utility class"); } public static String loadJson(String path) {<FILL_FUNCTION_BODY>} /** * @deprecated */ @Deprecated public static String getAnnotationValue(Class kubernetesResourceType, Class annotationClass) { Annotation annotation = getAnnotation(kubernetesResourceType, annotationClass); if (annotation instanceof Group) { return ((Group) annotation).value(); } else if (annotation instanceof Version) { return ((Version) annotation).value(); } return null; } private static Annotation getAnnotation(Class kubernetesResourceType, Class annotationClass) { return Arrays.stream(kubernetesResourceType.getAnnotations()) .filter(annotation -> annotation.annotationType().equals(annotationClass)) .findFirst() .orElse(null); } }
try (InputStream resourceAsStream = Helper.class.getResourceAsStream(path)) { final Scanner scanner = new Scanner(resourceAsStream).useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; } catch (IOException e) { throw new RuntimeException(e); }
238
87
325
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/api/Pluralize.java
Pluralize
apply
class Pluralize implements UnaryOperator<String> { private static final Pluralize INSTANCE = new Pluralize(); private static final Set<String> UNCOUNTABLE = new HashSet<>(Arrays.asList("equipment", "fish", "information", "money", "rice", "series", "sheep", "species", "news")); private static final Map<String, String> EXCEPTIONS = new HashMap<>(); static { EXCEPTIONS.put("person", "people"); EXCEPTIONS.put("woman", "women"); EXCEPTIONS.put("man", "men"); EXCEPTIONS.put("child", "children"); EXCEPTIONS.put("ox", "oxen"); EXCEPTIONS.put("die", "dice"); EXCEPTIONS.put("podmetrics", "pods"); EXCEPTIONS.put("nodemetrics", "nodes"); EXCEPTIONS.put("networkattachmentdefinition", "network-attachment-definitions"); EXCEPTIONS.put("egressqos", "egressqoses"); } private static final List<UnaryOperator<String>> PLURALS = Arrays.asList( //Rules new StringReplace("([^aeiouy]|qu)y$", "$1ies"), new StringReplace("(x|ch|ss|sh)$", "$1es"), new StringReplace("(s)?ex$", "$1exes"), new StringReplace("(bus)$", "$1es"), new StringReplace("(quiz)$", "$1zes"), new StringReplace("(matr)ix$", "$1ices"), new StringReplace("(vert|ind)ex$", "$1ices"), new StringReplace("(alias|status|dns)$", "$1es"), new StringReplace("(octop|vir)us$", "$1us"), new StringReplace("(cris|ax|test)is$", "$1es"), new StringReplace("(o)$", "$1es"), new StringReplace("([m|l])ouse$", "$1ice"), new StringReplace("([lr])f$", "$1ves"), new StringReplace("([^f])fe$", "$1ves"), new StringReplace("(^analy)sis$", "$1sis"), new StringReplace("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis"), new StringReplace("([ti])um$", "$1a"), new StringReplace("(prometheus)$", "$1es"), new StringReplace("(s|si|u)s$", "$1s")); public static String toPlural(String word) { return INSTANCE.apply(word); } @Override public String apply(String word) {<FILL_FUNCTION_BODY>} /** * Rudimentary implementation of checking whether word is plural or not. It can be further * improved to handle complex cases. * * @param word the word to test * @return {@code true} if the specified word is already plural, {@code false} otherwise */ private boolean isAlreadyPlural(String word) { if (!word.endsWith("ss")) { return word.endsWith("s"); } return false; } private static class StringReplace implements UnaryOperator<String> { private final String replacement; private final Pattern pattern; public StringReplace(String target, String replacement) { this.replacement = replacement; this.pattern = Pattern.compile(target, Pattern.CASE_INSENSITIVE); } @Override public String apply(String word) { Matcher matcher = this.pattern.matcher(word); if (!matcher.find()) { return null; } return matcher.replaceAll(replacement); } } }
if (word == null || word.isEmpty() || UNCOUNTABLE.contains(word)) { return word; } // deal with exceptions String plural = EXCEPTIONS.get(word); if (plural != null) { return plural; } // apply rules for (UnaryOperator<String> function : PLURALS) { String result = function.apply(word); if (result != null) { return result; } } // we haven't found a match, if the word is already plural, return it or add a final 's' return isAlreadyPlural(word) ? word : word + "s";
1,021
175
1,196
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/api/model/Duration.java
Duration
parse
class Duration implements KubernetesResource { private static final long serialVersionUID = -2326157920610452294L; private static final String DURATION_REGEX = "(\\d+)\\s*([A-Za-zµ]+)"; private static final Pattern DURATION_PATTERN = Pattern.compile(DURATION_REGEX); private java.time.Duration javaDuration; /** * No args constructor for use in serialization */ public Duration() { } public Duration(java.time.Duration javaDuration) { this.javaDuration = javaDuration; } public java.time.Duration getDuration() { return javaDuration; } public void setDuration(java.time.Duration javaDuration) { this.javaDuration = javaDuration; } /** * Converts Duration to a primitive value ready to be written to a database. * * @return duration value in nanoseconds */ public Long getValue() { return Optional.ofNullable(javaDuration).map(java.time.Duration::toNanos).orElse(0L); } /** * Tests if the provided string represents a valid Duration. * * @param durationToTest String with a possible Duration value * @return true if the provided String is a Duration, false otherwise */ public static boolean isDuration(String durationToTest) { try { Duration.parse(durationToTest); return true; } catch (ParseException e) { return false; } } /** * Parses {@link String} into Duration. * * <table> * <caption>Valid time abbreviations</caption> * <thead> * <tr> * <th>Abbreviation</th> * <th>Time Unit</th> * </tr> * </thead> * <tbody> * <tr> * <td>ns, nano, nanos</td> * <td>Nanosecond</td> * </tr> * <tr> * <td>us, µs, micro, micros</td> * <td>Microseconds</td> * </tr> * <tr> * <td>ms, milli, millis</td> * <td>Millisecond</td> * </tr> * <tr> * <td>s, sec, secs</td> * <td>Second</td> * </tr> * <tr> * <td>m, min, mins</td> * <td>Minute</td> * </tr> * <tr> * <td>h, hr, hour, hours</td> * <td>Hour</td> * </tr> * <tr> * <td>d, day, days</td> * <td>Day</td> * </tr> * <tr> * <td>w, wk, week, weeks</td> * <td>Week</td> * </tr> * </tbody> * </table> * <br> * <p> * Example: * * <pre>{@code * Duration.parse("1min1s"); * }</pre> * * @param duration String to be parsed * @return the parsed Duration * @throws ParseException if format is not parsable */ @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static Duration parse(String duration) throws ParseException {<FILL_FUNCTION_BODY>} public static class Serializer extends JsonSerializer<Duration> { @Override public void serialize(Duration duration, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeString(String.format("%sns", duration.getValue())); } } private enum TimeUnits { NANOSECOND(ChronoUnit.NANOS, "ns", "nano", "nanos"), MICROSECOND(ChronoUnit.MICROS, "us", "µs", "micro", "micros"), MILLISECOND(ChronoUnit.MILLIS, "ms", "milli", "millis"), SECOND(ChronoUnit.SECONDS, "s", "sec", "secs"), MINUTE(ChronoUnit.MINUTES, "m", "min", "mins"), HOUR(ChronoUnit.HOURS, "h", "hr", "hour", "hours"), DAY(ChronoUnit.DAYS, "d", "day", "days"), WEEK(SevenDayWeek.INSTANCE, "w", "wk", "week", "weeks"); private final Set<String> abbreviations; private final TemporalUnit timeUnit; TimeUnits(TemporalUnit timeUnit, String... abbreviations) { this.timeUnit = timeUnit; this.abbreviations = new HashSet<>(Arrays.asList(abbreviations)); } static TimeUnits from(String abbreviation) { return Stream.of(values()).filter(tu -> tu.abbreviations.contains(abbreviation.toLowerCase())).findAny() .orElse(null); } } /** * Provides an <strong>exact</strong> {@link TemporalUnit} implementation * of a 7 day week. */ private static class SevenDayWeek implements TemporalUnit { private static final SevenDayWeek INSTANCE = new SevenDayWeek(); private static final java.time.Duration SEVEN_DAYS = java.time.Duration.ofDays(7L); private SevenDayWeek() { } @Override public java.time.Duration getDuration() { return SEVEN_DAYS; } @Override public boolean isDurationEstimated() { return false; } @Override public boolean isDateBased() { return true; } @Override public boolean isTimeBased() { return false; } @SuppressWarnings("unchecked") @Override public <R extends Temporal> R addTo(R temporal, long amount) { return (R) temporal.plus(amount, this); } @Override public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) { return temporal1Inclusive.until(temporal2Exclusive, this); } } }
java.time.Duration accumulator = java.time.Duration.ZERO; boolean found = false; final Matcher matcher = Optional.ofNullable(duration).map(String::trim).map(DURATION_PATTERN::matcher).orElse(null); while (matcher != null && matcher.find()) { found = true; final java.time.Duration durationToken = Optional.ofNullable(TimeUnits.from(matcher.group(2))) .map(tu -> java.time.Duration.of(Long.parseLong(matcher.group(1)), tu.timeUnit)) .orElseThrow(() -> new ParseException(String.format("Invalid duration token (%s)", matcher.group()), 0)); accumulator = accumulator.plus(durationToken); } if (!found) { throw new ParseException(String.format("Provided duration string (%s) is invalid", duration), 0); } return new Duration(accumulator);
1,771
253
2,024
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/api/model/GenericKubernetesResource.java
GenericKubernetesResource
get
class GenericKubernetesResource implements HasMetadata { private static final ObjectMapper MAPPER = new ObjectMapper(); @JsonProperty("apiVersion") private String apiVersion; @JsonProperty("kind") private String kind; @JsonProperty("metadata") private ObjectMeta metadata; @JsonIgnore private Map<String, Object> additionalProperties = new LinkedHashMap<>(); @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } public void setAdditionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } /** * @deprecated use KubernetesSerialization to convert the additionalProperties */ @Deprecated @JsonIgnore public JsonNode getAdditionalPropertiesNode() { return MAPPER.convertValue(getAdditionalProperties(), JsonNode.class); } /** * Allows the retrieval of field values from this Resource for the provided path segments. * * <p> * If the path segment is of type {@link Integer}, then we assume that it is an array index to retrieve * the value of an entry in the array. * * <p> * If the path segment is of type {@link String}, then we assume that it is a field name to retrieve the value * from the resource. * * <p> * In any other case, the path segment is ignored and considered invalid. The method returns null. * * <p> * Considering the following JSON object: * * <pre>{@code * { * "field": { * "value": 42 * "list": [ * {entry: 1}, {entry: 2}, {entry: 3} * ], * "1": "one" * } * } * }</pre> * * <p> * The following invocations will produce the documented results: * <ul> * <li>{@code get("field", "value")} will result in {@code 42}</li> * <li>{@code get("field", "1")} will result in {@code "one"}</li> * <li>{@code get("field", 1)} will result in {@code null}</li> * <li>{@code get("field", "list", 1, "entry")} will result in {@code 2}</li> * <li>{@code get("field", "list", 99, "entry")} will result in {@code null}</li> * <li>{@code get("field", "list", "1", "entry")} will result in {@code null}</li> * <li>{@code get("field", "list", 1, false)} will result in {@code null}</li> * </ul> * * @param path of the field to retrieve. * @param <T> type of the returned object. * @return the value of the traversed path or null if the field does not exist. */ public <T> T get(Object... path) { return get(getAdditionalProperties(), path); } /** * The same as {@link #get(Object...)}, but starting at any root raw object * * @param <T> type of the returned object (Map, Collection, or value). * @param root starting object * @param path of the field to retrieve. * @return the value of the traversed path or null if the field does not exist. */ @SuppressWarnings("unchecked") public static <T> T get(Map<String, Object> root, Object... path) {<FILL_FUNCTION_BODY>} }
Object current = root; for (Object segment : path) { if (segment instanceof Integer && current instanceof Collection && ((Collection<?>) current).size() > (int) segment) { current = ((Collection<Object>) current).toArray()[(int) segment]; } else if (segment instanceof String && current instanceof Map) { current = ((Map<String, Object>) current).get(segment.toString()); } else { return null; } } return (T) current;
1,012
131
1,143
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/api/model/HasMetadataComparator.java
HasMetadataComparator
getKindValue
class HasMetadataComparator implements Comparator<HasMetadata> { private Integer getKindValue(String kind) {<FILL_FUNCTION_BODY>} @Override public int compare(HasMetadata a, HasMetadata b) { if (a == null || b == null) { throw new NullPointerException("Cannot compare null HasMetadata objects"); } if (a == b || a.equals(b)) { return 0; } int kindOrderCompare = getKindValue(a.getKind()).compareTo(getKindValue(b.getKind())); if (kindOrderCompare != 0) { return kindOrderCompare; } String classNameA = a.getClass().getSimpleName(); String classNameB = b.getClass().getSimpleName(); int classCompare = classNameA.compareTo(classNameB); if (classCompare != 0) { return classCompare; } return a.getMetadata().getName().compareTo(b.getMetadata().getName()); } }
try { switch (kind) { case "SecurityContextConstraints": return 0; case "Namespace": case "Project": case "ProjectRequest": return 1; case "LimitRange": return 2; case "ResourceQuota": return 3; case "RoleBindingRestriction": return 4; case "Secret": return 12; case "ServiceAccount": return 13; case "OAuthClient": return 14; case "Service": return 15; case "PolicyBinding": return 16; case "ClusterPolicyBinding": return 17; case "Role": return 18; case "RoleBinding": return 19; case "PersistentVolume": return 20; case "PersistentVolumeClaim": return 21; case "ImageStream": return 30; case "ImageStreamTag": return 31; default: return 100; } } catch (IllegalArgumentException e) { return 100; }
259
305
564
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/api/model/IntOrString.java
IntOrString
setValue
class IntOrString extends AnyType { public IntOrString() { } @JsonCreator //Builders are generated for the first non-empty constructor found. @Buildable(editableEnabled = false, generateBuilderPackage = false, builderPackage = "io.fabric8.kubernetes.api.builder") public IntOrString(Object value) { setValue(value); } @Override public void setValue(Object value) {<FILL_FUNCTION_BODY>} /** * Get Integer value * * @return Integer value if set */ public Integer getIntVal() { if (value instanceof Integer) { return (Integer) value; } return null; } /** * Get String value * * @return string value if set */ public String getStrVal() { if (value instanceof String) { return (String) value; } return null; } }
if (value != null && !(value instanceof Integer) && !(value instanceof String)) { throw new IllegalArgumentException("Either integer or string value needs to be provided"); } super.setValue(value);
256
56
312
<methods>public void <init>() ,public void <init>(java.lang.Object) ,public java.lang.Object getValue() <variables>protected java.lang.Object value
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/api/model/MicroTimeSerDes.java
Deserializer
deserialize
class Deserializer extends JsonDeserializer<MicroTime> { @Override public MicroTime deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {<FILL_FUNCTION_BODY>} }
ObjectCodec oc = jsonParser.getCodec(); JsonNode node = oc.readTree(jsonParser); MicroTime microTime = null; if (node != null) { microTime = new MicroTime(node.asText()); } return microTime;
59
73
132
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/internal/KubernetesDeserializer.java
TypeKey
equals
class TypeKey { final String kind; final String apiGroup; final String version; TypeKey(String kind, String apiGroup, String version) { this.kind = kind; this.apiGroup = apiGroup; this.version = version; } @Override public int hashCode() { return Objects.hash(kind, apiGroup, version); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} }
if (this == obj) { return true; } if (!(obj instanceof TypeKey)) { return false; } TypeKey o = (TypeKey) obj; return Objects.equals(kind, o.kind) && Objects.equals(apiGroup, o.apiGroup) && Objects.equals(version, o.version);
132
93
225
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-jsonschema2pojo/src/main/java/io/fabric8/kubernetes/jsonschema2pojo/Fabric8DefaultRule.java
Fabric8DefaultRule
apply
class Fabric8DefaultRule extends DefaultRule { private final RuleFactory ruleFactory; public Fabric8DefaultRule(RuleFactory ruleFactory) { super(ruleFactory); this.ruleFactory = ruleFactory; } @Override public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {<FILL_FUNCTION_BODY>} }
JType fieldType = field.type(); String fieldTypeName = fieldType.fullName(); if (ruleFactory.getGenerationConfig().isInitializeCollections()) { // add a default for maps if missing, rejected upstream https://github.com/joelittlejohn/jsonschema2pojo/issues/955 if (fieldTypeName.startsWith(Map.class.getName()) && (node == null || node.asText() == null || node.asText().isEmpty())) { JClass keyGenericType = ((JClass) fieldType).getTypeParameters().get(0); JClass valueGenericType = ((JClass) fieldType).getTypeParameters().get(1); JClass mapImplClass = fieldType.owner().ref(LinkedHashMap.class); mapImplClass = mapImplClass.narrow(keyGenericType, valueGenericType); field.init(JExpr._new(mapImplClass)); } // maps and some lists are not marked as omitJavaEmpty - it's simplest to just add the annotation here, rather than updating the generator JClass jsonInclude = fieldType.owner().ref(JsonInclude.class); if ((fieldTypeName.startsWith(Map.class.getName()) || fieldTypeName.startsWith(List.class.getName())) && field.annotations().stream() .noneMatch(annotation -> annotation.getAnnotationClass().isAssignableFrom(jsonInclude))) { field.annotate(jsonInclude).param(KubernetesCoreTypeAnnotator.ANNOTATION_VALUE, JsonInclude.Include.NON_EMPTY); } } return super.apply(nodeName, node, parent, field, currentSchema);
108
422
530
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-jsonschema2pojo/src/main/java/io/fabric8/kubernetes/jsonschema2pojo/Fabric8EnumRule.java
Fabric8EnumRule
getEnumFromValueConstants
class Fabric8EnumRule extends EnumRule { private static final String TO_LOWERCASE_METHOD = "toLowerCase"; private final RuleFactory ruleFactory; protected Fabric8EnumRule(RuleFactory ruleFactory) { super(ruleFactory); this.ruleFactory = ruleFactory; } @Override protected void addFieldAccessors(JDefinedClass _enum, JFieldVar valueField) { // do nothing } protected void addFactoryMethod(EnumDefinition enumDefinition, JDefinedClass _enum) { JClass stringType = _enum.owner().ref(String.class); JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue"); JVar valueParam = fromValue.param(_enum.owner().ref(Object.class), "value"); JBlock body = fromValue.body(); JFieldVar backingTypeLookupMap = addValueLookupMap(enumDefinition, _enum); JFieldVar addNameLookupMap = addNameLookupMap(_enum); // if param instanceof String JConditional _ifString = body._if(valueParam._instanceof(stringType)); getEnumFromNameConstants(_ifString._then().block(), valueParam, addNameLookupMap, enumDefinition, _enum); getEnumFromValueConstants(body, valueParam, backingTypeLookupMap, enumDefinition, _enum); ruleFactory.getAnnotator().enumCreatorMethod(_enum, fromValue); } protected void getEnumFromValueConstants(JBlock body, JVar valueParam, JFieldVar quickLookupMap, EnumDefinition enumDefinition, JDefinedClass _enum) {<FILL_FUNCTION_BODY>} protected void getEnumFromNameConstants(JBlock body, JVar valueParam, JFieldVar quickLookupMap, EnumDefinition enumDefinition, JDefinedClass _enum) { JType backingType = enumDefinition.getBackingType(); JClass stringType = _enum.owner().ref(String.class); JVar constant = body.decl(_enum, "constant").init(quickLookupMap.invoke("get") .arg(JExpr.invoke(JExpr.cast(stringType, valueParam), TO_LOWERCASE_METHOD))); JConditional _if = body._if(constant.eq(JExpr._null())); _if._then()._throw(illegalArgumentException(valueParam, _enum, backingType)); _if._else()._return(constant); } private JInvocation illegalArgumentException(JVar valueParam, JDefinedClass _enum, JType backingType) { JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class)); JExpression expr = valueParam; // if string no need to add "" if (!isString(backingType)) { expr = expr.plus(JExpr.lit("")); } illegalArgumentException.arg(expr); return illegalArgumentException; } protected JFieldVar addValueLookupMap(EnumDefinition enumDefinition, JDefinedClass _enum) { JType backingType = enumDefinition.getBackingType(); JClass lookupType = _enum.owner().ref(Map.class).narrow(backingType.boxify(), _enum); JFieldVar backingTypeLookupMap = _enum.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, lookupType, "CONSTANTS"); JClass lookupImplType = _enum.owner().ref(HashMap.class).narrow(backingType.boxify(), _enum); backingTypeLookupMap.init(JExpr._new(lookupImplType)); JForEach forEach = _enum.init().forEach(_enum, "c", JExpr.invoke("values")); JInvocation put = forEach.body().invoke(backingTypeLookupMap, "put"); if (isString(backingType)) { put.arg(forEach.var().ref("value").invoke(TO_LOWERCASE_METHOD)); } else { put.arg(forEach.var().ref("value")); } put.arg(forEach.var()); return backingTypeLookupMap; } protected JFieldVar addNameLookupMap(JDefinedClass _enum) { JClass stringType = _enum.owner().ref(String.class); JClass nameLookupType = _enum.owner().ref(Map.class).narrow(stringType, _enum); JFieldVar nameLookupMap = _enum.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, nameLookupType, "NAME_CONSTANTS"); JClass lookupImplType = _enum.owner().ref(HashMap.class).narrow(stringType, _enum); nameLookupMap.init(JExpr._new(lookupImplType)); JForEach forEach = _enum.init().forEach(_enum, "c", JExpr.invoke("values")); JInvocation namePut = forEach.body().invoke(nameLookupMap, "put"); namePut.arg(forEach.var().invoke("name").invoke(TO_LOWERCASE_METHOD)); namePut.arg(forEach.var()); return nameLookupMap; } }
JType backingType = enumDefinition.getBackingType(); JVar constant = body.decl(_enum, "constant").init(quickLookupMap.invoke("get").arg(valueParam)); JConditional _if = body._if(constant.eq(JExpr._null())); _if._then()._throw(illegalArgumentException(valueParam, _enum, backingType)); _if._else()._return(constant);
1,328
107
1,435
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-jsonschema2pojo/src/main/java/io/fabric8/kubernetes/jsonschema2pojo/Fabric8NameHelper.java
Fabric8NameHelper
correctCamelCaseWithPrefix
class Fabric8NameHelper extends NameHelper { private static final Map<String, String> PROTECTED_WORD_MAP = new HashMap<>(); static { PROTECTED_WORD_MAP.put("class", "className"); } private static final Pattern SINGLE_LETTER_PREFIX_WORD_PROPERTY = Pattern.compile("^[a-z]((-[a-zA-Z])|[A-Z])(.*)$"); public Fabric8NameHelper(GenerationConfig generationConfig) { super(generationConfig); } @Override public String getFieldName(String propertyName, JsonNode node) { final String fieldName = super.getFieldName(propertyName, node); return PROTECTED_WORD_MAP.getOrDefault(fieldName, fieldName); } @Override public String getGetterName(String propertyName, JType type, JsonNode node) { return correctCamelCaseWithPrefix(propertyName, super.getGetterName(propertyName, type, node)); } @Override public String getSetterName(String propertyName, JsonNode node) { return correctCamelCaseWithPrefix(propertyName, super.getSetterName(propertyName, node)); } static String correctCamelCaseWithPrefix(String propertyName, String functionName) {<FILL_FUNCTION_BODY>} }
final Matcher m = SINGLE_LETTER_PREFIX_WORD_PROPERTY.matcher(propertyName); if (m.matches()) { // https://github.com/joelittlejohn/jsonschema2pojo/issues/1028 + Sundr.io expecting the opposite (setXKubernetes... instead of setxKubernetes) return functionName.substring(0, 3) + functionName.substring(3, 4).toUpperCase() + functionName.substring(4); } return functionName;
353
142
495
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-jsonschema2pojo/src/main/java/io/fabric8/kubernetes/jsonschema2pojo/Fabric8ObjectRule.java
Fabric8ObjectRule
createInterface
class Fabric8ObjectRule extends ObjectRule { private static final String INTERFACE_TYPE_PROPERTY = "interfaceType"; private static final String INTERFACE_IMPLEMENTATIONS_TYPE_PROPERTY = "interfaceImpls"; private static final String VALUE_PROPERTY = "value"; private final RuleFactory ruleFactory; protected Fabric8ObjectRule(RuleFactory ruleFactory, ParcelableHelper parcelableHelper, ReflectionHelper reflectionHelper) { super(ruleFactory, parcelableHelper, reflectionHelper); this.ruleFactory = ruleFactory; } @Override public JType apply(String nodeName, JsonNode node, JsonNode parent, JPackage _package, Schema schema) { if (node.has(INTERFACE_TYPE_PROPERTY)) { // interface return createInterface(node, _package); } // rest of types return super.apply(nodeName, node, parent, _package, schema); } private JType createInterface(JsonNode node, JPackage _package) {<FILL_FUNCTION_BODY>} }
String fqn = node.path(INTERFACE_TYPE_PROPERTY).asText(); int index = fqn.lastIndexOf(".") + 1; JDefinedClass newType; try { newType = _package._interface(fqn.substring(index)); } catch (JClassAlreadyExistsException ex) { return ex.getExistingClass(); } this.ruleFactory.getAnnotator().typeInfo(newType, node); this.ruleFactory.getAnnotator().propertyInclusion(newType, node); // Allow to deserialize the interface from implementations: if (node.has(INTERFACE_IMPLEMENTATIONS_TYPE_PROPERTY)) { newType.annotate(JsonTypeResolver.class).param(VALUE_PROPERTY, UnwrappedTypeResolverBuilder.class); JAnnotationArrayMember subTypes = newType.annotate(JsonSubTypes.class).paramArray(VALUE_PROPERTY); JsonNode implementationsNode = node.get(INTERFACE_IMPLEMENTATIONS_TYPE_PROPERTY); List<String> implementations = new ArrayList<>(); for (JsonNode implementationNode : implementationsNode) { String implementation = implementationNode.textValue(); implementations.add(implementation); subTypes.annotate(JsonSubTypes.Type.class).param(VALUE_PROPERTY, new JCodeModel().ref(implementation)); } JAnnotationUse jsonTypeAnnotation = newType.annotate(JsonTypeInfo.class).param("use", JsonTypeInfo.Id.DEDUCTION); if (implementations.size() == 1) { jsonTypeAnnotation.param("defaultImpl", new JCodeModel().ref(implementations.get(0))); } } return newType;
278
452
730
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/kubernetes-model-jsonschema2pojo/src/main/java/io/fabric8/kubernetes/jsonschema2pojo/KubernetesTypeAnnotator.java
KubernetesTypeAnnotator
addBuildableTypes
class KubernetesTypeAnnotator extends KubernetesCoreTypeAnnotator { public KubernetesTypeAnnotator(GenerationConfig generationConfig) { super(generationConfig); } @Override protected boolean generateBuilderPackage() { return false; } @Override protected void addBuildableTypes(JDefinedClass clazz, List<String> types) {<FILL_FUNCTION_BODY>} }
types.add("io.fabric8.kubernetes.api.model.ObjectMeta"); types.add("io.fabric8.kubernetes.api.model.LabelSelector"); types.add("io.fabric8.kubernetes.api.model.Container"); types.add("io.fabric8.kubernetes.api.model.PodTemplateSpec"); types.add("io.fabric8.kubernetes.api.model.ResourceRequirements"); types.add("io.fabric8.kubernetes.api.model.IntOrString"); types.add("io.fabric8.kubernetes.api.model.ObjectReference"); types.add("io.fabric8.kubernetes.api.model.LocalObjectReference"); types.add("io.fabric8.kubernetes.api.model.PersistentVolumeClaim"); if (clazz.fields().values().stream() .anyMatch(f -> f.type().fullName().contains("io.fabric8.kubernetes.api.model.KubernetesResource") || f.type().fullName().contains("io.fabric8.kubernetes.api.model.HasMetadata") || f.type().fullName().contains("io.fabric8.kubernetes.api.model.RawExtension"))) { types.add("io.fabric8.kubernetes.api.model.GenericKubernetesResource"); types.add("io.fabric8.kubernetes.api.model.runtime.RawExtension"); }
114
380
494
<methods>public void <init>(GenerationConfig) ,public void propertyField(JFieldVar, JDefinedClass, java.lang.String, JsonNode) ,public void propertyInclusion(JDefinedClass, JsonNode) ,public void propertyOrder(JDefinedClass, JsonNode) <variables>protected static final java.lang.String ANNOTATION_VALUE,protected static final java.lang.String API_VERSION,public static final java.lang.String BUILDABLE_REFERENCE_VALUE,private static final java.lang.String BUILDER_PACKAGE,protected static final java.lang.String DEFAULT,private static final Set<java.lang.String> IGNORED_CLASSES,protected static final java.lang.String INTERFACE_TYPE_PROPERTY,protected static final java.lang.String KIND,protected static final java.lang.String METADATA,private final Set<java.lang.String> handledClasses,protected final Map<java.lang.String,JDefinedClass> pendingLists,protected final Map<java.lang.String,JDefinedClass> pendingResources
fabric8io_kubernetes-client
kubernetes-client/kubernetes-model-generator/openshift-model/src/main/java/io/fabric8/openshift/api/model/TemplateDeserializer.java
TemplateDeserializer
deserialize
class TemplateDeserializer extends JsonDeserializer<Template> { @Override public Template deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {<FILL_FUNCTION_BODY>} }
JavaType type = ctxt.getConfig().getTypeFactory().constructType(Template.class); BeanDescription description = ctxt.getConfig().introspect(type); JsonDeserializer<Object> beanDeserializer = ctxt.getFactory().createBeanDeserializer(ctxt, type, description); ((ResolvableDeserializer) beanDeserializer).resolve(ctxt); boolean inTemplate = false; if (!UnmatchedFieldTypeModule.isInTemplate()) { UnmatchedFieldTypeModule.setInTemplate(); inTemplate = true; } try { return (Template) beanDeserializer.deserialize(jsonParser, ctxt); } finally { if (inTemplate) { UnmatchedFieldTypeModule.removeInTemplate(); } }
57
203
260
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/log4j/src/main/java/io/fabric8/kubernetes/log4j/lookup/ClientBuilder.java
ClientBuilder
kubernetesClientConfig
class ClientBuilder { /** * If this system property is set to {@code true}, the client configuration is retrieved from Log4j Properties. */ public static final String KUBERNETES_LOG4J_USE_PROPERTIES = "kubernetes.log4j.useProperties"; private ClientBuilder() { } public static KubernetesClient createClient() { final Config config = kubernetesClientConfig(PropertiesUtil.getProperties()); return config != null ? new KubernetesClientBuilder() .withConfig(config).build() : null; } static Config kubernetesClientConfig(final PropertiesUtil props) {<FILL_FUNCTION_BODY>} }
try { final Config base = Config.autoConfigure(null); if (getSystemPropertyOrEnvVar(KUBERNETES_LOG4J_USE_PROPERTIES, false)) { final Log4jConfig log4jConfig = new Log4jConfig(props, base); return new ConfigBuilder() .withApiVersion(log4jConfig.getApiVersion()) .withCaCertData(log4jConfig.getCaCertData()) .withCaCertFile(log4jConfig.getCaCertFile()) .withClientCertData(log4jConfig.getClientCertData()) .withClientCertFile(log4jConfig.getClientCertFile()) .withClientKeyAlgo(log4jConfig.getClientKeyAlgo()) .withClientKeyData(log4jConfig.getClientKeyData()) .withClientKeyFile(log4jConfig.getClientKeyFile()) .withClientKeyPassphrase(log4jConfig.getClientKeyPassphrase()) .withConnectionTimeout(log4jConfig.getConnectionTimeout()) .withHttpProxy(log4jConfig.getHttpProxy()) .withHttpsProxy(log4jConfig.getHttpsProxy()) .withLoggingInterval(log4jConfig.getLoggingInterval()) .withMasterUrl(log4jConfig.getMasterUrl()) .withNamespace(log4jConfig.getNamespace()) .withNoProxy(log4jConfig.getNoProxy()) .withPassword(log4jConfig.getPassword()) .withProxyPassword(log4jConfig.getProxyPassword()) .withProxyUsername(log4jConfig.getProxyUsername()) .withRequestTimeout(log4jConfig.getRequestTimeout()) .withTrustCerts(log4jConfig.isTrustCerts()) .withUsername(log4jConfig.getUsername()) .withWatchReconnectInterval(log4jConfig.getWatchReconnectInterval()) .withWatchReconnectLimit(log4jConfig.getWatchReconnectLimit()) .build(); } return base; } catch (final Exception e) { StatusLogger.getLogger().warn("An error occurred while retrieving Kubernetes Client configuration: {}.", e.getMessage(), e); } return null;
176
567
743
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/openshift-client-api/src/main/java/io/fabric8/openshift/client/DefaultOpenShiftClient.java
DefaultOpenShiftClient
newBuilder
class DefaultOpenShiftClient extends NamespacedOpenShiftClientAdapter { public static final String OPENSHIFT_VERSION_ENDPOINT = "version/openshift"; public DefaultOpenShiftClient() { this(new OpenShiftConfigBuilder().build()); } public DefaultOpenShiftClient(String masterUrl) { this(new OpenShiftConfigBuilder().withMasterUrl(masterUrl).build()); } public DefaultOpenShiftClient(final Config config) { this(new OpenShiftConfig(config)); } public DefaultOpenShiftClient(final OpenShiftConfig config) { this(HttpClientUtils.createHttpClient(config), config); } public DefaultOpenShiftClient(HttpClient httpClient, OpenShiftConfig config) { // basically copied from DefaultKubernetesClient to avoid creating another public method KubernetesClientBuilder builder = new KubernetesClientBuilder().withConfig(config); if (httpClient != null) { builder.withHttpClientFactory(new Factory() { @Override public Builder newBuilder() { throw new UnsupportedOperationException(); } @Override public Builder newBuilder(Config config) {<FILL_FUNCTION_BODY>} }); } this.init(builder.build()); } }
return new StandardHttpClientBuilder<HttpClient, HttpClient.Factory, StandardHttpClientBuilder<HttpClient, HttpClient.Factory, ?>>( null) { @Override public HttpClient build() { return httpClient; } @Override protected StandardHttpClientBuilder<HttpClient, HttpClient.Factory, StandardHttpClientBuilder<HttpClient, HttpClient.Factory, ?>> newInstance( Factory clientFactory) { return null; } };
323
120
443
<methods>public void <init>() ,public NonNamespaceOperation<APIRequestCount,APIRequestCountList,Resource<APIRequestCount>> apiRequestCounts() ,public MixedOperation<BareMetalHost,BareMetalHostList,Resource<BareMetalHost>> bareMetalHosts() ,public NonNamespaceOperation<BrokerTemplateInstance,BrokerTemplateInstanceList,Resource<BrokerTemplateInstance>> brokerTemplateInstances() ,public MixedOperation<BuildConfig,BuildConfigList,BuildConfigResource<BuildConfig,java.lang.Void,Build>> buildConfigs() ,public MixedOperation<Build,BuildList,io.fabric8.openshift.client.dsl.BuildResource> builds() ,public io.fabric8.openshift.client.dsl.OpenShiftClusterAutoscalingAPIGroupDSL clusterAutoscaling() ,public NonNamespaceOperation<ClusterNetwork,ClusterNetworkList,Resource<ClusterNetwork>> clusterNetworks() ,public MixedOperation<ClusterRoleBinding,ClusterRoleBindingList,Resource<ClusterRoleBinding>> clusterRoleBindings() ,public NonNamespaceOperation<ClusterRole,ClusterRoleList,Resource<ClusterRole>> clusterRoles() ,public NonNamespaceOperation<ComponentStatus,ComponentStatusList,Resource<ComponentStatus>> componentstatuses() ,public io.fabric8.openshift.client.dsl.OpenShiftConfigAPIGroupDSL config() ,public io.fabric8.openshift.client.dsl.OpenShiftConsoleAPIGroupDSL console() ,public MixedOperation<CredentialsRequest,CredentialsRequestList,Resource<CredentialsRequest>> credentialsRequests() ,public User currentUser() ,public MixedOperation<DeploymentConfig,DeploymentConfigList,DeployableScalableResource<DeploymentConfig>> deploymentConfigs() ,public MixedOperation<EgressNetworkPolicy,EgressNetworkPolicyList,Resource<EgressNetworkPolicy>> egressNetworkPolicies() ,public MixedOperation<EgressRouter,EgressRouterList,Resource<EgressRouter>> egressRouters() ,public io.fabric8.kubernetes.client.VersionInfo getOpenShiftV3Version() ,public java.lang.String getOpenShiftV4Version() ,public java.net.URL getOpenshiftUrl() ,public NonNamespaceOperation<Group,GroupList,Resource<Group>> groups() ,public NonNamespaceOperation<HelmChartRepository,HelmChartRepositoryList,Resource<HelmChartRepository>> helmChartRepositories() ,public io.fabric8.openshift.client.dsl.OpenShiftHiveAPIGroupDSL hive() ,public NonNamespaceOperation<HostSubnet,HostSubnetList,Resource<HostSubnet>> hostSubnets() ,public NonNamespaceOperation<Identity,IdentityList,Resource<Identity>> identities() ,public NonNamespaceOperation<io.fabric8.openshift.api.model.miscellaneous.imageregistry.operator.v1.Config,ConfigList,Resource<io.fabric8.openshift.api.model.miscellaneous.imageregistry.operator.v1.Config>> imageRegistryOperatorConfigs() ,public io.fabric8.openshift.client.dsl.NameableCreateOrDeleteable imageSignatures() ,public Namespaceable<Nameable<? extends Gettable<ImageStreamImage>>> imageStreamImages() ,public NamespacedInOutCreateable<ImageStreamImport,ImageStreamImport> imageStreamImports() ,public NamespacedInOutCreateable<ImageStreamMapping,ImageStreamMapping> imageStreamMappings() ,public MixedOperation<ImageStreamTag,ImageStreamTagList,Resource<ImageStreamTag>> imageStreamTags() ,public MixedOperation<ImageStream,ImageStreamList,Resource<ImageStream>> imageStreams() ,public MixedOperation<ImageTag,ImageTagList,Resource<ImageTag>> imageTags() ,public NonNamespaceOperation<Image,ImageList,Resource<Image>> images() ,public io.fabric8.openshift.client.NamespacedOpenShiftClientAdapter inAnyNamespace() ,public io.fabric8.openshift.client.NamespacedOpenShiftClientAdapter inNamespace(java.lang.String) ,public boolean isSupported() ,public io.fabric8.openshift.client.dsl.OpenShiftStorageVersionMigratorApiGroupDSL kubeStorageVersionMigrator() ,public NamespacedInOutCreateable<LocalResourceAccessReview,ResourceAccessReviewResponse> localResourceAccessReviews() ,public NamespacedInOutCreateable<LocalSubjectAccessReview,SubjectAccessReviewResponse> localSubjectAccessReviews() ,public io.fabric8.openshift.client.dsl.OpenShiftMachineAPIGroupDSL machine() ,public io.fabric8.openshift.client.dsl.MachineConfigurationAPIGroupDSL machineConfigurations() ,public MixedOperation<Metal3RemediationTemplate,Metal3RemediationTemplateList,Resource<Metal3RemediationTemplate>> metal3RemediationTemplates() ,public MixedOperation<Metal3Remediation,Metal3RemediationList,Resource<Metal3Remediation>> metal3Remediations() ,public io.fabric8.openshift.client.dsl.OpenShiftMonitoringAPIGroupDSL monitoring() ,public NonNamespaceOperation<NetNamespace,NetNamespaceList,Resource<NetNamespace>> netNamespaces() ,public MixedOperation<NetworkAttachmentDefinition,NetworkAttachmentDefinitionList,Resource<NetworkAttachmentDefinition>> networkAttachmentDefinitions() ,public io.fabric8.openshift.client.NamespacedOpenShiftClientAdapter newInstance() ,public NonNamespaceOperation<OAuthAccessToken,OAuthAccessTokenList,Resource<OAuthAccessToken>> oAuthAccessTokens() ,public NonNamespaceOperation<OAuthAuthorizeToken,OAuthAuthorizeTokenList,Resource<OAuthAuthorizeToken>> oAuthAuthorizeTokens() ,public NonNamespaceOperation<OAuthClientAuthorization,OAuthClientAuthorizationList,Resource<OAuthClientAuthorization>> oAuthClientAuthorizations() ,public NonNamespaceOperation<OAuthClient,OAuthClientList,Resource<OAuthClient>> oAuthClients() ,public io.fabric8.openshift.client.dsl.OpenShiftOperatorAPIGroupDSL operator() ,public io.fabric8.openshift.client.dsl.OpenShiftOperatorHubAPIGroupDSL operatorHub() ,public MixedOperation<OperatorPKI,OperatorPKIList,Resource<OperatorPKI>> operatorPKIs() ,public NamespacedInOutCreateable<PodSecurityPolicyReview,PodSecurityPolicyReview> podSecurityPolicyReviews() ,public NamespacedInOutCreateable<PodSecurityPolicySelfSubjectReview,PodSecurityPolicySelfSubjectReview> podSecurityPolicySelfSubjectReviews() ,public NamespacedInOutCreateable<PodSecurityPolicySubjectReview,PodSecurityPolicySubjectReview> podSecurityPolicySubjectReviews() ,public MixedOperation<ProjectHelmChartRepository,ProjectHelmChartRepositoryList,Resource<ProjectHelmChartRepository>> projectHelmChartRepositories() ,public io.fabric8.openshift.client.dsl.ProjectRequestOperation projectrequests() ,public io.fabric8.openshift.client.dsl.ProjectOperation projects() ,public io.fabric8.openshift.client.dsl.OpenShiftQuotaAPIGroupDSL quotas() ,public NonNamespaceOperation<RangeAllocation,RangeAllocationList,Resource<RangeAllocation>> rangeAllocations() ,public InOutCreateable<ResourceAccessReview,ResourceAccessReviewResponse> resourceAccessReviews() ,public MixedOperation<RoleBindingRestriction,RoleBindingRestrictionList,Resource<RoleBindingRestriction>> roleBindingRestrictions() ,public MixedOperation<RoleBinding,RoleBindingList,Resource<RoleBinding>> roleBindings() ,public MixedOperation<Role,RoleList,Resource<Role>> roles() ,public MixedOperation<Route,RouteList,Resource<Route>> routes() ,public NonNamespaceOperation<SecurityContextConstraints,SecurityContextConstraintsList,Resource<SecurityContextConstraints>> securityContextConstraints() ,public NamespacedInOutCreateable<SelfSubjectRulesReview,SelfSubjectRulesReview> selfSubjectRulesReviews() ,public InOutCreateable<SubjectAccessReview,SubjectAccessReviewResponse> subjectAccessReviews() ,public NamespacedInOutCreateable<SubjectRulesReview,SubjectRulesReview> subjectRulesReviews() ,public boolean supportsOpenShiftAPIGroup(java.lang.String) ,public MixedOperation<TemplateInstance,TemplateInstanceList,Resource<TemplateInstance>> templateInstances() ,public ParameterMixedOperation<Template,TemplateList,io.fabric8.openshift.client.dsl.TemplateResource> templates() ,public io.fabric8.openshift.client.dsl.OpenShiftTunedAPIGroupDSL tuned() ,public InOutCreateable<UserIdentityMapping,UserIdentityMapping> userIdentityMappings() ,public NonNamespaceOperation<UserOAuthAccessToken,UserOAuthAccessTokenList,Resource<UserOAuthAccessToken>> userOAuthAccessTokens() ,public NonNamespaceOperation<User,UserList,Resource<User>> users() ,public io.fabric8.openshift.client.dsl.OpenShiftWhereaboutsAPIGroupDSL whereabouts() ,public FunctionCallable<io.fabric8.openshift.client.NamespacedOpenShiftClient> withRequestConfig(io.fabric8.kubernetes.client.RequestConfig) <variables>
fabric8io_kubernetes-client
kubernetes-client/openshift-client-api/src/main/java/io/fabric8/openshift/client/readiness/OpenShiftReadiness.java
OpenShiftReadinessHolder
isResourceReady
class OpenShiftReadinessHolder { public static final OpenShiftReadiness INSTANCE = new OpenShiftReadiness(); } public static OpenShiftReadiness getInstance() { return OpenShiftReadinessHolder.INSTANCE; } @Override protected boolean isReadinessApplicable(HasMetadata item) { return super.isReadinessApplicable(item) || item instanceof DeploymentConfig; } @Override protected boolean isResourceReady(HasMetadata item) {<FILL_FUNCTION_BODY>
if (item instanceof DeploymentConfig) { return isDeploymentConfigReady((DeploymentConfig) item); } return super.isResourceReady(item);
134
43
177
<methods>public non-sealed void <init>() ,public static io.fabric8.kubernetes.client.readiness.Readiness getInstance() ,public static boolean isDeploymentReady(Deployment) ,public static boolean isEndpointsReady(Endpoints) ,public static boolean isExtensionsDeploymentReady(io.fabric8.kubernetes.api.model.extensions.Deployment) ,public static boolean isNodeReady(Node) ,public static boolean isPodReady(Pod) ,public static boolean isPodSucceeded(Pod) ,public boolean isReady(io.fabric8.kubernetes.api.model.HasMetadata) ,public static boolean isReplicaSetReady(ReplicaSet) ,public static boolean isReplicationControllerReady(ReplicationController) ,public static boolean isStatefulSetReady(StatefulSet) <variables>private static final java.lang.String NODE_READY,private static final java.lang.String POD_READY,protected static final java.lang.String READINESS_APPLICABLE_RESOURCES,private static final java.lang.String TRUE,private static final Logger logger
fabric8io_kubernetes-client
kubernetes-client/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/apps/DeploymentConfigOperationsImpl.java
DeploymentConfigOperationsImpl
waitUntilDeploymentConfigPodBecomesReady
class DeploymentConfigOperationsImpl extends HasMetadataOperation<DeploymentConfig, DeploymentConfigList, DeployableScalableResource<DeploymentConfig>> implements DeployableScalableResource<DeploymentConfig> { public static final String OPENSHIFT_IO_DEPLOYMENT_CONFIG_NAME = "openshift.io/deployment-config.name"; private final PodOperationContext rollingOperationContext; public DeploymentConfigOperationsImpl(Client client) { this(new PodOperationContext(), HasMetadataOperationsImpl.defaultContext(client)); } public DeploymentConfigOperationsImpl(PodOperationContext context, OperationContext superContext) { super(superContext.withApiGroupName(APPS).withPlural("deploymentconfigs"), DeploymentConfig.class, DeploymentConfigList.class); this.rollingOperationContext = context; } @Override public DeploymentConfigOperationsImpl newInstance(OperationContext context) { return new DeploymentConfigOperationsImpl(rollingOperationContext, context); } @Override public Scale scale(Scale scaleParam) { return LegacyRollableScalableResourceOperation.scale(scaleParam, this); } @Override public DeploymentConfig deployLatest(boolean wait) { DeploymentConfigOperationsImpl deployable = this; if (wait) { deployable = this.withTimeoutInMillis(getRequestConfig().getScaleTimeout()); } return deployable.deployLatest(); } @Override public DeploymentConfig deployLatest() { Long currentVersion = getItemOrRequireFromServer().getStatus().getLatestVersion(); if (currentVersion == null) { currentVersion = 1L; } final Long latestVersion = currentVersion + 1; DeploymentConfig deployment = accept(d -> d.getStatus().setLatestVersion(latestVersion)); if (context.getTimeout() > 0) { waitUntilScaled(deployment.getSpec().getReplicas()); deployment = getItemOrRequireFromServer(); } return deployment; } @Override public String getLog() { return getLog(rollingOperationContext.isPrettyOutput()); } @Override public String getLog(boolean isPretty) { return new DeploymentConfigOperationsImpl(rollingOperationContext.withPrettyOutput(isPretty), context) .doGetLog(String.class); } private <T> T doGetLog(Class<T> type) { try { URL url = getResourceLogUrl(false); return handleRawGet(url, type); } catch (Throwable t) { throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t); } } /** * Returns an unclosed Reader. It's the caller responsibility to close it. * * @return Reader */ @Override public Reader getLogReader() { return doGetLog(Reader.class); } /** * Returns an unclosed InputStream. It's the caller responsibility to close it. * * @return InputStream */ @Override public InputStream getLogInputStream() { return doGetLog(InputStream.class); } @Override public LogWatch watchLog() { return watchLog(null); } @Override public LogWatch watchLog(OutputStream out) { try { // In case of DeploymentConfig we directly get logs at DeploymentConfig Url, but we need to wait for Pods waitUntilDeploymentConfigPodBecomesReady(get()); URL url = getResourceLogUrl(true); final LogWatchCallback callback = new LogWatchCallback(out, context); return callback.callAndWait(this.httpClient, url); } catch (Throwable t) { throw KubernetesClientException.launderThrowable(forOperationType("watchLog"), t); } } private URL getResourceLogUrl(Boolean follow) throws MalformedURLException { if (Boolean.TRUE.equals(follow)) { return new URL(URLUtils.join(getResourceUrl().toString(), rollingOperationContext.getLogParameters() + "&follow=true")); } else { return new URL( URLUtils.join(getResourceUrl().toString(), rollingOperationContext.getLogParameters())); } } @Override public Loggable withLogWaitTimeout(Integer logWaitTimeout) { return withReadyWaitTimeout(logWaitTimeout); } @Override public Loggable withReadyWaitTimeout(Integer timeout) { return new DeploymentConfigOperationsImpl(rollingOperationContext.withReadyWaitTimeout(timeout), context); } private void waitUntilDeploymentConfigPodBecomesReady(DeploymentConfig deploymentConfig) {<FILL_FUNCTION_BODY>} private static void waitForBuildPodToBecomeReady(List<PodResource> podOps, Integer podLogWaitTimeout) { for (PodResource podOp : podOps) { PodOperationUtil.waitUntilReadyOrTerminal(podOp, podLogWaitTimeout); } } static Map<String, String> getDeploymentConfigPodLabels(DeploymentConfig deploymentConfig) { Map<String, String> labels = new HashMap<>(); if (deploymentConfig != null && deploymentConfig.getMetadata() != null) { labels.put(OPENSHIFT_IO_DEPLOYMENT_CONFIG_NAME, deploymentConfig.getMetadata().getName()); } return labels; } @Override public Loggable inContainer(String id) { return new DeploymentConfigOperationsImpl(rollingOperationContext.withContainerId(id), context); } @Override public TimeTailPrettyLoggable limitBytes(int limitBytes) { return new DeploymentConfigOperationsImpl(rollingOperationContext.withLimitBytes(limitBytes), context); } @Override public TimeTailPrettyLoggable terminated() { return new DeploymentConfigOperationsImpl(rollingOperationContext.withTerminatedStatus(true), context); } @Override public Loggable withPrettyOutput() { return new DeploymentConfigOperationsImpl(rollingOperationContext.withPrettyOutput(true), context); } @Override public PrettyLoggable tailingLines(int lines) { return new DeploymentConfigOperationsImpl(rollingOperationContext.withTailingLines(lines), context); } @Override public TailPrettyLoggable sinceTime(String timestamp) { return new DeploymentConfigOperationsImpl(rollingOperationContext.withSinceTimestamp(timestamp), context); } @Override public TailPrettyLoggable sinceSeconds(int seconds) { return new DeploymentConfigOperationsImpl(rollingOperationContext.withSinceSeconds(seconds), context); } @Override public BytesLimitTerminateTimeTailPrettyLoggable usingTimestamps() { return new DeploymentConfigOperationsImpl(rollingOperationContext.withTimestamps(true), context); } @Override public DeploymentConfigOperationsImpl withTimeout(long timeout, TimeUnit unit) { return new DeploymentConfigOperationsImpl(rollingOperationContext, context.withTimeout(timeout, unit)); } @Override public DeploymentConfigOperationsImpl withTimeoutInMillis(long timeoutInMillis) { return withTimeout(timeoutInMillis, TimeUnit.MILLISECONDS); } }
Integer podLogWaitTimeout = rollingOperationContext.getReadyWaitTimeout(); List<PodResource> podOps = PodOperationUtil.getPodOperationsForController(context, rollingOperationContext, deploymentConfig.getMetadata().getUid(), getDeploymentConfigPodLabels(deploymentConfig)); waitForBuildPodToBecomeReady(podOps, podLogWaitTimeout != null ? podLogWaitTimeout : PodOperationsImpl.DEFAULT_POD_READY_WAIT_TIMEOUT_MS);
1,887
127
2,014
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<DeploymentConfig>, Class<DeploymentConfigList>) ,public DeploymentConfig accept(Consumer<DeploymentConfig>) ,public DeploymentConfig edit(UnaryOperator<DeploymentConfig>) ,public transient DeploymentConfig edit(Visitor[]) ,public DeploymentConfig editStatus(UnaryOperator<DeploymentConfig>) ,public HasMetadataOperation<DeploymentConfig,DeploymentConfigList,DeployableScalableResource<DeploymentConfig>> newInstance(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public DeploymentConfig patch() ,public DeploymentConfig patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public DeploymentConfig patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, DeploymentConfig) ,public DeploymentConfig patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public DeploymentConfig patchStatus() ,public DeploymentConfig patchStatus(DeploymentConfig) ,public DeploymentConfig replace() ,public DeploymentConfig replaceStatus() ,public DeploymentConfig scale(int) ,public DeploymentConfig scale(int, boolean) ,public Scale scale(Scale) ,public DeploymentConfig update() ,public DeploymentConfig updateStatus() <variables>public static final long DEFAULT_GRACE_PERIOD_IN_SECONDS,public static final io.fabric8.kubernetes.api.model.DeletionPropagation DEFAULT_PROPAGATION_POLICY,private static final Logger LOGGER,private static final java.lang.String PATCH_OPERATION,private static final java.lang.String REPLACE_OPERATION,private static final java.lang.String UPDATE_OPERATION
fabric8io_kubernetes-client
kubernetes-client/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/authorization/RoleBindingOperationsImpl.java
RoleBindingOperationsImpl
enrichFromUsersAndGroups
class RoleBindingOperationsImpl extends HasMetadataOperation<RoleBinding, RoleBindingList, Resource<RoleBinding>> { public static final String SERVICE_ACCOUNT = "ServiceAccount"; public static final String USER = "User"; public static final String GROUP = "Group"; public RoleBindingOperationsImpl(Client client) { this(HasMetadataOperationsImpl.defaultContext(client)); } public RoleBindingOperationsImpl(OperationContext context) { super(context.withApiGroupName(AUTHORIZATION) .withPlural("rolebindings"), RoleBinding.class, RoleBindingList.class); } @Override public RoleBindingOperationsImpl newInstance(OperationContext context) { return new RoleBindingOperationsImpl(context); } @Override protected RoleBinding handleCreate(RoleBinding resource) throws InterruptedException, IOException { return super.handleCreate(enrichRoleBinding(resource)); } @Override protected RoleBinding modifyItemForReplaceOrPatch(Supplier<RoleBinding> current, RoleBinding binding) { return enrichRoleBinding(binding); } private RoleBinding enrichRoleBinding(RoleBinding binding) { RoleBindingBuilder builder = new RoleBindingBuilder(binding); if ((binding.getUserNames() != null && !binding.getUserNames().isEmpty()) || (binding.getGroupNames() != null && !binding.getGroupNames().isEmpty())) { enrichFromUsersAndGroups(builder, binding.getUserNames(), binding.getGroupNames()); } else { enrichFromSubjects(builder, binding.getSubjects()); enrichSubjectsNamespace(builder); } return builder.build(); } private void enrichSubjectsNamespace(RoleBindingBuilder builder) { builder.accept(new TypedVisitor<ObjectReferenceBuilder>() { @Override public void visit(ObjectReferenceBuilder o) { if (o.getKind() != null && o.getKind().equals(SERVICE_ACCOUNT) && (o.getNamespace() == null || o.getNamespace().isEmpty())) { o.withNamespace(getNamespace()); } } }); } private void enrichFromUsersAndGroups(RoleBindingBuilder builder, List<String> userNames, List<String> groupNames) {<FILL_FUNCTION_BODY>} private void enrichFromSubjects(RoleBindingBuilder builder, List<ObjectReference> subjects) { for (ObjectReference ref : subjects) { switch (ref.getKind()) { case USER: builder.addToUserNames(ref.getName()); break; case SERVICE_ACCOUNT: String namespace = ref.getNamespace(); if (namespace == null || namespace.isEmpty()) { namespace = getNamespace(); } builder.addToUserNames("system:serviceaccount:" + namespace + ":" + ref.getName()); break; case GROUP: builder.addToGroupNames(ref.getName()); break; } } } }
builder.withSubjects(); if (userNames != null) { for (String userName : userNames) { if (userName.startsWith("system:serviceaccount:")) { String[] splitUserName = userName.split(":"); if (splitUserName.length == 4) { builder.addNewSubject().withKind(SERVICE_ACCOUNT).withNamespace(splitUserName[2]).withName(splitUserName[3]) .endSubject(); continue; } } builder.addNewSubject().withKind(USER).withName(userName).endSubject(); } } if (groupNames != null) { for (String groupName : groupNames) { builder.addNewSubject().withKind(GROUP).withName(groupName).endSubject(); } }
769
214
983
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<RoleBinding>, Class<RoleBindingList>) ,public RoleBinding accept(Consumer<RoleBinding>) ,public RoleBinding edit(UnaryOperator<RoleBinding>) ,public transient RoleBinding edit(Visitor[]) ,public RoleBinding editStatus(UnaryOperator<RoleBinding>) ,public HasMetadataOperation<RoleBinding,RoleBindingList,Resource<RoleBinding>> newInstance(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public RoleBinding patch() ,public RoleBinding patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public RoleBinding patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, RoleBinding) ,public RoleBinding patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public RoleBinding patchStatus() ,public RoleBinding patchStatus(RoleBinding) ,public RoleBinding replace() ,public RoleBinding replaceStatus() ,public RoleBinding scale(int) ,public RoleBinding scale(int, boolean) ,public Scale scale(Scale) ,public RoleBinding update() ,public RoleBinding updateStatus() <variables>public static final long DEFAULT_GRACE_PERIOD_IN_SECONDS,public static final io.fabric8.kubernetes.api.model.DeletionPropagation DEFAULT_PROPAGATION_POLICY,private static final Logger LOGGER,private static final java.lang.String PATCH_OPERATION,private static final java.lang.String REPLACE_OPERATION,private static final java.lang.String UPDATE_OPERATION
fabric8io_kubernetes-client
kubernetes-client/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/build/BuildOperationsImpl.java
BuildOperationsImpl
watchLog
class BuildOperationsImpl extends HasMetadataOperation<Build, BuildList, BuildResource> implements BuildResource { public static final String OPENSHIFT_IO_BUILD_NAME = "openshift.io/build.name"; private Integer version; private final PodOperationContext operationContext; public BuildOperationsImpl(Client client) { this(new PodOperationContext(), HasMetadataOperationsImpl.defaultContext(client), null); } public BuildOperationsImpl(PodOperationContext context, OperationContext superContext, Integer version) { super(superContext.withApiGroupName(BUILD) .withPlural("builds"), Build.class, BuildList.class); this.operationContext = context; this.context = superContext; this.version = version; } @Override public BuildOperationsImpl newInstance(OperationContext context) { return new BuildOperationsImpl(operationContext, context, version); } PodOperationContext getContext() { return operationContext; } protected String getLogParameters() { String params = operationContext.getLogParameters(); if (version != null) { params += ("&version=" + version); } return params; } protected <T> T doGetLog(Class<T> type) { try { URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters())); return handleRawGet(url, type); } catch (IOException t) { throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t); } } @Override public String getLog() { return doGetLog(String.class); } @Override public String getLog(boolean isPretty) { return new BuildOperationsImpl(getContext().withPrettyOutput(isPretty), context, version).getLog(); } /** * Returns an unclosed Reader. It's the caller responsibility to close it. * * @return Reader */ @Override public Reader getLogReader() { return doGetLog(Reader.class); } /** * Returns an unclosed InputStream. It's the caller responsibility to close it. * * @return InputStream */ @Override public InputStream getLogInputStream() { return doGetLog(InputStream.class); } @Override public LogWatch watchLog() { return watchLog(null); } @Override public LogWatch watchLog(OutputStream out) {<FILL_FUNCTION_BODY>} @Override public Loggable withLogWaitTimeout(Integer logWaitTimeout) { return withReadyWaitTimeout(logWaitTimeout); } @Override public Loggable withReadyWaitTimeout(Integer timeout) { return new BuildOperationsImpl(getContext().withReadyWaitTimeout(timeout), context, version); } @Override public Loggable withPrettyOutput() { return new BuildOperationsImpl(getContext().withPrettyOutput(true), context, version); } @Override public PrettyLoggable tailingLines(int tailingLines) { return new BuildOperationsImpl(getContext().withTailingLines(tailingLines), context, version); } @Override public TimeTailPrettyLoggable terminated() { return new BuildOperationsImpl(getContext().withTerminatedStatus(true), context, version); } @Override public TailPrettyLoggable sinceTime(String sinceTimestamp) { return new BuildOperationsImpl(getContext().withSinceTimestamp(sinceTimestamp), context, version); } @Override public TailPrettyLoggable sinceSeconds(int sinceSeconds) { return new BuildOperationsImpl(getContext().withSinceSeconds(sinceSeconds), context, version); } @Override public BytesLimitTerminateTimeTailPrettyLoggable limitBytes(int limitBytes) { return new BuildOperationsImpl(getContext().withLimitBytes(limitBytes), context, version); } @Override public TimestampBytesLimitTerminateTimeTailPrettyLoggable withVersion(Integer version) { return new BuildOperationsImpl(getContext(), context, version); } @Override public BytesLimitTerminateTimeTailPrettyLoggable usingTimestamps() { return new BuildOperationsImpl(getContext().withTimestamps(true), context, version); } private void waitUntilBuildPodBecomesReady(Build build) { List<PodResource> podOps = PodOperationUtil.getPodOperationsForController(context, operationContext, build.getMetadata().getUid(), getBuildPodLabels(build)); waitForBuildPodToBecomeReady(podOps, operationContext.getReadyWaitTimeout() != null ? operationContext.getReadyWaitTimeout() : PodOperationsImpl.DEFAULT_POD_READY_WAIT_TIMEOUT_MS); } private static void waitForBuildPodToBecomeReady(List<PodResource> podOps, Integer podLogWaitTimeout) { for (PodResource podOp : podOps) { PodOperationUtil.waitUntilReadyOrTerminal(podOp, podLogWaitTimeout); } } static Map<String, String> getBuildPodLabels(Build build) { Map<String, String> labels = new HashMap<>(); if (build != null && build.getMetadata() != null) { labels.put(OPENSHIFT_IO_BUILD_NAME, build.getMetadata().getName()); } return labels; } }
try { // In case of Build we directly get logs at Build Url, but we need to wait for Pods waitUntilBuildPodBecomesReady(get()); URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters() + "&follow=true")); final LogWatchCallback callback = new LogWatchCallback(out, context); return callback.callAndWait(this.httpClient, url); } catch (IOException t) { throw KubernetesClientException.launderThrowable(forOperationType("watchLog"), t); }
1,445
141
1,586
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<Build>, Class<BuildList>) ,public Build accept(Consumer<Build>) ,public Build edit(UnaryOperator<Build>) ,public transient Build edit(Visitor[]) ,public Build editStatus(UnaryOperator<Build>) ,public HasMetadataOperation<Build,BuildList,io.fabric8.openshift.client.dsl.BuildResource> newInstance(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public Build patch() ,public Build patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public Build patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, Build) ,public Build patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public Build patchStatus() ,public Build patchStatus(Build) ,public Build replace() ,public Build replaceStatus() ,public Build scale(int) ,public Build scale(int, boolean) ,public Scale scale(Scale) ,public Build update() ,public Build updateStatus() <variables>public static final long DEFAULT_GRACE_PERIOD_IN_SECONDS,public static final io.fabric8.kubernetes.api.model.DeletionPropagation DEFAULT_PROPAGATION_POLICY,private static final Logger LOGGER,private static final java.lang.String PATCH_OPERATION,private static final java.lang.String REPLACE_OPERATION,private static final java.lang.String UPDATE_OPERATION
fabric8io_kubernetes-client
kubernetes-client/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/core/TemplateOperationsImpl.java
TemplateOperationsImpl
processLocally
class TemplateOperationsImpl extends HasMetadataOperation<Template, TemplateList, TemplateResource> implements TemplateResource, ParameterMixedOperation<Template, TemplateList, TemplateResource> { private static final Logger logger = LoggerFactory.getLogger(TemplateOperationsImpl.class); private static final String EXPRESSION = "expression"; private static final TypeReference<HashMap<String, String>> MAPS_REFERENCE = new TypeReference<HashMap<String, String>>() { }; private final Map<String, String> parameters; public TemplateOperationsImpl(Client client) { this(HasMetadataOperationsImpl.defaultContext(client), null); } public TemplateOperationsImpl(OperationContext context, Map<String, String> parameters) { super(context.withApiGroupName(TEMPLATE) .withPlural("templates"), Template.class, TemplateList.class); this.parameters = parameters; } @Override public TemplateOperationsImpl newInstance(OperationContext context) { return new TemplateOperationsImpl(context, parameters); } public TemplateOperationsImpl newInstance(OperationContext context, Map<String, String> parameters) { return new TemplateOperationsImpl(context, parameters == null ? null : new LinkedHashMap<>(parameters)); } @Override public KubernetesList process(File f) { try (FileInputStream is = new FileInputStream(f)) { return process(is); } catch (IOException e) { throw KubernetesClientException.launderThrowable(forOperationType("process"), e); } } @Override public KubernetesList process(InputStream is) { return process(getKubernetesSerialization().unmarshal(is, MAPS_REFERENCE)); } @Override public KubernetesList process(Map<String, String> valuesMap) { Template t = get(); try { List<Parameter> parameters = t.getParameters(); if (parameters != null) { for (Parameter p : parameters) { String v = valuesMap.get(p.getName()); if (v != null) { p.setGenerate(null); p.setValue(v); } } } HttpRequest.Builder requestBuilder = this.httpClient.newHttpRequestBuilder() .post(JSON, getKubernetesSerialization().asJson(t)) .url(getProcessUrl()); t = handleResponse(requestBuilder); KubernetesList l = new KubernetesList(); l.setItems(t.getObjects()); return l; } catch (Exception e) { throw KubernetesClientException.launderThrowable(forOperationType("process"), e); } } @Override public KubernetesList process(ParameterValue... values) { Map<String, String> valuesMap = new HashMap<>(values.length); for (ParameterValue pv : values) { valuesMap.put(pv.getName(), pv.getValue()); } return process(valuesMap); } @Override public KubernetesList processLocally(File f) { try (FileInputStream is = new FileInputStream(f)) { return processLocally(is); } catch (IOException e) { throw KubernetesClientException.launderThrowable(forOperationType("processLocally"), e); } } @Override public KubernetesList processLocally(InputStream is) { return processLocally(getKubernetesSerialization().unmarshal(is, MAPS_REFERENCE)); } @Override public KubernetesList processLocally(ParameterValue... values) {<FILL_FUNCTION_BODY>} @Override public TemplateOperationsImpl withParameters(Map<String, String> parameters) { return newInstance(context, parameters); } @Override public KubernetesList processLocally(Map<String, String> valuesMap) { Template t = processParameters(getItemOrRequireFromServer()); List<Parameter> parameters = t.getParameters(); KubernetesList list = new KubernetesListBuilder() .withItems(t.getObjects()) .build(); String json = getKubernetesSerialization().asJson(list); String last = null; if (parameters != null && !parameters.isEmpty()) { while (!Objects.equals(last, json)) { last = json; for (Parameter parameter : parameters) { String parameterName = parameter.getName(); String parameterValue; if (valuesMap.containsKey(parameterName)) { parameterValue = valuesMap.get(parameterName); } else if (Utils.isNotNullOrEmpty(parameter.getValue())) { parameterValue = parameter.getValue(); } else if (EXPRESSION.equals(parameter.getGenerate())) { Generex generex = new Generex(parameter.getFrom()); parameterValue = generex.random(); } else if (parameter.getRequired() == null || !parameter.getRequired()) { parameterValue = ""; } else { throw new IllegalArgumentException("No value available for parameter name: " + parameterName); } if (parameterValue == null) { logger.debug("Parameter {} has a null value", parameterName); parameterValue = ""; } json = Utils.interpolateString(json, Collections.singletonMap(parameterName, parameterValue)); } } } return getKubernetesSerialization().unmarshal(json, KubernetesList.class); } private URL getProcessUrl() throws MalformedURLException { return getNamespacedUrl(getNamespace(), "processedtemplates"); } @Override public Template get() { return processParameters(super.get()); } private Template processParameters(Template t) { if (this.parameters != null && !this.parameters.isEmpty()) { return getKubernetesSerialization() .unmarshal(Utils.interpolateString(getKubernetesSerialization().asJson(t), this.parameters), Template.class); } return t; } @Override public TemplateResource load(InputStream is) { Template template = null; List<HasMetadata> items = this.context.getClient().adapt(KubernetesClient.class).load(is).items(); Object item = items; if (items.size() == 1) { item = items.get(0); } if (item instanceof Template) { template = (Template) item; } else { String generatedName = "template-" + Utils.randomString(5); template = new TemplateBuilder() .withNewMetadata() .withName(generatedName) .endMetadata() .withObjects(items).build(); } return resource(template); } }
Map<String, String> valuesMap = new HashMap<>(values.length); for (ParameterValue pv : values) { valuesMap.put(pv.getName(), pv.getValue()); } return processLocally(valuesMap);
1,737
65
1,802
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<Template>, Class<TemplateList>) ,public Template accept(Consumer<Template>) ,public Template edit(UnaryOperator<Template>) ,public transient Template edit(Visitor[]) ,public Template editStatus(UnaryOperator<Template>) ,public HasMetadataOperation<Template,TemplateList,io.fabric8.openshift.client.dsl.TemplateResource> newInstance(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public Template patch() ,public Template patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public Template patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, Template) ,public Template patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public Template patchStatus() ,public Template patchStatus(Template) ,public Template replace() ,public Template replaceStatus() ,public Template scale(int) ,public Template scale(int, boolean) ,public Scale scale(Scale) ,public Template update() ,public Template updateStatus() <variables>public static final long DEFAULT_GRACE_PERIOD_IN_SECONDS,public static final io.fabric8.kubernetes.api.model.DeletionPropagation DEFAULT_PROPAGATION_POLICY,private static final Logger LOGGER,private static final java.lang.String PATCH_OPERATION,private static final java.lang.String REPLACE_OPERATION,private static final java.lang.String UPDATE_OPERATION
fabric8io_kubernetes-client
kubernetes-client/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/project/ProjectOperationsImpl.java
ProjectOperationsImpl
createProjectAndRoleBindings
class ProjectOperationsImpl extends HasMetadataOperation<Project, ProjectList, Resource<Project>> implements ProjectOperation { public static final String OPENSHIFT_IO_DESCRIPTION_ANNOTATION = "openshift.io/description"; public static final String OPENSHIFT_IO_DISPLAY_NAME_ANNOTATION = "openshift.io/display-name"; public static final String OPENSHIFT_IO_REQUESTER_ANNOTATION = "openshift.io/requester"; public static final String RBAC_AUTHORIZATION_APIGROUP = "rbac.authorization.k8s.io"; public static final String CLUSTER_ROLE = "ClusterRole"; public ProjectOperationsImpl(Client client) { this(HasMetadataOperationsImpl.defaultContext(client)); } public ProjectOperationsImpl(OperationContext context) { super(context.withApiGroupName(PROJECT) .withPlural("projects"), Project.class, ProjectList.class); } @Override public ProjectOperationsImpl newInstance(OperationContext context) { return new ProjectOperationsImpl(context); } @Override public boolean isResourceNamespaced() { return false; } @Override public List<HasMetadata> createProjectAndRoleBindings(String name, String description, String displayName, String adminUser, String requestingUser) {<FILL_FUNCTION_BODY>} private Project initProject(String name, String description, String displayName, String requestingUser) { return new ProjectBuilder() .withNewMetadata() .addToAnnotations(OPENSHIFT_IO_DESCRIPTION_ANNOTATION, description) .addToAnnotations(OPENSHIFT_IO_DISPLAY_NAME_ANNOTATION, displayName) .addToAnnotations(OPENSHIFT_IO_REQUESTER_ANNOTATION, requestingUser) .withName(name) .endMetadata() .build(); } private List<HasMetadata> initRoleBindings(String name, String adminUser) { RoleBinding roleBindingPuller = new RoleBindingBuilder() .withNewMetadata() .addToAnnotations(OPENSHIFT_IO_DESCRIPTION_ANNOTATION, "Allows all pods in this namespace to pull images from this namespace. It is auto-managed by a controller; remove subjects to disable.") .withName("system:image-pullers") .withNamespace(name) .endMetadata() .withNewRoleRef() .withApiGroup(RBAC_AUTHORIZATION_APIGROUP) .withKind(CLUSTER_ROLE) .withName("system:image-puller") .endRoleRef() .addNewSubject() .withApiGroup(RBAC_AUTHORIZATION_APIGROUP) .withKind("Group") .withName("system:serviceaccounts:" + name) .endSubject() .build(); RoleBinding roleBindingBuilder = new RoleBindingBuilder() .withNewMetadata() .addToAnnotations(OPENSHIFT_IO_DESCRIPTION_ANNOTATION, "Allows builds in this namespace to push images to" + "this namespace. It is auto-managed by a controller; remove subjects to disable.") .withName("system:image-builders") .withNamespace(name) .endMetadata() .withNewRoleRef() .withApiGroup(RBAC_AUTHORIZATION_APIGROUP) .withKind(CLUSTER_ROLE) .withName("system:image-builder") .endRoleRef() .addNewSubject() .withKind("ServiceAccount") .withName("builder") .withNamespace(name) .endSubject() .build(); RoleBinding roleBindingDeployer = new RoleBindingBuilder() .withNewMetadata() .addToAnnotations(OPENSHIFT_IO_DESCRIPTION_ANNOTATION, " Allows deploymentconfigs in this namespace to rollout" + " pods in this namespace. It is auto-managed by a controller; remove subjects" + " to disable.") .withName("system:deployers") .withNamespace(name) .endMetadata() .withNewRoleRef() .withApiGroup(RBAC_AUTHORIZATION_APIGROUP) .withKind(CLUSTER_ROLE) .withName("system:deployer") .endRoleRef() .addNewSubject() .withKind("ServiceAccount") .withName("deployer") .withNamespace(name) .endSubject() .build(); RoleBinding roleBindingAdmin = new RoleBindingBuilder() .withNewMetadata() .withName("admin") .withNamespace(name) .endMetadata() .withNewRoleRef() .withApiGroup(RBAC_AUTHORIZATION_APIGROUP) .withKind(CLUSTER_ROLE) .withName("admin") .endRoleRef() .addNewSubject() .withApiGroup(RBAC_AUTHORIZATION_APIGROUP) .withKind("User") .withName(adminUser) .endSubject() .build(); List<HasMetadata> resources = new ArrayList<>(); resources.add(roleBindingPuller); resources.add(roleBindingBuilder); resources.add(roleBindingDeployer); resources.add(roleBindingAdmin); return resources; } }
List<HasMetadata> result = new ArrayList<>(); Project project = initProject(name, description, displayName, requestingUser); List<HasMetadata> projectRoleBindings = initRoleBindings(name, adminUser); // Create Project result.add(create(project)); // Create Role Bindings NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl listOp = new NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl( context.withItem(projectRoleBindings)); result.addAll(listOp.createOrReplace()); return result;
1,425
154
1,579
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<Project>, Class<ProjectList>) ,public Project accept(Consumer<Project>) ,public Project edit(UnaryOperator<Project>) ,public transient Project edit(Visitor[]) ,public Project editStatus(UnaryOperator<Project>) ,public HasMetadataOperation<Project,ProjectList,Resource<Project>> newInstance(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public Project patch() ,public Project patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public Project patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, Project) ,public Project patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public Project patchStatus() ,public Project patchStatus(Project) ,public Project replace() ,public Project replaceStatus() ,public Project scale(int) ,public Project scale(int, boolean) ,public Scale scale(Scale) ,public Project update() ,public Project updateStatus() <variables>public static final long DEFAULT_GRACE_PERIOD_IN_SECONDS,public static final io.fabric8.kubernetes.api.model.DeletionPropagation DEFAULT_PROPAGATION_POLICY,private static final Logger LOGGER,private static final java.lang.String PATCH_OPERATION,private static final java.lang.String REPLACE_OPERATION,private static final java.lang.String UPDATE_OPERATION
fabric8io_kubernetes-client
kubernetes-client/openshift-client/src/main/java/io/fabric8/openshift/client/impl/OpenShiftExtensionAdapter.java
OpenShiftExtensionAdapter
registerClients
class OpenShiftExtensionAdapter implements ExtensionAdapter<OpenShiftClient>, InternalExtensionAdapter { @Override public Class<OpenShiftClient> getExtensionType() { return OpenShiftClient.class; } @Override public OpenShiftClient adapt(Client client) { return new OpenShiftClientImpl(client); } @Override public void registerHandlers(Handlers handlers) { handlers.register(BuildConfig.class, BuildConfigOperationsImpl::new); handlers.register(Build.class, BuildOperationsImpl::new); handlers.register(DeploymentConfig.class, DeploymentConfigOperationsImpl::new); handlers.register(RoleBinding.class, RoleBindingOperationsImpl::new); handlers.register(Template.class, TemplateOperationsImpl::new); handlers.register(Project.class, ProjectOperationsImpl::new); } @Override public void registerClients(ClientFactory factory) {<FILL_FUNCTION_BODY>} }
factory.register(OpenShiftConfigAPIGroupDSL.class, new OpenShiftConfigAPIGroupClient()); factory.register(OpenShiftClusterAutoscalingAPIGroupDSL.class, new OpenShiftClusterAutoscalingAPIGroupClient()); factory.register(OpenShiftHiveAPIGroupDSL.class, new OpenShiftHiveAPIGroupClient()); factory.register(V1beta1ClusterAutoscalingAPIGroupDSL.class, new V1beta1OpenShiftClusterAutoscalingAPIGroupClient()); factory.register(V1ClusterAutoscalingAPIGroupDSL.class, new V1OpenShiftClusterAutoscalingAPIGroupClient()); factory.register(OpenShiftConsoleAPIGroupDSL.class, new OpenShiftConsoleAPIGroupClient()); factory.register(OpenShiftOperatorAPIGroupDSL.class, new OpenShiftOperatorAPIGroupClient()); factory.register(OpenShiftOperatorHubAPIGroupDSL.class, new OpenShiftOperatorHubAPIGroupClient()); factory.register(MachineConfigurationAPIGroupDSL.class, new OpenShiftMachineConfigurationAPIGroupClient()); factory.register(OpenShiftMachineAPIGroupDSL.class, new OpenShiftMachineAPIGroupClient()); factory.register(OpenShiftMonitoringAPIGroupDSL.class, new OpenShiftMonitoringAPIGroupClient()); factory.register(OpenShiftTunedAPIGroupDSL.class, new OpenShiftTunedAPIGroupClient()); factory.register(OpenShiftQuotaAPIGroupDSL.class, new OpenShiftQuotaAPIGroupClient()); factory.register(OpenShiftWhereaboutsAPIGroupDSL.class, new OpenShiftWhereaboutsAPIGroupClient()); factory.register(OpenShiftStorageVersionMigratorApiGroupDSL.class, new OpenShiftStorageVersionMigratorApiGroupClient());
254
449
703
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/openshift-client/src/main/java/io/fabric8/openshift/client/impl/URLFromOpenshiftRouteImpl.java
URLFromOpenshiftRouteImpl
getURL
class URLFromOpenshiftRouteImpl implements ServiceToURLProvider { public static final Logger logger = LoggerFactory.getLogger(URLFromOpenshiftRouteImpl.class); @Override public String getURL(Service service, String portName, String namespace, KubernetesClient client) {<FILL_FUNCTION_BODY>} @Override public int getPriority() { return ServiceToUrlImplPriority.FOURTH.getValue(); } }
String serviceName = service.getMetadata().getName(); ServicePort port = URLFromServiceUtil.getServicePortByName(service, portName); if (port != null && port.getName() != null && client.isAdaptable(OpenShiftClient.class)) { try { String serviceProtocol = port.getProtocol(); OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class); Route route = openShiftClient.routes().inNamespace(namespace).withName(service.getMetadata().getName()).get(); if (route != null) { return (serviceProtocol + "://" + route.getSpec().getHost()).toLowerCase(Locale.ROOT); } } catch (KubernetesClientException e) { if (e.getCode() == HttpURLConnection.HTTP_FORBIDDEN) { logger.warn("Could not lookup route:{} in namespace:{}, due to:{} ", serviceName, namespace, e.getMessage()); } } } return null;
118
255
373
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptor.java
OpenShiftOAuthInterceptor
authorize
class OpenShiftOAuthInterceptor extends TokenRefreshInterceptor { private static final String AUTHORIZATION = "Authorization"; private static final String LOCATION = "Location"; private static final String AUTHORIZATION_SERVER_PATH = ".well-known/oauth-authorization-server"; private static final String AUTHORIZE_QUERY = "?response_type=token&client_id=openshift-challenging-client"; private static final String BEFORE_TOKEN = "access_token="; private static final String AFTER_TOKEN = "&expires"; private static final Set<String> RETRIABLE_RESOURCES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( HasMetadata.getPlural(LocalSubjectAccessReview.class), HasMetadata.getPlural(LocalResourceAccessReview.class), HasMetadata.getPlural(ResourceAccessReview.class), HasMetadata.getPlural(SelfSubjectRulesReview.class), HasMetadata.getPlural(SubjectRulesReview.class), HasMetadata.getPlural(SubjectAccessReview.class), HasMetadata.getPlural(SelfSubjectAccessReview.class)))); public OpenShiftOAuthInterceptor(HttpClient client, Config config) { super(config, Instant.now(), newestConfig -> authorize(config, client).thenApply(token -> persistNewOAuthTokenIntoKubeConfig(config, token))); } @Override protected boolean useBasicAuth() { return false; // openshift does not support the basic auth header } @Override protected boolean useRemoteRefresh(Config newestConfig) { return isBasicAuth(); // if we have both username, and password, try to refresh } private static CompletableFuture<String> authorize(Config config, HttpClient client) {<FILL_FUNCTION_BODY>} @Override protected boolean shouldFail(HttpResponse<?> response) { HttpRequest request = response.request(); String url = request.uri().toString(); String method = request.method(); // always retry in case of authorization endpoints; since they also return 200 when no // authorization header is provided if (method.equals("POST") && RETRIABLE_RESOURCES.stream().anyMatch(url::endsWith)) { return false; } return response.code() != HTTP_UNAUTHORIZED; } private static String persistNewOAuthTokenIntoKubeConfig(Config config, String token) { if (token != null) { OpenIDConnectionUtils.persistOAuthToken(config, null, token); } return token; } }
HttpClient.DerivedClientBuilder builder = client.newBuilder(); builder.addOrReplaceInterceptor(TokenRefreshInterceptor.NAME, null); HttpClient clone = builder.build(); URL url; try { url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZATION_SERVER_PATH)); } catch (MalformedURLException e) { throw KubernetesClientException.launderThrowable(e); } CompletableFuture<HttpResponse<String>> responseFuture = clone.sendAsync(clone.newHttpRequestBuilder().url(url).build(), String.class); return responseFuture.thenCompose(response -> { if (!response.isSuccessful() || response.body() == null) { throw new KubernetesClientException("Unexpected response (" + response.code() + " " + response.message() + ")"); } String body = response.body(); try { Map<String, Object> jsonResponse = Serialization.unmarshal(body, Map.class); String authorizationServer = String.valueOf(jsonResponse.get("authorization_endpoint")); URL authorizeQuery = new URL(authorizationServer + AUTHORIZE_QUERY); String credential = HttpClientUtils.basicCredentials(config.getUsername(), config.getPassword()); return clone.sendAsync(client.newHttpRequestBuilder().url(authorizeQuery).setHeader(AUTHORIZATION, credential).build(), String.class); } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } }).thenApply(response -> { HttpResponse<?> responseOrPrevious = response.previousResponse().isPresent() ? response.previousResponse().get() : response; List<String> location = responseOrPrevious.headers(LOCATION); String token = !location.isEmpty() ? location.get(0) : null; if (token == null || token.isEmpty()) { throw new KubernetesClientException("Unexpected response (" + responseOrPrevious.code() + " " + responseOrPrevious.message() + "), to the authorization request. Missing header:[" + LOCATION + "]. More than likely the username / password are not correct."); } token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length()); token = token.substring(0, token.indexOf(AFTER_TOKEN)); return token; });
691
634
1,325
<methods>public void <init>(io.fabric8.kubernetes.client.Config, io.fabric8.kubernetes.client.http.HttpClient.Factory, java.time.Instant) ,public void <init>(io.fabric8.kubernetes.client.Config, java.time.Instant, Function<io.fabric8.kubernetes.client.Config,CompletableFuture<java.lang.String>>) ,public CompletableFuture<java.lang.Boolean> afterFailure(io.fabric8.kubernetes.client.http.BasicBuilder, HttpResponse<?>, io.fabric8.kubernetes.client.http.Interceptor.RequestTags) ,public void before(io.fabric8.kubernetes.client.http.BasicBuilder, io.fabric8.kubernetes.client.http.HttpRequest, io.fabric8.kubernetes.client.http.Interceptor.RequestTags) <variables>public static final java.lang.String AUTHORIZATION,public static final java.lang.String NAME,private static final int REFRESH_INTERVAL_MINUTE,protected final non-sealed io.fabric8.kubernetes.client.Config config,private volatile java.time.Instant latestRefreshTimestamp,private final non-sealed Function<io.fabric8.kubernetes.client.Config,CompletableFuture<java.lang.String>> remoteRefresh
fabric8io_kubernetes-client
kubernetes-client/openshift-client/src/main/java/io/fabric8/openshift/client/osgi/ManagedOpenShiftClient.java
ManagedOpenShiftClient
activate
class ManagedOpenShiftClient extends NamespacedOpenShiftClientAdapter { @Activate public void activate(Map<String, Object> properties) {<FILL_FUNCTION_BODY>} @Deactivate public void deactivate() { getClient().close(); } }
final OpenShiftConfigBuilder builder = new OpenShiftConfigBuilder(); if (properties.containsKey(KUBERNETES_MASTER_SYSTEM_PROPERTY)) { builder.withMasterUrl((String) properties.get(KUBERNETES_MASTER_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_API_VERSION_SYSTEM_PROPERTY)) { builder.withApiVersion((String) properties.get(KUBERNETES_API_VERSION_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_NAMESPACE_SYSTEM_PROPERTY)) { builder.withNamespace((String) properties.get(KUBERNETES_NAMESPACE_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_CA_CERTIFICATE_FILE_SYSTEM_PROPERTY)) { builder.withCaCertFile((String) properties.get(KUBERNETES_CA_CERTIFICATE_FILE_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_CA_CERTIFICATE_DATA_SYSTEM_PROPERTY)) { builder.withCaCertData((String) properties.get(KUBERNETES_CA_CERTIFICATE_DATA_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_CLIENT_CERTIFICATE_FILE_SYSTEM_PROPERTY)) { builder.withClientCertFile((String) properties.get(KUBERNETES_CLIENT_CERTIFICATE_FILE_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_CLIENT_CERTIFICATE_DATA_SYSTEM_PROPERTY)) { builder.withClientCertData((String) properties.get(KUBERNETES_CLIENT_CERTIFICATE_DATA_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_CLIENT_KEY_FILE_SYSTEM_PROPERTY)) { builder.withClientKeyFile((String) properties.get(KUBERNETES_CLIENT_KEY_FILE_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_CLIENT_KEY_DATA_SYSTEM_PROPERTY)) { builder.withClientKeyData((String) properties.get(KUBERNETES_CLIENT_KEY_DATA_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_CLIENT_KEY_ALGO_SYSTEM_PROPERTY)) { builder.withClientKeyAlgo((String) properties.get(KUBERNETES_CLIENT_KEY_ALGO_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_CLIENT_KEY_PASSPHRASE_SYSTEM_PROPERTY)) { builder.withClientKeyPassphrase((String) properties.get(KUBERNETES_CLIENT_KEY_PASSPHRASE_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_AUTH_BASIC_USERNAME_SYSTEM_PROPERTY)) { builder.withUsername((String) properties.get(KUBERNETES_AUTH_BASIC_USERNAME_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_AUTH_BASIC_PASSWORD_SYSTEM_PROPERTY)) { builder.withPassword((String) properties.get(KUBERNETES_AUTH_BASIC_PASSWORD_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_OAUTH_TOKEN_SYSTEM_PROPERTY)) { builder.withOauthToken((String) properties.get(KUBERNETES_OAUTH_TOKEN_SYSTEM_PROPERTY)); } if (properties.containsKey(KUBERNETES_WATCH_RECONNECT_INTERVAL_SYSTEM_PROPERTY)) { builder.withWatchReconnectInterval( Integer.parseInt((String) properties.get(KUBERNETES_WATCH_RECONNECT_INTERVAL_SYSTEM_PROPERTY))); } if (properties.containsKey(KUBERNETES_WATCH_RECONNECT_LIMIT_SYSTEM_PROPERTY)) { builder .withWatchReconnectLimit(Integer.parseInt((String) properties.get(KUBERNETES_WATCH_RECONNECT_LIMIT_SYSTEM_PROPERTY))); } if (properties.containsKey(KUBERNETES_REQUEST_TIMEOUT_SYSTEM_PROPERTY)) { builder.withRequestTimeout(Integer.parseInt((String) properties.get(KUBERNETES_REQUEST_TIMEOUT_SYSTEM_PROPERTY))); } if (properties.containsKey(KUBERNETES_HTTP_PROXY)) { builder.withHttpProxy((String) properties.get(KUBERNETES_HTTP_PROXY)); } if (properties.containsKey(KUBERNETES_HTTPS_PROXY)) { builder.withHttpsProxy((String) properties.get(KUBERNETES_HTTPS_PROXY)); } if (properties.containsKey(KUBERNETES_NO_PROXY)) { String noProxyProperty = (String) properties.get(KUBERNETES_NO_PROXY); builder.withNoProxy(noProxyProperty.split(",")); } if (properties.containsKey(OPENSHIFT_URL_SYSTEM_PROPERTY)) { builder.withOpenShiftUrl((String) properties.get(OPENSHIFT_URL_SYSTEM_PROPERTY)); } else { builder.withOpenShiftUrl(URLUtils.join(builder.getMasterUrl(), "oapi", builder.getOapiVersion())); } if (properties.containsKey(OPENSHIFT_BUILD_TIMEOUT_SYSTEM_PROPERTY)) { builder.withBuildTimeout(Integer.parseInt((String) properties.get(OPENSHIFT_BUILD_TIMEOUT_SYSTEM_PROPERTY))); } else { builder.withBuildTimeout(DEFAULT_BUILD_TIMEOUT); } if (properties.containsKey(KUBERNETES_WEBSOCKET_PING_INTERVAL_SYSTEM_PROPERTY)) { builder.withWebsocketPingInterval( Long.parseLong((String) properties.get(KUBERNETES_WEBSOCKET_PING_INTERVAL_SYSTEM_PROPERTY))); } NamespacedOpenShiftClient delegate = new KubernetesClientBuilder().withConfig(builder.build()).build() .adapt(NamespacedOpenShiftClient.class); this.init(delegate);
78
1,728
1,806
<methods>public void <init>() ,public NonNamespaceOperation<APIRequestCount,APIRequestCountList,Resource<APIRequestCount>> apiRequestCounts() ,public MixedOperation<BareMetalHost,BareMetalHostList,Resource<BareMetalHost>> bareMetalHosts() ,public NonNamespaceOperation<BrokerTemplateInstance,BrokerTemplateInstanceList,Resource<BrokerTemplateInstance>> brokerTemplateInstances() ,public MixedOperation<BuildConfig,BuildConfigList,BuildConfigResource<BuildConfig,java.lang.Void,Build>> buildConfigs() ,public MixedOperation<Build,BuildList,io.fabric8.openshift.client.dsl.BuildResource> builds() ,public io.fabric8.openshift.client.dsl.OpenShiftClusterAutoscalingAPIGroupDSL clusterAutoscaling() ,public NonNamespaceOperation<ClusterNetwork,ClusterNetworkList,Resource<ClusterNetwork>> clusterNetworks() ,public MixedOperation<ClusterRoleBinding,ClusterRoleBindingList,Resource<ClusterRoleBinding>> clusterRoleBindings() ,public NonNamespaceOperation<ClusterRole,ClusterRoleList,Resource<ClusterRole>> clusterRoles() ,public NonNamespaceOperation<ComponentStatus,ComponentStatusList,Resource<ComponentStatus>> componentstatuses() ,public io.fabric8.openshift.client.dsl.OpenShiftConfigAPIGroupDSL config() ,public io.fabric8.openshift.client.dsl.OpenShiftConsoleAPIGroupDSL console() ,public MixedOperation<CredentialsRequest,CredentialsRequestList,Resource<CredentialsRequest>> credentialsRequests() ,public User currentUser() ,public MixedOperation<DeploymentConfig,DeploymentConfigList,DeployableScalableResource<DeploymentConfig>> deploymentConfigs() ,public MixedOperation<EgressNetworkPolicy,EgressNetworkPolicyList,Resource<EgressNetworkPolicy>> egressNetworkPolicies() ,public MixedOperation<EgressRouter,EgressRouterList,Resource<EgressRouter>> egressRouters() ,public io.fabric8.kubernetes.client.VersionInfo getOpenShiftV3Version() ,public java.lang.String getOpenShiftV4Version() ,public java.net.URL getOpenshiftUrl() ,public NonNamespaceOperation<Group,GroupList,Resource<Group>> groups() ,public NonNamespaceOperation<HelmChartRepository,HelmChartRepositoryList,Resource<HelmChartRepository>> helmChartRepositories() ,public io.fabric8.openshift.client.dsl.OpenShiftHiveAPIGroupDSL hive() ,public NonNamespaceOperation<HostSubnet,HostSubnetList,Resource<HostSubnet>> hostSubnets() ,public NonNamespaceOperation<Identity,IdentityList,Resource<Identity>> identities() ,public NonNamespaceOperation<io.fabric8.openshift.api.model.miscellaneous.imageregistry.operator.v1.Config,ConfigList,Resource<io.fabric8.openshift.api.model.miscellaneous.imageregistry.operator.v1.Config>> imageRegistryOperatorConfigs() ,public io.fabric8.openshift.client.dsl.NameableCreateOrDeleteable imageSignatures() ,public Namespaceable<Nameable<? extends Gettable<ImageStreamImage>>> imageStreamImages() ,public NamespacedInOutCreateable<ImageStreamImport,ImageStreamImport> imageStreamImports() ,public NamespacedInOutCreateable<ImageStreamMapping,ImageStreamMapping> imageStreamMappings() ,public MixedOperation<ImageStreamTag,ImageStreamTagList,Resource<ImageStreamTag>> imageStreamTags() ,public MixedOperation<ImageStream,ImageStreamList,Resource<ImageStream>> imageStreams() ,public MixedOperation<ImageTag,ImageTagList,Resource<ImageTag>> imageTags() ,public NonNamespaceOperation<Image,ImageList,Resource<Image>> images() ,public io.fabric8.openshift.client.NamespacedOpenShiftClientAdapter inAnyNamespace() ,public io.fabric8.openshift.client.NamespacedOpenShiftClientAdapter inNamespace(java.lang.String) ,public boolean isSupported() ,public io.fabric8.openshift.client.dsl.OpenShiftStorageVersionMigratorApiGroupDSL kubeStorageVersionMigrator() ,public NamespacedInOutCreateable<LocalResourceAccessReview,ResourceAccessReviewResponse> localResourceAccessReviews() ,public NamespacedInOutCreateable<LocalSubjectAccessReview,SubjectAccessReviewResponse> localSubjectAccessReviews() ,public io.fabric8.openshift.client.dsl.OpenShiftMachineAPIGroupDSL machine() ,public io.fabric8.openshift.client.dsl.MachineConfigurationAPIGroupDSL machineConfigurations() ,public MixedOperation<Metal3RemediationTemplate,Metal3RemediationTemplateList,Resource<Metal3RemediationTemplate>> metal3RemediationTemplates() ,public MixedOperation<Metal3Remediation,Metal3RemediationList,Resource<Metal3Remediation>> metal3Remediations() ,public io.fabric8.openshift.client.dsl.OpenShiftMonitoringAPIGroupDSL monitoring() ,public NonNamespaceOperation<NetNamespace,NetNamespaceList,Resource<NetNamespace>> netNamespaces() ,public MixedOperation<NetworkAttachmentDefinition,NetworkAttachmentDefinitionList,Resource<NetworkAttachmentDefinition>> networkAttachmentDefinitions() ,public io.fabric8.openshift.client.NamespacedOpenShiftClientAdapter newInstance() ,public NonNamespaceOperation<OAuthAccessToken,OAuthAccessTokenList,Resource<OAuthAccessToken>> oAuthAccessTokens() ,public NonNamespaceOperation<OAuthAuthorizeToken,OAuthAuthorizeTokenList,Resource<OAuthAuthorizeToken>> oAuthAuthorizeTokens() ,public NonNamespaceOperation<OAuthClientAuthorization,OAuthClientAuthorizationList,Resource<OAuthClientAuthorization>> oAuthClientAuthorizations() ,public NonNamespaceOperation<OAuthClient,OAuthClientList,Resource<OAuthClient>> oAuthClients() ,public io.fabric8.openshift.client.dsl.OpenShiftOperatorAPIGroupDSL operator() ,public io.fabric8.openshift.client.dsl.OpenShiftOperatorHubAPIGroupDSL operatorHub() ,public MixedOperation<OperatorPKI,OperatorPKIList,Resource<OperatorPKI>> operatorPKIs() ,public NamespacedInOutCreateable<PodSecurityPolicyReview,PodSecurityPolicyReview> podSecurityPolicyReviews() ,public NamespacedInOutCreateable<PodSecurityPolicySelfSubjectReview,PodSecurityPolicySelfSubjectReview> podSecurityPolicySelfSubjectReviews() ,public NamespacedInOutCreateable<PodSecurityPolicySubjectReview,PodSecurityPolicySubjectReview> podSecurityPolicySubjectReviews() ,public MixedOperation<ProjectHelmChartRepository,ProjectHelmChartRepositoryList,Resource<ProjectHelmChartRepository>> projectHelmChartRepositories() ,public io.fabric8.openshift.client.dsl.ProjectRequestOperation projectrequests() ,public io.fabric8.openshift.client.dsl.ProjectOperation projects() ,public io.fabric8.openshift.client.dsl.OpenShiftQuotaAPIGroupDSL quotas() ,public NonNamespaceOperation<RangeAllocation,RangeAllocationList,Resource<RangeAllocation>> rangeAllocations() ,public InOutCreateable<ResourceAccessReview,ResourceAccessReviewResponse> resourceAccessReviews() ,public MixedOperation<RoleBindingRestriction,RoleBindingRestrictionList,Resource<RoleBindingRestriction>> roleBindingRestrictions() ,public MixedOperation<RoleBinding,RoleBindingList,Resource<RoleBinding>> roleBindings() ,public MixedOperation<Role,RoleList,Resource<Role>> roles() ,public MixedOperation<Route,RouteList,Resource<Route>> routes() ,public NonNamespaceOperation<SecurityContextConstraints,SecurityContextConstraintsList,Resource<SecurityContextConstraints>> securityContextConstraints() ,public NamespacedInOutCreateable<SelfSubjectRulesReview,SelfSubjectRulesReview> selfSubjectRulesReviews() ,public InOutCreateable<SubjectAccessReview,SubjectAccessReviewResponse> subjectAccessReviews() ,public NamespacedInOutCreateable<SubjectRulesReview,SubjectRulesReview> subjectRulesReviews() ,public boolean supportsOpenShiftAPIGroup(java.lang.String) ,public MixedOperation<TemplateInstance,TemplateInstanceList,Resource<TemplateInstance>> templateInstances() ,public ParameterMixedOperation<Template,TemplateList,io.fabric8.openshift.client.dsl.TemplateResource> templates() ,public io.fabric8.openshift.client.dsl.OpenShiftTunedAPIGroupDSL tuned() ,public InOutCreateable<UserIdentityMapping,UserIdentityMapping> userIdentityMappings() ,public NonNamespaceOperation<UserOAuthAccessToken,UserOAuthAccessTokenList,Resource<UserOAuthAccessToken>> userOAuthAccessTokens() ,public NonNamespaceOperation<User,UserList,Resource<User>> users() ,public io.fabric8.openshift.client.dsl.OpenShiftWhereaboutsAPIGroupDSL whereabouts() ,public FunctionCallable<io.fabric8.openshift.client.NamespacedOpenShiftClient> withRequestConfig(io.fabric8.kubernetes.client.RequestConfig) <variables>
langchain4j_langchain4j
langchain4j/code-execution-engines/langchain4j-code-execution-engine-graalvm-polyglot/src/main/java/dev/langchain4j/code/graalvm/GraalVmJavaScriptExecutionEngine.java
GraalVmJavaScriptExecutionEngine
execute
class GraalVmJavaScriptExecutionEngine implements CodeExecutionEngine { @Override public String execute(String code) {<FILL_FUNCTION_BODY>} }
OutputStream outputStream = new ByteArrayOutputStream(); try (Context context = Context.newBuilder("js") .sandbox(CONSTRAINED) .allowHostAccess(UNTRUSTED) .out(outputStream) .err(outputStream) .build()) { Object result = context.eval("js", code).as(Object.class); return String.valueOf(result); }
44
107
151
<no_super_class>
langchain4j_langchain4j
langchain4j/code-execution-engines/langchain4j-code-execution-engine-graalvm-polyglot/src/main/java/dev/langchain4j/code/graalvm/GraalVmPythonExecutionEngine.java
GraalVmPythonExecutionEngine
execute
class GraalVmPythonExecutionEngine implements CodeExecutionEngine { @Override public String execute(String code) {<FILL_FUNCTION_BODY>} }
OutputStream outputStream = new ByteArrayOutputStream(); try (Context context = Context.newBuilder("python") .sandbox(TRUSTED) .allowHostAccess(UNTRUSTED) .out(outputStream) .err(outputStream) .build()) { Object result = context.eval("python", code).as(Object.class); return String.valueOf(result); }
43
106
149
<no_super_class>
langchain4j_langchain4j
langchain4j/document-loaders/langchain4j-document-loader-amazon-s3/src/main/java/dev/langchain4j/data/document/loader/amazon/s3/AmazonS3DocumentLoader.java
Builder
createS3Client
class Builder { private Region region = US_EAST_1; private String endpointUrl; private String profile; private boolean forcePathStyle; private AwsCredentials awsCredentials; /** * Set the AWS region. Defaults to US_EAST_1 * * @param region The AWS region. * @return The builder instance. */ public Builder region(String region) { this.region = Region.of(region); return this; } /** * Set the AWS region. Defaults to US_EAST_1 * * @param region The AWS region. * @return The builder instance. */ public Builder region(Region region) { this.region = region; return this; } /** * Specifies a custom endpoint URL to override the default service URL. * * @param endpointUrl The endpoint URL. * @return The builder instance. */ public Builder endpointUrl(String endpointUrl) { this.endpointUrl = endpointUrl; return this; } /** * Set the profile defined in AWS credentials. If not set, it will use the default profile. * * @param profile The profile defined in AWS credentials. * @return The builder instance. */ public Builder profile(String profile) { this.profile = profile; return this; } /** * Set the forcePathStyle. When enabled, it will use the path-style URL * * @param forcePathStyle The forcePathStyle. * @return The builder instance. */ public Builder forcePathStyle(boolean forcePathStyle) { this.forcePathStyle = forcePathStyle; return this; } /** * Set the AWS credentials. If not set, it will use the default credentials. * * @param awsCredentials The AWS credentials. * @return The builder instance. */ public Builder awsCredentials(AwsCredentials awsCredentials) { this.awsCredentials = awsCredentials; return this; } public AmazonS3DocumentLoader build() { AwsCredentialsProvider credentialsProvider = createCredentialsProvider(); S3Client s3Client = createS3Client(credentialsProvider); return new AmazonS3DocumentLoader(s3Client); } private AwsCredentialsProvider createCredentialsProvider() { if (!isNullOrBlank(profile)) { return ProfileCredentialsProvider.create(profile); } if (awsCredentials != null) { return awsCredentials.toCredentialsProvider(); } return DefaultCredentialsProvider.create(); } private S3Client createS3Client(AwsCredentialsProvider credentialsProvider) {<FILL_FUNCTION_BODY>} }
S3ClientBuilder s3ClientBuilder = S3Client.builder() .region(region) .forcePathStyle(forcePathStyle) .credentialsProvider(credentialsProvider); if (!isNullOrBlank(endpointUrl)) { try { s3ClientBuilder.endpointOverride(new URI(endpointUrl)); } catch (URISyntaxException e) { throw new RuntimeException(e); } } return s3ClientBuilder.build();
717
126
843
<no_super_class>
langchain4j_langchain4j
langchain4j/document-loaders/langchain4j-document-loader-amazon-s3/src/main/java/dev/langchain4j/data/document/loader/amazon/s3/AwsCredentials.java
AwsCredentials
toCredentials
class AwsCredentials { private final String accessKeyId; private final String secretAccessKey; private final String sessionToken; public AwsCredentials(String accessKeyId, String secretAccessKey) { this(accessKeyId, secretAccessKey, null); } public AwsCredentials(String accessKeyId, String secretAccessKey, String sessionToken) { this.accessKeyId = ensureNotBlank(accessKeyId, "accessKeyId"); this.secretAccessKey = ensureNotBlank(secretAccessKey, "secretAccessKey"); this.sessionToken = sessionToken; } public AwsCredentialsProvider toCredentialsProvider() { return StaticCredentialsProvider.create(toCredentials()); } private software.amazon.awssdk.auth.credentials.AwsCredentials toCredentials() {<FILL_FUNCTION_BODY>} }
if (sessionToken != null) { return AwsSessionCredentials.create(accessKeyId, secretAccessKey, sessionToken); } return AwsBasicCredentials.create(accessKeyId, secretAccessKey);
225
58
283
<no_super_class>
langchain4j_langchain4j
langchain4j/document-loaders/langchain4j-document-loader-azure-storage-blob/src/main/java/dev/langchain4j/data/document/loader/azure/storage/blob/AzureBlobStorageDocumentLoader.java
AzureBlobStorageDocumentLoader
loadDocument
class AzureBlobStorageDocumentLoader { private static final Logger log = LoggerFactory.getLogger(AzureBlobStorageDocumentLoader.class); private final BlobServiceClient blobServiceClient; public AzureBlobStorageDocumentLoader(BlobServiceClient blobServiceClient) { this.blobServiceClient = ensureNotNull(blobServiceClient, "blobServiceClient"); } public Document loadDocument(String containerName, String blobName, DocumentParser parser) {<FILL_FUNCTION_BODY>} public List<Document> loadDocuments(String containerName, DocumentParser parser) { List<Document> documents = new ArrayList<>(); blobServiceClient.getBlobContainerClient(containerName) .listBlobs() .forEach(blob -> documents.add(loadDocument(containerName, blob.getName(), parser))); return documents; } }
BlobClient blobClient = blobServiceClient.getBlobContainerClient(containerName).getBlobClient(blobName); BlobProperties properties = blobClient.getProperties(); BlobInputStream blobInputStream = blobClient.openInputStream(); AzureBlobStorageSource source = new AzureBlobStorageSource(blobInputStream, blobClient.getAccountName(), containerName, blobName, properties); return DocumentLoader.load(source, parser);
222
112
334
<no_super_class>
langchain4j_langchain4j
langchain4j/document-loaders/langchain4j-document-loader-azure-storage-blob/src/main/java/dev/langchain4j/data/document/source/azure/storage/blob/AzureBlobStorageSource.java
AzureBlobStorageSource
metadata
class AzureBlobStorageSource implements DocumentSource { public static final String SOURCE = "source"; private final InputStream inputStream; private final String accountName; private final String containerName; private final String blobName; private final BlobProperties properties; public AzureBlobStorageSource(InputStream inputStream, String containerName, String accountName, String blobName, BlobProperties properties) { this.inputStream = ensureNotNull(inputStream, "inputStream"); this.accountName = ensureNotBlank(accountName, "accountName"); this.containerName = ensureNotBlank(containerName, "containerName"); this.blobName = ensureNotBlank(blobName, "blobName"); this.properties = ensureNotNull(properties, "properties"); } @Override public InputStream inputStream() { return inputStream; } @Override public Metadata metadata() {<FILL_FUNCTION_BODY>} }
Metadata metadata = new Metadata(); metadata.add(SOURCE, format("https://%s.blob.core.windows.net/%s/%s", accountName, containerName, blobName)); metadata.add("azure_storage_blob_creation_time", properties.getCreationTime()); metadata.add("azure_storage_blob_last_modified", properties.getLastModified()); metadata.add("azure_storage_blob_content_length", String.valueOf(properties.getBlobSize())); return metadata;
243
137
380
<no_super_class>
langchain4j_langchain4j
langchain4j/document-loaders/langchain4j-document-loader-github/src/main/java/dev/langchain4j/data/document/loader/github/GitHubDocumentLoader.java
GitHubDocumentLoader
scanDirectory
class GitHubDocumentLoader { private static final Logger logger = LoggerFactory.getLogger(GitHubDocumentLoader.class); private final GitHub gitHub; public GitHubDocumentLoader(String gitHubToken, String gitHubTokenOrganization) { this(null, gitHubToken, gitHubTokenOrganization); } public GitHubDocumentLoader(String apiUrl, String gitHubToken, String gitHubTokenOrganization) { GitHubBuilder gitHubBuilder = new GitHubBuilder(); if (apiUrl != null) { gitHubBuilder.withEndpoint(apiUrl); } if (gitHubToken != null) { if (gitHubTokenOrganization == null) { gitHubBuilder.withOAuthToken(gitHubToken); } else { gitHubBuilder.withOAuthToken(gitHubToken, gitHubTokenOrganization); } } try { gitHub = gitHubBuilder.build(); } catch (IOException ioException) { throw new RuntimeException(ioException); } } public GitHubDocumentLoader() { try { gitHub = new GitHubBuilder().build(); } catch (IOException ioException) { throw new RuntimeException(ioException); } } public GitHubDocumentLoader(GitHub gitHub) { this.gitHub = gitHub; } public Document loadDocument(String owner, String repo, String branch, String path, DocumentParser parser) { GHContent content = null; try { content = gitHub .getRepository(owner + "/" + repo) .getFileContent(path, branch); } catch (IOException ioException) { throw new RuntimeException(ioException); } return fromGitHub(parser, content); } public List<Document> loadDocuments(String owner, String repo, String branch, String path, DocumentParser parser) { List<Document> documents = new ArrayList<>(); try { gitHub .getRepository(owner + "/" + repo) .getDirectoryContent(path, branch) .forEach(ghDirectoryContent -> GitHubDocumentLoader.scanDirectory(ghDirectoryContent, documents, parser)); } catch (IOException ioException) { throw new RuntimeException(ioException); } return documents; } public List<Document> loadDocuments(String owner, String repo, String branch, DocumentParser parser) { return loadDocuments(owner, repo, branch, "", parser); } private static void scanDirectory(GHContent ghContent, List<Document> documents, DocumentParser parser) {<FILL_FUNCTION_BODY>} private static Document fromGitHub(DocumentParser parser, GHContent content) { logger.info("Loading document from GitHub: {}", content.getHtmlUrl()); try { if (content.isFile()) { GitHubSource source = new GitHubSource(content); return DocumentLoader.load(source, parser); } else { throw new IllegalArgumentException("Content must be a file, and not a directory: " + content.getHtmlUrl()); } } catch (IOException ioException) { throw new RuntimeException("Failed to load document from GitHub: {}", ioException); } } public static Builder builder() { return new Builder(); } public static class Builder { private String apiUrl; private String gitHubToken; private String gitHubTokenOrganization; public Builder apiUrl(String apiUrl) { this.apiUrl = apiUrl; return this; } public Builder gitHubToken(String gitHubToken) { this.gitHubToken = gitHubToken; return this; } public Builder gitHubTokenOrganization(String gitHubTokenOrganization) { this.gitHubTokenOrganization = gitHubTokenOrganization; return this; } public GitHubDocumentLoader build() { return new GitHubDocumentLoader(apiUrl, gitHubToken, gitHubTokenOrganization); } } }
if (ghContent.isDirectory()) { try { ghContent.listDirectoryContent().forEach(ghDirectoryContent -> GitHubDocumentLoader.scanDirectory(ghDirectoryContent, documents, parser)); } catch (IOException ioException) { logger.error("Failed to read directory from GitHub: {}", ghContent.getHtmlUrl(), ioException); } } else { Document document = null; try { document = withRetry(() -> fromGitHub(parser, ghContent), 3); } catch (RuntimeException runtimeException) { logger.error("Failed to read document from GitHub: {}", ghContent.getHtmlUrl(), runtimeException); } if (document != null) { documents.add(document); } }
1,014
196
1,210
<no_super_class>
langchain4j_langchain4j
langchain4j/document-loaders/langchain4j-document-loader-github/src/main/java/dev/langchain4j/data/document/source/github/GitHubSource.java
GitHubSource
metadata
class GitHubSource implements DocumentSource { private final InputStream inputStream; private final GHContent content; public GitHubSource(GHContent content) throws IOException { this.content = ensureNotNull(content, "content"); this.inputStream = ensureNotNull(content.read(), "inputStream"); } @Override public InputStream inputStream() { return inputStream; } @Override public Metadata metadata() {<FILL_FUNCTION_BODY>} }
Metadata metadata = new Metadata(); metadata.add("github_git_url", content.getGitUrl()); try { metadata.add("github_download_url", content.getDownloadUrl()); } catch (IOException e) { // Ignore if download_url is not available } metadata.add("github_html_url", content.getHtmlUrl()); metadata.add("github_url", content.getUrl()); metadata.add("github_file_name", content.getName()); metadata.add("github_file_path", content.getPath()); metadata.add("github_file_sha", content.getSha()); metadata.add("github_file_size", Long.toString(content.getSize())); metadata.add("github_file_encoding", content.getEncoding()); return metadata;
129
205
334
<no_super_class>
langchain4j_langchain4j
langchain4j/document-loaders/langchain4j-document-loader-tencent-cos/src/main/java/dev/langchain4j/data/document/loader/tencent/cos/TencentCosDocumentLoader.java
TencentCosDocumentLoader
loadDocuments
class TencentCosDocumentLoader { private static final Logger log = LoggerFactory.getLogger(TencentCosDocumentLoader.class); private final COSClient cosClient; public TencentCosDocumentLoader(COSClient s3Client) { this.cosClient = ensureNotNull(s3Client, "cosClient"); } /** * Loads a single document from the specified COS bucket based on the specified object key. * * @param bucket COS bucket to load from. * @param key The key of the COS object which should be loaded. * @param parser The parser to be used for parsing text from the object. * @return A document containing the content of the COS object. */ public Document loadDocument(String bucket, String key, DocumentParser parser) { GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, key); COSObject cosObject = cosClient.getObject(getObjectRequest); TencentCosSource source = new TencentCosSource(cosObject.getObjectContent(), bucket, key); return DocumentLoader.load(source, parser); } /** * Loads all documents from an COS bucket. * Skips any documents that fail to load. * * @param bucket COS bucket to load from. * @param parser The parser to be used for parsing text from the object. * @return A list of documents. */ public List<Document> loadDocuments(String bucket, DocumentParser parser) { return loadDocuments(bucket, null, parser); } /** * Loads all documents from an COS bucket. * Skips any documents that fail to load. * * @param bucket COS bucket to load from. * @param prefix Only keys with the specified prefix will be loaded. * @param parser The parser to be used for parsing text from the object. * @return A list of documents. */ public List<Document> loadDocuments(String bucket, String prefix, DocumentParser parser) {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(); } public static class Builder { private Region region; private TencentCredentials tencentCredentials; /** * Set the Tencent region. * * @param region The Tencent region. * @return The builder instance. */ public Builder region(String region) { this.region = new Region(Region.formatRegion(region)); return this; } /** * Set the Tencent region. * * @param region The Tencent region. * @return The builder instance. */ public Builder region(Region region) { this.region = region; return this; } /** * Set the Tencent credentials. If not set, it will use the default credentials. * * @param tencentCredentials The Tencent credentials. * @return The builder instance. */ public Builder tencentCredentials(TencentCredentials tencentCredentials) { this.tencentCredentials = tencentCredentials; return this; } public TencentCosDocumentLoader build() { COSCredentialsProvider credentialsProvider = createCredentialsProvider(); COSClient cosClient = createCosClient(credentialsProvider); return new TencentCosDocumentLoader(cosClient); } private COSCredentialsProvider createCredentialsProvider() { if (tencentCredentials != null) { return tencentCredentials.toCredentialsProvider(); } throw new IllegalArgumentException("Tencent credentials are required."); } private COSClient createCosClient(COSCredentialsProvider cosCredentialsProvider) { ClientConfig clientConfig = new ClientConfig(region); return new COSClient(cosCredentialsProvider, clientConfig); } } }
List<Document> documents = new ArrayList<>(); ListObjectsRequest listObjectsRequest = new ListObjectsRequest() .withBucketName(ensureNotBlank(bucket, "bucket")) .withPrefix(prefix); ObjectListing objectListing = cosClient.listObjects(listObjectsRequest); List<COSObjectSummary> filteredObjects = objectListing.getObjectSummaries().stream() .filter(object -> !object.getKey().endsWith("/") && object.getSize() > 0) .collect(toList()); for (COSObjectSummary object : filteredObjects) { String key = object.getKey(); try { Document document = loadDocument(bucket, key, parser); documents.add(document); } catch (Exception e) { log.warn("Failed to load an object with key '{}' from bucket '{}', skipping it.", key, bucket, e); } } return documents;
1,004
242
1,246
<no_super_class>
langchain4j_langchain4j
langchain4j/document-loaders/langchain4j-document-loader-tencent-cos/src/main/java/dev/langchain4j/data/document/loader/tencent/cos/TencentCredentials.java
TencentCredentials
toCredentials
class TencentCredentials { private final String secretId; private final String secretKey; private final String sessionToken; public TencentCredentials(String secretId, String secretKey) { this(secretId, secretKey, null); } public TencentCredentials(String secretId, String secretKey, String sessionToken) { this.secretId = ensureNotBlank(secretId, "accessKeyId"); this.secretKey = ensureNotBlank(secretKey, "secretAccessKey"); this.sessionToken = sessionToken; } public COSCredentialsProvider toCredentialsProvider() { return new COSStaticCredentialsProvider(toCredentials()); } public COSCredentials toCredentials() {<FILL_FUNCTION_BODY>} }
if (sessionToken == null) { return new BasicCOSCredentials(secretId, secretKey); } return new BasicSessionCredentials(secretId, secretKey, sessionToken);
203
51
254
<no_super_class>
langchain4j_langchain4j
langchain4j/document-parsers/langchain4j-document-parser-apache-pdfbox/src/main/java/dev/langchain4j/data/document/parser/apache/pdfbox/ApachePdfBoxDocumentParser.java
ApachePdfBoxDocumentParser
parse
class ApachePdfBoxDocumentParser implements DocumentParser { @Override public Document parse(InputStream inputStream) {<FILL_FUNCTION_BODY>} }
try { PDDocument pdfDocument = PDDocument.load(inputStream); PDFTextStripper stripper = new PDFTextStripper(); String text = stripper.getText(pdfDocument); pdfDocument.close(); if (isNullOrBlank(text)) { throw new BlankDocumentException(); } return Document.from(text); } catch (IOException e) { throw new RuntimeException(e); }
42
118
160
<no_super_class>
langchain4j_langchain4j
langchain4j/document-parsers/langchain4j-document-parser-apache-poi/src/main/java/dev/langchain4j/data/document/parser/apache/poi/ApachePoiDocumentParser.java
ApachePoiDocumentParser
parse
class ApachePoiDocumentParser implements DocumentParser { @Override public Document parse(InputStream inputStream) {<FILL_FUNCTION_BODY>} }
try (POITextExtractor extractor = ExtractorFactory.createExtractor(inputStream)) { String text = extractor.getText(); if (isNullOrBlank(text)) { throw new BlankDocumentException(); } return Document.from(text); } catch (EmptyFileException e) { throw new BlankDocumentException(); } catch (IOException e) { throw new RuntimeException(e); }
41
114
155
<no_super_class>
langchain4j_langchain4j
langchain4j/document-parsers/langchain4j-document-parser-apache-tika/src/main/java/dev/langchain4j/data/document/parser/apache/tika/ApacheTikaDocumentParser.java
ApacheTikaDocumentParser
parse
class ApacheTikaDocumentParser implements DocumentParser { private static final int NO_WRITE_LIMIT = -1; private final Parser parser; private final ContentHandler contentHandler; private final Metadata metadata; private final ParseContext parseContext; /** * Creates an instance of an {@code ApacheTikaDocumentParser} with the default Tika components. * It uses {@link AutoDetectParser}, {@link BodyContentHandler} without write limit, * empty {@link Metadata} and empty {@link ParseContext}. */ public ApacheTikaDocumentParser() { this(null, null, null, null); } /** * Creates an instance of an {@code ApacheTikaDocumentParser} with the provided Tika components. * If some of the components are not provided ({@code null}, the defaults will be used. * * @param parser Tika parser to use. Default: {@link AutoDetectParser} * @param contentHandler Tika content handler. Default: {@link BodyContentHandler} without write limit * @param metadata Tika metadata. Default: empty {@link Metadata} * @param parseContext Tika parse context. Default: empty {@link ParseContext} */ public ApacheTikaDocumentParser(Parser parser, ContentHandler contentHandler, Metadata metadata, ParseContext parseContext) { this.parser = getOrDefault(parser, AutoDetectParser::new); this.contentHandler = getOrDefault(contentHandler, () -> new BodyContentHandler(NO_WRITE_LIMIT)); this.metadata = getOrDefault(metadata, Metadata::new); this.parseContext = getOrDefault(parseContext, ParseContext::new); } // TODO allow automatically extract metadata (e.g. creator, last-author, created/modified timestamp, etc) @Override public Document parse(InputStream inputStream) {<FILL_FUNCTION_BODY>} }
try { parser.parse(inputStream, contentHandler, metadata, parseContext); String text = contentHandler.toString(); if (isNullOrBlank(text)) { throw new BlankDocumentException(); } return Document.from(text); } catch (BlankDocumentException e) { throw e; } catch (ZeroByteFileException e) { throw new BlankDocumentException(); } catch (Exception e) { throw new RuntimeException(e); }
485
129
614
<no_super_class>
langchain4j_langchain4j
langchain4j/embedding-store-filter-parsers/langchain4j-embedding-store-filter-parser-sql/src/main/java/dev/langchain4j/store/embedding/filter/builder/sql/LanguageModelSqlFilterBuilder.java
LanguageModelSqlFilterBuilder
extractSelectStatement
class LanguageModelSqlFilterBuilder { private static final Logger log = LoggerFactory.getLogger(LanguageModelSqlFilterBuilder.class); private static final PromptTemplate DEFAULT_PROMPT_TEMPLATE = PromptTemplate.from( "### Instructions:\n" + "Your task is to convert a question into a SQL query, given a Postgres database schema.\n" + "Adhere to these rules:\n" + "- **Deliberately go through the question and database schema word by word** to appropriately answer the question\n" + "- **Use Table Aliases** to prevent ambiguity. For example, `SELECT table1.col1, table2.col1 FROM table1 JOIN table2 ON table1.id = table2.id`.\n" + "- When creating a ratio, always cast the numerator as float\n" + "\n" + "### Input:\n" + "Generate a SQL query that answers the question `{{query}}`.\n" + "This query will run on a database whose schema is represented in this string:\n" + "{{create_table_statement}}\n" + "\n" + "### Response:\n" + "Based on your instructions, here is the SQL query I have generated to answer the question `{{query}}`:\n" + "```sql" ); protected final ChatLanguageModel chatLanguageModel; protected final TableDefinition tableDefinition; protected final String createTableStatement; protected final PromptTemplate promptTemplate; protected final SqlFilterParser sqlFilterParser; public LanguageModelSqlFilterBuilder(ChatLanguageModel chatLanguageModel, TableDefinition tableDefinition) { this(chatLanguageModel, tableDefinition, DEFAULT_PROMPT_TEMPLATE, new SqlFilterParser()); } @Builder private LanguageModelSqlFilterBuilder(ChatLanguageModel chatLanguageModel, TableDefinition tableDefinition, PromptTemplate promptTemplate, SqlFilterParser sqlFilterParser) { this.chatLanguageModel = ensureNotNull(chatLanguageModel, "chatLanguageModel"); this.tableDefinition = ensureNotNull(tableDefinition, "tableDefinition"); this.createTableStatement = format(tableDefinition); this.promptTemplate = getOrDefault(promptTemplate, DEFAULT_PROMPT_TEMPLATE); this.sqlFilterParser = getOrDefault(sqlFilterParser, SqlFilterParser::new); } public Filter build(Query query) { Prompt prompt = createPrompt(query); Response<AiMessage> response = chatLanguageModel.generate(prompt.toUserMessage()); String generatedSql = response.content().text(); String cleanedSql = clean(generatedSql); log.trace("Cleaned SQL: '{}'", cleanedSql); try { return sqlFilterParser.parse(cleanedSql); } catch (Exception e) { log.warn("Failed parsing the following SQL: '{}'", cleanedSql, e); // TODO implement additional strategies (configurable): // - feed the error to the LLM and retry // - return predefined filter // - return partial filter if the filter is composite and some parts were parsed successfully // - etc return fallback(query, generatedSql, cleanedSql, e); } } protected Prompt createPrompt(Query query) { Map<String, Object> variables = new HashMap<>(); variables.put("create_table_statement", createTableStatement); variables.put("query", query.text()); return promptTemplate.apply(variables); } protected String clean(String sql) { return sql.trim(); } protected Filter fallback(Query query, String generatedSql, String cleanedSql, Exception e) { String extractedSql = extractSelectStatement(generatedSql); if (isNullOrBlank(extractedSql)) { log.trace("Cannot extract SQL, giving up"); return null; } try { log.trace("Extracted SQL: '{}'", extractedSql); return sqlFilterParser.parse(extractedSql); } catch (Exception e2) { log.warn("Failed parsing the following SQL, giving up: '{}'", extractedSql, e2); return null; } } protected String extractSelectStatement(String dirtySql) {<FILL_FUNCTION_BODY>} protected String format(TableDefinition tableDefinition) { StringBuilder createTableStatement = new StringBuilder(); createTableStatement.append(String.format("CREATE TABLE %s (\n", tableDefinition.name())); for (ColumnDefinition columnDefinition : tableDefinition.columns()) { createTableStatement.append(String.format(" %s %s,", columnDefinition.name(), columnDefinition.type())); if (!isNullOrBlank(columnDefinition.description())) { createTableStatement.append(String.format(" -- %s", columnDefinition.description())); } createTableStatement.append("\n"); } createTableStatement.append(")"); if (!isNullOrBlank(tableDefinition.description())) { createTableStatement.append(String.format(" COMMENT='%s'", tableDefinition.description())); } createTableStatement.append(";"); return createTableStatement.toString(); } }
// TODO improve if (dirtySql.contains("```sql")) { for (String part : dirtySql.split("```sql")) { if (part.toUpperCase().contains("SELECT") && part.toUpperCase().contains("WHERE")) { return part.split("```")[0].trim(); } } } else if (dirtySql.contains("```")) { for (String part : dirtySql.split("```")) { if (part.toUpperCase().contains("SELECT") && part.toUpperCase().contains("WHERE")) { return part.split("```")[0].trim(); } } } else { for (String part : dirtySql.split("SELECT")) { if (part.toUpperCase().contains("WHERE")) { if (part.contains("\n")) { for (String part2 : part.split("\n")) { if (part2.toUpperCase().contains("WHERE")) { return "SELECT " + part2.trim(); } } } else { return "SELECT " + part.trim(); } } } } return null;
1,299
294
1,593
<no_super_class>
langchain4j_langchain4j
langchain4j/embedding-store-filter-parsers/langchain4j-embedding-store-filter-parser-sql/src/main/java/dev/langchain4j/store/embedding/filter/builder/sql/TableDefinition.java
Builder
addColumn
class Builder { private String name; private String description; private Collection<ColumnDefinition> columns; public Builder name(String name) { this.name = name; return this; } public Builder description(String description) { this.description = description; return this; } public Builder columns(Collection<ColumnDefinition> columns) { this.columns = columns; return this; } public Builder addColumn(String name, String type) {<FILL_FUNCTION_BODY>} public Builder addColumn(String name, String type, String description) { if (columns == null) { columns = new ArrayList<>(); } this.columns.add(new ColumnDefinition(name, type, description)); return this; } public TableDefinition build() { return new TableDefinition(name, description, columns); } }
if (columns == null) { columns = new ArrayList<>(); } this.columns.add(new ColumnDefinition(name, type)); return this;
231
44
275
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-anthropic/src/main/java/dev/langchain4j/model/anthropic/AnthropicChatModel.java
AnthropicChatModelBuilder
generate
class AnthropicChatModelBuilder { public AnthropicChatModelBuilder modelName(String modelName) { this.modelName = modelName; return this; } public AnthropicChatModelBuilder modelName(AnthropicChatModelName modelName) { this.modelName = modelName.toString(); return this; } } /** * Creates an instance of {@code AnthropicChatModel} with the specified API key. * * @param apiKey the API key for authentication * @return an {@code AnthropicChatModel} instance */ public static AnthropicChatModel withApiKey(String apiKey) { return builder().apiKey(apiKey).build(); } @Override public Response<AiMessage> generate(List<ChatMessage> messages) { return generate(messages, (List<ToolSpecification>) null); } @Override public Response<AiMessage> generate(List<ChatMessage> messages, List<ToolSpecification> toolSpecifications) {<FILL_FUNCTION_BODY>
ensureNotEmpty(messages, "messages"); AnthropicCreateMessageRequest request = AnthropicCreateMessageRequest.builder() .model(modelName) .messages(toAnthropicMessages(messages)) .system(toAnthropicSystemPrompt(messages)) .maxTokens(maxTokens) .stopSequences(stopSequences) .stream(false) .temperature(temperature) .topP(topP) .topK(topK) .tools(toAnthropicTools(toolSpecifications)) .build(); AnthropicCreateMessageResponse response = withRetry(() -> client.createMessage(request), maxRetries); return Response.from( toAiMessage(response.content), toTokenUsage(response.usage), toFinishReason(response.stopReason) );
267
215
482
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-anthropic/src/main/java/dev/langchain4j/model/anthropic/AnthropicClient.java
Builder
apiKey
class Builder<T extends AnthropicClient, B extends Builder<T, B>> { public String baseUrl; public String apiKey; public String version; public String beta; public Duration timeout; public Boolean logRequests; public Boolean logResponses; public abstract T build(); public B baseUrl(String baseUrl) { if ((baseUrl == null) || baseUrl.trim().isEmpty()) { throw new IllegalArgumentException("baseUrl cannot be null or empty"); } this.baseUrl = baseUrl; return (B) this; } public B apiKey(String apiKey) {<FILL_FUNCTION_BODY>} public B version(String version) { if (version == null) { throw new IllegalArgumentException("version cannot be null or empty"); } this.version = version; return (B) this; } public B beta(String beta) { if (beta == null) { throw new IllegalArgumentException("beta cannot be null or empty"); } this.beta = beta; return (B) this; } public B timeout(Duration timeout) { if (timeout == null) { throw new IllegalArgumentException("timeout cannot be null"); } this.timeout = timeout; return (B) this; } public B logRequests() { return logRequests(true); } public B logRequests(Boolean logRequests) { if (logRequests == null) { logRequests = false; } this.logRequests = logRequests; return (B) this; } public B logResponses() { return logResponses(true); } public B logResponses(Boolean logResponses) { if (logResponses == null) { logResponses = false; } this.logResponses = logResponses; return (B) this; } }
if (apiKey == null || apiKey.trim().isEmpty()) { throw new IllegalArgumentException("Anthropic API key must be defined. " + "It can be generated here: https://console.anthropic.com/settings/keys"); } this.apiKey = apiKey; return (B) this;
514
81
595
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-anthropic/src/main/java/dev/langchain4j/model/anthropic/AnthropicMapper.java
AnthropicMapper
toAnthropicMessages
class AnthropicMapper { static List<AnthropicMessage> toAnthropicMessages(List<ChatMessage> messages) {<FILL_FUNCTION_BODY>} private static AnthropicToolResultContent toAnthropicToolResultContent(ToolExecutionResultMessage message) { return new AnthropicToolResultContent(message.id(), message.text(), null); // TODO propagate isError } private static List<AnthropicMessageContent> toAnthropicMessageContents(UserMessage message) { return message.contents().stream() .map(content -> { if (content instanceof TextContent) { return new AnthropicTextContent(((TextContent) content).text()); } else if (content instanceof ImageContent) { Image image = ((ImageContent) content).image(); if (image.url() != null) { throw illegalArgument("Anthropic does not support images as URLs, " + "only as Base64-encoded strings"); } return new AnthropicImageContent( ensureNotBlank(image.mimeType(), "mimeType"), ensureNotBlank(image.base64Data(), "base64Data") ); } else { throw illegalArgument("Unknown content type: " + content); } }).collect(toList()); } private static List<AnthropicMessageContent> toAnthropicMessageContents(AiMessage message) { List<AnthropicMessageContent> contents = new ArrayList<>(); if (isNotNullOrBlank(message.text())) { contents.add(new AnthropicTextContent(message.text())); } if (message.hasToolExecutionRequests()) { List<AnthropicToolUseContent> toolUseContents = message.toolExecutionRequests().stream() .map(toolExecutionRequest -> AnthropicToolUseContent.builder() .id(toolExecutionRequest.id()) .name(toolExecutionRequest.name()) .input(Json.fromJson(toolExecutionRequest.arguments(), Map.class)) .build()) .collect(toList()); contents.addAll(toolUseContents); } return contents; } static String toAnthropicSystemPrompt(List<ChatMessage> messages) { String systemPrompt = messages.stream() .filter(message -> message instanceof SystemMessage) .map(message -> ((SystemMessage) message).text()) .collect(joining("\n\n")); if (isNullOrBlank(systemPrompt)) { return null; } else { return systemPrompt; } } public static AiMessage toAiMessage(List<AnthropicContent> contents) { String text = contents.stream() .filter(content -> "text".equals(content.type)) .map(content -> content.text) .collect(joining("\n")); List<ToolExecutionRequest> toolExecutionRequests = contents.stream() .filter(content -> "tool_use".equals(content.type)) .map(content -> ToolExecutionRequest.builder() .id(content.id) .name(content.name) .arguments(Json.toJson(content.input)) .build()) .collect(toList()); if (isNotNullOrBlank(text) && !isNullOrEmpty(toolExecutionRequests)) { return new AiMessage(text, toolExecutionRequests); } else if (!isNullOrEmpty(toolExecutionRequests)) { return AiMessage.from(toolExecutionRequests); } else { return AiMessage.from(text); } } public static TokenUsage toTokenUsage(AnthropicUsage anthropicUsage) { if (anthropicUsage == null) { return null; } return new TokenUsage(anthropicUsage.inputTokens, anthropicUsage.outputTokens); } public static FinishReason toFinishReason(String anthropicStopReason) { if (anthropicStopReason == null) { return null; } switch (anthropicStopReason) { case "end_turn": return STOP; case "max_tokens": return LENGTH; case "stop_sequence": return OTHER; // TODO case "tool_use": return TOOL_EXECUTION; default: return null; // TODO } } static List<AnthropicTool> toAnthropicTools(List<ToolSpecification> toolSpecifications) { if (toolSpecifications == null) { return null; } return toolSpecifications.stream() .map(AnthropicMapper::toAnthropicTool) .collect(toList()); } static AnthropicTool toAnthropicTool(ToolSpecification toolSpecification) { ToolParameters parameters = toolSpecification.parameters(); return AnthropicTool.builder() .name(toolSpecification.name()) .description(toolSpecification.description()) .inputSchema(AnthropicToolSchema.builder() .properties(parameters != null ? parameters.properties() : emptyMap()) .required(parameters != null ? parameters.required() : emptyList()) .build()) .build(); } }
List<AnthropicMessage> anthropicMessages = new ArrayList<>(); List<AnthropicMessageContent> toolContents = new ArrayList<>(); for (ChatMessage message : messages) { if (message instanceof ToolExecutionResultMessage) { toolContents.add(toAnthropicToolResultContent((ToolExecutionResultMessage) message)); } else { if (!toolContents.isEmpty()) { anthropicMessages.add(new AnthropicMessage(USER, toolContents)); toolContents = new ArrayList<>(); } if (message instanceof UserMessage) { List<AnthropicMessageContent> contents = toAnthropicMessageContents((UserMessage) message); anthropicMessages.add(new AnthropicMessage(USER, contents)); } else if (message instanceof AiMessage) { List<AnthropicMessageContent> contents = toAnthropicMessageContents((AiMessage) message); anthropicMessages.add(new AnthropicMessage(ASSISTANT, contents)); } } } if (!toolContents.isEmpty()) { anthropicMessages.add(new AnthropicMessage(USER, toolContents)); } return anthropicMessages;
1,324
294
1,618
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-anthropic/src/main/java/dev/langchain4j/model/anthropic/AnthropicRequestLoggingInterceptor.java
AnthropicRequestLoggingInterceptor
getBody
class AnthropicRequestLoggingInterceptor implements Interceptor { private static final Set<String> COMMON_SECRET_HEADERS = new HashSet<>(asList("authorization", "x-api-key", "x-auth-token")); @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); log(request); return chain.proceed(request); } private void log(Request request) { try { log.debug("Request:\n- method: {}\n- url: {}\n- headers: {}\n- body: {}", request.method(), request.url(), getHeaders(request.headers()), getBody(request)); } catch (Exception e) { log.warn("Error while logging request: {}", e.getMessage()); } } static String getHeaders(Headers headers) { return StreamSupport.stream(headers.spliterator(), false) .map(header -> format(header.component1(), header.component2())) .collect(joining(", ")); } static String format(String headerKey, String headerValue) { if (COMMON_SECRET_HEADERS.contains(headerKey.toLowerCase())) { headerValue = maskSecretKey(headerValue); } return String.format("[%s: %s]", headerKey, headerValue); } static String maskSecretKey(String key) { if (isNullOrBlank(key)) { return key; } if (key.length() >= 7) { return key.substring(0, 5) + "..." + key.substring(key.length() - 2); } else { return "..."; // to short to be masked } } private static String getBody(Request request) {<FILL_FUNCTION_BODY>} }
try { Buffer buffer = new Buffer(); if (request.body() == null) { return ""; } request.body().writeTo(buffer); return buffer.readUtf8(); } catch (Exception e) { log.warn("Exception while getting body", e); return "Exception while getting body: " + e.getMessage(); }
477
97
574
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-anthropic/src/main/java/dev/langchain4j/model/anthropic/AnthropicResponseLoggingInterceptor.java
AnthropicResponseLoggingInterceptor
getBody
class AnthropicResponseLoggingInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); this.log(response); return response; } private void log(Response response) { try { log.debug("Response:\n- status code: {}\n- headers: {}\n- body: {}", response.code(), getHeaders(response.headers()), this.getBody(response)); } catch (Exception e) { log.warn("Error while logging response: {}", e.getMessage()); } } private String getBody(Response response) throws IOException {<FILL_FUNCTION_BODY>} private static boolean isEventStream(Response response) { String contentType = response.header("Content-Type"); return contentType != null && contentType.contains("event-stream"); } }
return isEventStream(response) ? "[skipping response body due to streaming]" : response.peekBody(Long.MAX_VALUE).string();
241
41
282
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-anthropic/src/main/java/dev/langchain4j/model/anthropic/AnthropicStreamingChatModel.java
AnthropicStreamingChatModelBuilder
generate
class AnthropicStreamingChatModelBuilder { public AnthropicStreamingChatModelBuilder modelName(String modelName) { this.modelName = modelName; return this; } public AnthropicStreamingChatModelBuilder modelName(AnthropicChatModelName modelName) { this.modelName = modelName.toString(); return this; } } /** * Creates an instance of {@code AnthropicStreamingChatModel} with the specified API key. * * @param apiKey the API key for authentication * @return an {@code AnthropicStreamingChatModel} instance */ public static AnthropicStreamingChatModel withApiKey(String apiKey) { return builder().apiKey(apiKey).build(); } @Override public void generate(List<ChatMessage> messages, StreamingResponseHandler<AiMessage> handler) {<FILL_FUNCTION_BODY>
ensureNotEmpty(messages, "messages"); ensureNotNull(handler, "handler"); AnthropicCreateMessageRequest request = AnthropicCreateMessageRequest.builder() .model(modelName) .messages(toAnthropicMessages(messages)) .system(toAnthropicSystemPrompt(messages)) .maxTokens(maxTokens) .stopSequences(stopSequences) .stream(true) .temperature(temperature) .topP(topP) .topK(topK) .build(); client.createMessage(request, handler);
231
151
382
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-azure-ai-search/src/main/java/dev/langchain4j/store/embedding/azure/search/AzureAiSearchEmbeddingStore.java
Builder
build
class Builder { private String endpoint; private AzureKeyCredential keyCredential; private TokenCredential tokenCredential; private boolean createOrUpdateIndex = true; private int dimensions; private SearchIndex index; /** * Sets the Azure AI Search endpoint. This is a mandatory parameter. * * @param endpoint The Azure AI Search endpoint in the format: https://{resource}.search.windows.net * @return builder */ public Builder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * Sets the Azure AI Search API key. * * @param apiKey The Azure AI Search API key. * @return builder */ public Builder apiKey(String apiKey) { this.keyCredential = new AzureKeyCredential(apiKey); return this; } /** * Used to authenticate to Azure OpenAI with Azure Active Directory credentials. * @param tokenCredential the credentials to authenticate with Azure Active Directory * @return builder */ public Builder tokenCredential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /** * Whether to create or update the search index. * * @param createOrUpdateIndex Whether to create or update the index. * @return builder */ public Builder createOrUpdateIndex(boolean createOrUpdateIndex) { this.createOrUpdateIndex = createOrUpdateIndex; return this; } /** * If using the ready-made index, sets the number of dimensions of the embeddings. * This parameter is exclusive of the index parameter. * * @param dimensions The number of dimensions of the embeddings. * @return builder */ public Builder dimensions(int dimensions) { this.dimensions = dimensions; return this; } /** * If using a custom index, sets the index to be used. * This parameter is exclusive of the dimensions parameter. * * @param index The index to be used. * @return builder */ public Builder index(SearchIndex index) { this.index = index; return this; } public AzureAiSearchEmbeddingStore build() {<FILL_FUNCTION_BODY>} }
ensureNotNull(endpoint, "endpoint"); ensureTrue(keyCredential != null || tokenCredential != null, "either apiKey or tokenCredential must be set"); ensureTrue(dimensions > 0 || index != null, "either dimensions or index must be set"); if (keyCredential == null) { if (index == null) { return new AzureAiSearchEmbeddingStore(endpoint, tokenCredential, createOrUpdateIndex, dimensions); } else { return new AzureAiSearchEmbeddingStore(endpoint, tokenCredential, createOrUpdateIndex, index); } } else { if (index == null) { return new AzureAiSearchEmbeddingStore(endpoint, keyCredential, createOrUpdateIndex, dimensions); } else { return new AzureAiSearchEmbeddingStore(endpoint, keyCredential, createOrUpdateIndex, index); } }
594
231
825
<methods>public non-sealed void <init>() ,public java.lang.String add(dev.langchain4j.data.embedding.Embedding) ,public void add(java.lang.String, dev.langchain4j.data.embedding.Embedding) ,public java.lang.String add(dev.langchain4j.data.embedding.Embedding, dev.langchain4j.data.segment.TextSegment) ,public List<java.lang.String> addAll(List<dev.langchain4j.data.embedding.Embedding>) ,public List<java.lang.String> addAll(List<dev.langchain4j.data.embedding.Embedding>, List<dev.langchain4j.data.segment.TextSegment>) ,public void createOrUpdateIndex(int) ,public void deleteIndex() ,public List<EmbeddingMatch<dev.langchain4j.data.segment.TextSegment>> findRelevant(dev.langchain4j.data.embedding.Embedding, int, double) <variables>protected static final java.lang.String DEFAULT_FIELD_CONTENT,protected final java.lang.String DEFAULT_FIELD_CONTENT_VECTOR,static final java.lang.String DEFAULT_FIELD_ID,protected static final java.lang.String DEFAULT_FIELD_METADATA,protected static final java.lang.String DEFAULT_FIELD_METADATA_ATTRS,protected static final java.lang.String DEFAULT_FIELD_METADATA_SOURCE,public static final java.lang.String INDEX_NAME,protected static final java.lang.String SEMANTIC_SEARCH_CONFIG_NAME,protected static final java.lang.String VECTOR_ALGORITHM_NAME,protected static final java.lang.String VECTOR_SEARCH_PROFILE_NAME,private boolean createOrUpdateIndex,private static final Logger log,protected SearchClient searchClient,private SearchIndexClient searchIndexClient
langchain4j_langchain4j
langchain4j/langchain4j-azure-cosmos-mongo-vcore/src/main/java/dev/langchain4j/store/embedding/azure/cosmos/mongo/vcore/MappingUtils.java
MappingUtils
toEmbeddingMatch
class MappingUtils { private MappingUtils() throws InstantiationException { throw new InstantiationException("can't instantiate this class"); } static AzureCosmosDbMongoVCoreDocument toMongoDbDocument(String id, Embedding embedding, TextSegment textSegment) { if (textSegment == null) { return new AzureCosmosDbMongoVCoreDocument(id, embedding.vectorAsList(), null, null); } return new AzureCosmosDbMongoVCoreDocument(id, embedding.vectorAsList(), textSegment.text(), textSegment.metadata().asMap()); } static EmbeddingMatch<TextSegment> toEmbeddingMatch(AzureCosmosDbMongoVCoreMatchedDocument matchedDocument) {<FILL_FUNCTION_BODY>} }
TextSegment textSegment = null; if (matchedDocument.getText() != null) { textSegment = TextSegment.from(matchedDocument.getText(), Metadata.from(matchedDocument.getMetadata())); } return new EmbeddingMatch<>(matchedDocument.getScore(), matchedDocument.getId(), Embedding.from(matchedDocument.getEmbedding()), textSegment);
200
96
296
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-azure-open-ai/src/main/java/dev/langchain4j/model/azure/AzureOpenAiImageModel.java
Builder
build
class Builder { private String endpoint; private String serviceVersion; private String apiKey; private KeyCredential keyCredential; private TokenCredential tokenCredential; private String deploymentName; private String quality; private String size; private String user; private String style; private String responseFormat; private Duration timeout; private Integer maxRetries; private ProxyOptions proxyOptions; private boolean logRequestsAndResponses; private OpenAIClient openAIClient; /** * Sets the Azure OpenAI endpoint. This is a mandatory parameter. * * @param endpoint The Azure OpenAI endpoint in the format: https://{resource}.openai.azure.com/ * @return builder */ public Builder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * Sets the Azure OpenAI API service version. This is a mandatory parameter. * * @param serviceVersion The Azure OpenAI API service version in the format: 2023-05-15 * @return builder */ public Builder serviceVersion(String serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the Azure OpenAI API key. * * @param apiKey The Azure OpenAI API key. * @return builder */ public Builder apiKey(String apiKey) { this.apiKey = apiKey; return this; } /** * Used to authenticate with the OpenAI service, instead of Azure OpenAI. * This automatically sets the endpoint to https://api.openai.com/v1. * * @param nonAzureApiKey The non-Azure OpenAI API key * @return builder */ public Builder nonAzureApiKey(String nonAzureApiKey) { this.keyCredential = new KeyCredential(nonAzureApiKey); this.endpoint = "https://api.openai.com/v1"; return this; } /** * Used to authenticate to Azure OpenAI with Azure Active Directory credentials. * @param tokenCredential the credentials to authenticate with Azure Active Directory * @return builder */ public Builder tokenCredential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /** * Sets the deployment name in Azure OpenAI. This is a mandatory parameter. * * @param deploymentName The Deployment name. * @return builder */ public Builder deploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } /** * Sets the quality of the image. This is an optional parameter. * * @param quality The quality of the image. * @return builder */ public Builder quality(String quality) { this.quality = quality; return this; } /** * Sets the quality of the image, using the ImageGenerationQuality enum. This is an optional parameter. * * @param imageGenerationQuality The quality of the image. * @return builder */ public Builder quality(ImageGenerationQuality imageGenerationQuality) { this.quality = imageGenerationQuality.toString(); return this; } /** * Sets the size of the image. This is an optional parameter. * * @param size The size of the image. * @return builder */ public Builder size(String size) { this.size = size; return this; } /** * Sets the size of the image, using the ImageSize enum. This is an optional parameter. * * @param imageSize The size of the image. * @return builder */ public Builder size(ImageSize imageSize) { this.size = imageSize.toString(); return this; } /** * Sets the user of the image. This is an optional parameter. * * @param user The user of the image. * @return builder */ public Builder user(String user) { this.user = user; return this; } /** * Sets the style of the image. This is an optional parameter. * * @param style The style of the image. * @return builder */ public Builder style(String style) { this.style = style; return this; } /** * Sets the style of the image, using the ImageGenerationStyle enum. This is an optional parameter. * * @param imageGenerationStyle The style of the image. * @return builder */ public Builder style(ImageGenerationStyle imageGenerationStyle) { this.style = imageGenerationStyle.toString(); return this; } /** * Sets the response format of the image. This is an optional parameter. * * @param responseFormat The response format of the image. * @return builder */ public Builder responseFormat(String responseFormat) { this.responseFormat = responseFormat; return this; } /** * Sets the response format of the image, using the ImageGenerationResponseFormat enum. This is an optional parameter. * * @param imageGenerationResponseFormat The response format of the image. * @return builder */ public Builder responseFormat(ImageGenerationResponseFormat imageGenerationResponseFormat) { this.responseFormat = imageGenerationResponseFormat.toString(); return this; } public Builder timeout(Duration timeout) { this.timeout = timeout; return this; } public Builder maxRetries(Integer maxRetries) { this.maxRetries = maxRetries; return this; } public Builder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } public Builder logRequestsAndResponses(Boolean logRequestsAndResponses) { this.logRequestsAndResponses = logRequestsAndResponses; return this; } public Builder openAIClient(OpenAIClient openAIClient) { this.openAIClient = openAIClient; return this; } public AzureOpenAiImageModel build() {<FILL_FUNCTION_BODY>} }
if (openAIClient == null) { if (tokenCredential != null) { return new AzureOpenAiImageModel( endpoint, serviceVersion, tokenCredential, deploymentName, quality, size, user, style, responseFormat, timeout, maxRetries, proxyOptions, logRequestsAndResponses); } else if (keyCredential != null) { return new AzureOpenAiImageModel( endpoint, serviceVersion, keyCredential, deploymentName, quality, size, user, style, responseFormat, timeout, maxRetries, proxyOptions, logRequestsAndResponses); } return new AzureOpenAiImageModel( endpoint, serviceVersion, apiKey, deploymentName, quality, size, user, style, responseFormat, timeout, maxRetries, proxyOptions, logRequestsAndResponses); } return new AzureOpenAiImageModel( openAIClient, deploymentName, quality, size, user, style, responseFormat);
1,627
321
1,948
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-azure-open-ai/src/main/java/dev/langchain4j/model/azure/AzureOpenAiLanguageModel.java
Builder
build
class Builder { private String endpoint; private String serviceVersion; private String apiKey; private KeyCredential keyCredential; private TokenCredential tokenCredential; private String deploymentName; private Tokenizer tokenizer; private Integer maxTokens; private Double temperature; private Double topP; private Map<String, Integer> logitBias; private String user; private Integer n; private Integer logprobs; private Boolean echo; private List<String> stop; private Double presencePenalty; private Double frequencyPenalty; private Integer bestOf; private Duration timeout; private Integer maxRetries; private ProxyOptions proxyOptions; private boolean logRequestsAndResponses; private OpenAIClient openAIClient; /** * Sets the Azure OpenAI endpoint. This is a mandatory parameter. * * @param endpoint The Azure OpenAI endpoint in the format: https://{resource}.openai.azure.com/ * @return builder */ public Builder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * Sets the Azure OpenAI API service version. This is a mandatory parameter. * * @param serviceVersion The Azure OpenAI API service version in the format: 2023-05-15 * @return builder */ public Builder serviceVersion(String serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Sets the Azure OpenAI API key. * * @param apiKey The Azure OpenAI API key. * @return builder */ public Builder apiKey(String apiKey) { this.apiKey = apiKey; return this; } /** * Used to authenticate with the OpenAI service, instead of Azure OpenAI. * This automatically sets the endpoint to https://api.openai.com/v1. * * @param nonAzureApiKey The non-Azure OpenAI API key * @return builder */ public Builder nonAzureApiKey(String nonAzureApiKey) { this.keyCredential = new KeyCredential(nonAzureApiKey); this.endpoint = "https://api.openai.com/v1"; return this; } /** * Used to authenticate to Azure OpenAI with Azure Active Directory credentials. * @param tokenCredential the credentials to authenticate with Azure Active Directory * @return builder */ public Builder tokenCredential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /** * Sets the deployment name in Azure OpenAI. This is a mandatory parameter. * * @param deploymentName The Deployment name. * @return builder */ public Builder deploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } public Builder tokenizer(Tokenizer tokenizer) { this.tokenizer = tokenizer; return this; } public Builder maxTokens(Integer maxTokens) { this.maxTokens = maxTokens; return this; } public Builder temperature(Double temperature) { this.temperature = temperature; return this; } public Builder topP(Double topP) { this.topP = topP; return this; } public Builder logitBias(Map<String, Integer> logitBias) { this.logitBias = logitBias; return this; } public Builder user(String user) { this.user = user; return this; } public Builder n(Integer n) { this.n = n; return this; } public Builder logprobs(Integer logprobs) { this.logprobs = logprobs; return this; } public Builder echo(Boolean echo) { this.echo = echo; return this; } public Builder stop(List<String> stop) { this.stop = stop; return this; } public Builder presencePenalty(Double presencePenalty) { this.presencePenalty = presencePenalty; return this; } public Builder frequencyPenalty(Double frequencyPenalty) { this.frequencyPenalty = frequencyPenalty; return this; } public Builder bestOf(Integer bestOf) { this.bestOf = bestOf; return this; } public Builder timeout(Duration timeout) { this.timeout = timeout; return this; } public Builder maxRetries(Integer maxRetries) { this.maxRetries = maxRetries; return this; } public Builder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } public Builder logRequestsAndResponses(boolean logRequestsAndResponses) { this.logRequestsAndResponses = logRequestsAndResponses; return this; } /** * Sets the Azure OpenAI client. This is an optional parameter, if you need more flexibility than using the endpoint, serviceVersion, apiKey, deploymentName parameters. * * @param openAIClient The Azure OpenAI client. * @return builder */ public Builder openAIClient(OpenAIClient openAIClient) { this.openAIClient = openAIClient; return this; } public AzureOpenAiLanguageModel build() {<FILL_FUNCTION_BODY>} }
if (openAIClient == null) { if (tokenCredential != null) { return new AzureOpenAiLanguageModel( endpoint, serviceVersion, tokenCredential, deploymentName, tokenizer, maxTokens, temperature, topP, logitBias, user, n, logprobs, echo, stop, presencePenalty, frequencyPenalty, bestOf, timeout, maxRetries, proxyOptions, logRequestsAndResponses ); } else if (keyCredential != null) { return new AzureOpenAiLanguageModel( endpoint, serviceVersion, keyCredential, deploymentName, tokenizer, maxTokens, temperature, topP, logitBias, user, n, logprobs, echo, stop, presencePenalty, frequencyPenalty, bestOf, timeout, maxRetries, proxyOptions, logRequestsAndResponses ); } return new AzureOpenAiLanguageModel( endpoint, serviceVersion, apiKey, deploymentName, tokenizer, maxTokens, temperature, topP, logitBias, user, n, logprobs, echo, stop, presencePenalty, frequencyPenalty, bestOf, timeout, maxRetries, proxyOptions, logRequestsAndResponses ); } else { return new AzureOpenAiLanguageModel( openAIClient, deploymentName, tokenizer, maxTokens, temperature, topP, logitBias, user, n, logprobs, echo, stop, presencePenalty, frequencyPenalty, bestOf ); }
1,462
522
1,984
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-azure-open-ai/src/main/java/dev/langchain4j/model/azure/AzureOpenAiStreamingResponseBuilder.java
AzureOpenAiStreamingResponseBuilder
append
class AzureOpenAiStreamingResponseBuilder { private final StringBuffer contentBuilder = new StringBuffer(); private final StringBuffer toolNameBuilder = new StringBuffer(); private final StringBuffer toolArgumentsBuilder = new StringBuffer(); private volatile CompletionsFinishReason finishReason; private final Integer inputTokenCount; public AzureOpenAiStreamingResponseBuilder(Integer inputTokenCount) { this.inputTokenCount = inputTokenCount; } public void append(ChatCompletions completions) {<FILL_FUNCTION_BODY>} public void append(Completions completions) { if (completions == null) { return; } List<Choice> choices = completions.getChoices(); if (choices == null || choices.isEmpty()) { return; } Choice completionChoice = choices.get(0); if (completionChoice == null) { return; } CompletionsFinishReason completionsFinishReason = completionChoice.getFinishReason(); if (completionsFinishReason != null) { this.finishReason = completionsFinishReason; } String token = completionChoice.getText(); if (token != null) { contentBuilder.append(token); } } public Response<AiMessage> build(Tokenizer tokenizer, boolean forcefulToolExecution) { String content = contentBuilder.toString(); if (!content.isEmpty()) { return Response.from( AiMessage.from(content), tokenUsage(content, tokenizer), finishReasonFrom(finishReason) ); } String toolName = toolNameBuilder.toString(); if (!toolName.isEmpty()) { ToolExecutionRequest toolExecutionRequest = ToolExecutionRequest.builder() .name(toolName) .arguments(toolArgumentsBuilder.toString()) .build(); return Response.from( AiMessage.from(toolExecutionRequest), tokenUsage(toolExecutionRequest, tokenizer, forcefulToolExecution), finishReasonFrom(finishReason) ); } return null; } private TokenUsage tokenUsage(String content, Tokenizer tokenizer) { if (tokenizer == null) { return null; } int outputTokenCount = tokenizer.estimateTokenCountInText(content); return new TokenUsage(inputTokenCount, outputTokenCount); } private TokenUsage tokenUsage(ToolExecutionRequest toolExecutionRequest, Tokenizer tokenizer, boolean forcefulToolExecution) { if (tokenizer == null) { return null; } int outputTokenCount = 0; if (forcefulToolExecution) { // OpenAI calculates output tokens differently when tool is executed forcefully outputTokenCount += tokenizer.estimateTokenCountInForcefulToolExecutionRequest(toolExecutionRequest); } else { outputTokenCount = tokenizer.estimateTokenCountInToolExecutionRequests(singletonList(toolExecutionRequest)); } return new TokenUsage(inputTokenCount, outputTokenCount); } }
if (completions == null) { return; } List<ChatChoice> choices = completions.getChoices(); if (choices == null || choices.isEmpty()) { return; } ChatChoice chatCompletionChoice = choices.get(0); if (chatCompletionChoice == null) { return; } CompletionsFinishReason finishReason = chatCompletionChoice.getFinishReason(); if (finishReason != null) { this.finishReason = finishReason; } com.azure.ai.openai.models.ChatResponseMessage delta = chatCompletionChoice.getDelta(); if (delta == null) { return; } String content = delta.getContent(); if (content != null) { contentBuilder.append(content); return; } FunctionCall functionCall = delta.getFunctionCall(); if (functionCall != null) { if (functionCall.getName() != null) { toolNameBuilder.append(functionCall.getName()); } if (functionCall.getArguments() != null) { toolArgumentsBuilder.append(functionCall.getArguments()); } }
785
320
1,105
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-azure-open-ai/src/main/java/dev/langchain4j/model/azure/InternalAzureOpenAiHelper.java
Parameters
finishReasonFrom
class Parameters { private final String type = "object"; private Map<String, Map<String, Object>> properties = new HashMap<>(); private List<String> required = new ArrayList<>(); public String getType() { return this.type; } public Map<String, Map<String, Object>> getProperties() { return properties; } public void setProperties(Map<String, Map<String, Object>> properties) { this.properties = properties; } public List<String> getRequired() { return required; } public void setRequired(List<String> required) { this.required = required; } } public static AiMessage aiMessageFrom(com.azure.ai.openai.models.ChatResponseMessage chatResponseMessage) { if (chatResponseMessage.getContent() != null) { return aiMessage(chatResponseMessage.getContent()); } else { FunctionCall functionCall = chatResponseMessage.getFunctionCall(); ToolExecutionRequest toolExecutionRequest = ToolExecutionRequest.builder() .name(functionCall.getName()) .arguments(functionCall.getArguments()) .build(); return aiMessage(toolExecutionRequest); } } public static Image imageFrom(com.azure.ai.openai.models.ImageGenerationData imageGenerationData) { Image.Builder imageBuilder = Image.builder() .revisedPrompt(imageGenerationData.getRevisedPrompt()); String urlString = imageGenerationData.getUrl(); String imageData = imageGenerationData.getBase64Data(); if (urlString != null) { try { URI uri = new URI(urlString); imageBuilder.url(uri); } catch (URISyntaxException e) { throw new RuntimeException(e); } } else if (imageData != null) { imageBuilder.base64Data(imageData); } return imageBuilder.build(); } public static TokenUsage tokenUsageFrom(CompletionsUsage openAiUsage) { if (openAiUsage == null) { return null; } return new TokenUsage( openAiUsage.getPromptTokens(), openAiUsage.getCompletionTokens(), openAiUsage.getTotalTokens() ); } public static FinishReason finishReasonFrom(CompletionsFinishReason openAiFinishReason) {<FILL_FUNCTION_BODY>
if (openAiFinishReason == null) { return null; } else if (openAiFinishReason == CompletionsFinishReason.STOPPED) { return STOP; } else if (openAiFinishReason == CompletionsFinishReason.TOKEN_LIMIT_REACHED) { return LENGTH; } else if (openAiFinishReason == CompletionsFinishReason.CONTENT_FILTERED) { return CONTENT_FILTER; } else if (openAiFinishReason == CompletionsFinishReason.FUNCTION_CALL) { return TOOL_EXECUTION; } else { return null; }
644
183
827
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockAI21LabsChatModel.java
BedrockAI21LabsChatModel
getRequestParameters
class BedrockAI21LabsChatModel extends AbstractBedrockChatModel<BedrockAI21LabsChatModelResponse> { @Builder.Default private final String model = Types.J2MidV2.getValue(); @Builder.Default private final Map<String, Object> countPenalty = of("scale", 0); @Builder.Default private final Map<String, Object> presencePenalty = of("scale", 0); @Builder.Default private final Map<String, Object> frequencyPenalty = of("scale", 0); @Override protected Map<String, Object> getRequestParameters(String prompt) {<FILL_FUNCTION_BODY>} @Override protected String getModelId() { return model; } @Override protected Class<BedrockAI21LabsChatModelResponse> getResponseClassType() { return BedrockAI21LabsChatModelResponse.class; } /** * Bedrock AI21 Labs model ids */ @Getter public enum Types { J2MidV2("ai21.j2-mid-v1"), J2UltraV1("ai21.j2-ultra-v1"); private final String value; Types(String modelID) { this.value = modelID; } } }
final Map<String, Object> parameters = new HashMap<>(8); parameters.put("prompt", prompt); parameters.put("maxTokens", getMaxTokens()); parameters.put("temperature", getTemperature()); parameters.put("topP", getTopP()); parameters.put("stopSequences", getStopSequences()); parameters.put("countPenalty", countPenalty); parameters.put("presencePenalty", presencePenalty); parameters.put("frequencyPenalty", frequencyPenalty); return parameters;
358
145
503
<methods>public non-sealed void <init>() ,public Response<dev.langchain4j.data.message.AiMessage> generate(List<dev.langchain4j.data.message.ChatMessage>) <variables>private static final java.lang.String ASSISTANT_PROMPT,private static final java.lang.String HUMAN_PROMPT,private final java.lang.String assistantPrompt,private final BedrockRuntimeClient client,private final AwsCredentialsProvider credentialsProvider,private final java.lang.String humanPrompt,private final java.lang.Integer maxRetries,private final int maxTokens,private final Region region,private final java.lang.String[] stopSequences,private final float temperature,private final float topP
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockAI21LabsChatModelResponse.java
Completion
getFinishReason
class Completion { private Prompt data; private CompletionReason finishReason; } private int id; private Prompt prompt; private List<Completion> completions; @Override public String getOutputText() { return completions.get(0).data.text; } @Override public FinishReason getFinishReason() {<FILL_FUNCTION_BODY>
final String finishReason = completions.get(0).getFinishReason().getReason(); switch (finishReason) { case "endoftext": return FinishReason.STOP; default: throw new IllegalStateException("Unknown finish reason: " + finishReason); }
108
76
184
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockAnthropicCompletionChatModel.java
BedrockAnthropicCompletionChatModel
getRequestParameters
class BedrockAnthropicCompletionChatModel extends AbstractBedrockChatModel<BedrockAnthropicCompletionChatModelResponse> { private static final String DEFAULT_ANTHROPIC_VERSION = "bedrock-2023-05-31"; @Builder.Default private final int topK = 250; @Builder.Default private final String anthropicVersion = DEFAULT_ANTHROPIC_VERSION; @Builder.Default private final String model = Types.AnthropicClaudeV2.getValue(); @Override protected String getModelId() { return model; } @Override protected Map<String, Object> getRequestParameters(String prompt) {<FILL_FUNCTION_BODY>} @Override public Class<BedrockAnthropicCompletionChatModelResponse> getResponseClassType() { return BedrockAnthropicCompletionChatModelResponse.class; } /** * Bedrock Anthropic model ids */ @Getter public enum Types { AnthropicClaudeInstantV1("anthropic.claude-instant-v1"), AnthropicClaudeV1("anthropic.claude-v1"), AnthropicClaudeV2("anthropic.claude-v2"), AnthropicClaudeV2_1("anthropic.claude-v2:1"), AnthropicClaude3SonnetV1("anthropic.claude-3-sonnet-20240229-v1:0"); private final String value; Types(String modelID) { this.value = modelID; } } }
final Map<String, Object> parameters = new HashMap<>(7); parameters.put("prompt", prompt); parameters.put("max_tokens_to_sample", getMaxTokens()); parameters.put("temperature", getTemperature()); parameters.put("top_k", topK); parameters.put("top_p", getTopP()); parameters.put("stop_sequences", getStopSequences()); parameters.put("anthropic_version", anthropicVersion); return parameters;
426
131
557
<methods>public non-sealed void <init>() ,public Response<dev.langchain4j.data.message.AiMessage> generate(List<dev.langchain4j.data.message.ChatMessage>) <variables>private static final java.lang.String ASSISTANT_PROMPT,private static final java.lang.String HUMAN_PROMPT,private final java.lang.String assistantPrompt,private final BedrockRuntimeClient client,private final AwsCredentialsProvider credentialsProvider,private final java.lang.String humanPrompt,private final java.lang.Integer maxRetries,private final int maxTokens,private final Region region,private final java.lang.String[] stopSequences,private final float temperature,private final float topP
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockAnthropicCompletionChatModelResponse.java
BedrockAnthropicCompletionChatModelResponse
getFinishReason
class BedrockAnthropicCompletionChatModelResponse implements BedrockChatModelResponse { private String completion; private String stop_reason; @Override public String getOutputText() { return completion; } @Override public FinishReason getFinishReason() {<FILL_FUNCTION_BODY>} @Override public TokenUsage getTokenUsage() { return null; } }
switch (stop_reason) { case "stop_sequence": return FinishReason.STOP; case "max_tokens": return FinishReason.LENGTH; default: throw new IllegalArgumentException("Unknown stop reason: " + stop_reason); }
112
73
185
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockAnthropicMessageChatModel.java
BedrockAnthropicMessageChatModel
mapContentToAnthropic
class BedrockAnthropicMessageChatModel extends AbstractBedrockChatModel<BedrockAnthropicMessageChatModelResponse> { private static final String DEFAULT_ANTHROPIC_VERSION = "bedrock-2023-05-31"; @Builder.Default private final int topK = 250; @Builder.Default private final String anthropicVersion = DEFAULT_ANTHROPIC_VERSION; @Builder.Default private final String model = Types.AnthropicClaude3SonnetV1.getValue(); @Override protected String getModelId() { return model; } @Override protected Map<String, Object> getRequestParameters(String prompt) { final Map<String, Object> parameters = new HashMap<>(9); parameters.put("max_tokens", getMaxTokens()); parameters.put("temperature", getTemperature()); parameters.put("top_k", topK); parameters.put("top_p", getTopP()); parameters.put("stop_sequences", getStopSequences()); parameters.put("anthropic_version", anthropicVersion); return parameters; } @Override public Response<AiMessage> generate(List<ChatMessage> messages) { final String system = getAnthropicSystemPrompt(messages); List<BedrockAnthropicMessage> formattedMessages = getAnthropicMessages(messages); Map<String, Object> parameters = getRequestParameters(null); parameters.put("messages", formattedMessages); parameters.put("system", system); final String body = Json.toJson(parameters); InvokeModelResponse invokeModelResponse = withRetry(() -> invoke(body), getMaxRetries()); final String response = invokeModelResponse.body().asUtf8String(); BedrockAnthropicMessageChatModelResponse result = Json.fromJson(response, getResponseClassType()); return new Response<>(new AiMessage(result.getOutputText()), result.getTokenUsage(), result.getFinishReason()); } private List<BedrockAnthropicMessage> getAnthropicMessages(List<ChatMessage> messages) { return messages.stream() .filter(message -> message.type() != ChatMessageType.SYSTEM) .map(message -> new BedrockAnthropicMessage(getAnthropicRole(message), getAnthropicContent(message))) .collect(Collectors.toList()); } private List<BedrockAnthropicContent> getAnthropicContent(ChatMessage message) { if (message instanceof AiMessage) { return Collections.singletonList(new BedrockAnthropicContent("text", ((AiMessage) message).text())); } else if (message instanceof UserMessage) { return ((UserMessage) message).contents().stream() .map(BedrockAnthropicMessageChatModel::mapContentToAnthropic) .collect(Collectors.toList()); } else { throw new IllegalArgumentException("Unknown message type: " + message.type()); } } private static BedrockAnthropicContent mapContentToAnthropic(Content content) {<FILL_FUNCTION_BODY>} private String getAnthropicSystemPrompt(List<ChatMessage> messages) { return messages.stream() .filter(message -> message.type() == ChatMessageType.SYSTEM) .map(ChatMessage::text) .collect(joining("\n")); } private String getAnthropicRole(ChatMessage message) { return message.type() == ChatMessageType.AI ? "assistant" : "user"; } @Override public Class<BedrockAnthropicMessageChatModelResponse> getResponseClassType() { return BedrockAnthropicMessageChatModelResponse.class; } /** * Bedrock Anthropic model ids */ @Getter public enum Types { AnthropicClaudeInstantV1("anthropic.claude-instant-v1"), AnthropicClaudeV2("anthropic.claude-v2"), AnthropicClaudeV2_1("anthropic.claude-v2:1"), AnthropicClaude3SonnetV1("anthropic.claude-3-sonnet-20240229-v1:0"), AnthropicClaude3HaikuV1("anthropic.claude-3-haiku-20240307-v1:0"); private final String value; Types(String modelID) { this.value = modelID; } } }
if (content instanceof TextContent) { return new BedrockAnthropicContent("text", ((TextContent) content).text()); } else if (content instanceof ImageContent) { ImageContent imageContent = (ImageContent) content; if (imageContent.image().url() != null) { throw new IllegalArgumentException("Anthropic does not support images as URLs, only as Base64-encoded strings"); } BedrockAnthropicImageSource imageSource = new BedrockAnthropicImageSource( "base64", ensureNotBlank(imageContent.image().mimeType(), "mimeType"), ensureNotBlank(imageContent.image().base64Data(), "base64Data") ); return new BedrockAnthropicContent("image", imageSource); } else { throw new IllegalArgumentException("Unknown content type: " + content); }
1,187
220
1,407
<methods>public non-sealed void <init>() ,public Response<dev.langchain4j.data.message.AiMessage> generate(List<dev.langchain4j.data.message.ChatMessage>) <variables>private static final java.lang.String ASSISTANT_PROMPT,private static final java.lang.String HUMAN_PROMPT,private final java.lang.String assistantPrompt,private final BedrockRuntimeClient client,private final AwsCredentialsProvider credentialsProvider,private final java.lang.String humanPrompt,private final java.lang.Integer maxRetries,private final int maxTokens,private final Region region,private final java.lang.String[] stopSequences,private final float temperature,private final float topP
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockAnthropicMessageChatModelResponse.java
BedrockAnthropicUsage
getTokenUsage
class BedrockAnthropicUsage { private int input_tokens; private int output_tokens; } @Override public String getOutputText() { return content.stream().map(BedrockAnthropicContent::getText).collect(Collectors.joining("\n\n")); } @Override public FinishReason getFinishReason() { switch (stop_reason) { case "end_turn": case "stop_sequence": return FinishReason.STOP; case "max_tokens": return FinishReason.LENGTH; default: throw new IllegalArgumentException("Unknown stop reason: " + stop_reason); } } @Override public TokenUsage getTokenUsage() {<FILL_FUNCTION_BODY>
if (usage != null) { int totalTokenCount = usage.input_tokens + usage.output_tokens; return new TokenUsage(usage.input_tokens, usage.output_tokens, totalTokenCount); } else { return null; }
203
73
276
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockCohereChatModel.java
BedrockCohereChatModel
getRequestParameters
class BedrockCohereChatModel extends AbstractBedrockChatModel<BedrockCohereChatModelResponse> { public enum ReturnLikelihood { NONE, GENERATION, ALL } @Builder.Default private static ReturnLikelihood returnLikelihood = ReturnLikelihood.NONE; @Builder.Default private final int topK = 0; @Builder.Default private final String model = Types.CommandTextV14.getValue(); @Override protected Map<String, Object> getRequestParameters(String prompt) {<FILL_FUNCTION_BODY>} @Override protected String getModelId() { return model; } @Override protected Class<BedrockCohereChatModelResponse> getResponseClassType() { return BedrockCohereChatModelResponse.class; } /** * Bedrock Cohere model ids */ @Getter public enum Types { CommandTextV14("cohere.command-text-v14"); private final String value; Types(String modelID) { this.value = modelID; } } }
final Map<String, Object> parameters = new HashMap<>(7); parameters.put("prompt", prompt); parameters.put("max_tokens", getMaxTokens()); parameters.put("temperature", getTemperature()); parameters.put("p", getTopP()); parameters.put("k", getTopK()); parameters.put("stop_sequences", getStopSequences()); parameters.put("return_likelihoods", returnLikelihood.name()); return parameters;
304
127
431
<methods>public non-sealed void <init>() ,public Response<dev.langchain4j.data.message.AiMessage> generate(List<dev.langchain4j.data.message.ChatMessage>) <variables>private static final java.lang.String ASSISTANT_PROMPT,private static final java.lang.String HUMAN_PROMPT,private final java.lang.String assistantPrompt,private final BedrockRuntimeClient client,private final AwsCredentialsProvider credentialsProvider,private final java.lang.String humanPrompt,private final java.lang.Integer maxRetries,private final int maxTokens,private final Region region,private final java.lang.String[] stopSequences,private final float temperature,private final float topP
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockCohereChatModelResponse.java
Generation
getFinishReason
class Generation { private String id; private String text; private String finish_reason; private List<TokenLikelihood> token_likelihoods; } private String id; private List<Generation> generations; private String prompt; @Override public String getOutputText() { return generations.get(0).text; } @Override public FinishReason getFinishReason() {<FILL_FUNCTION_BODY>
final String finishReason = generations.get(0).finish_reason; if ("COMPLETE".equals(finishReason)) { return FinishReason.STOP; } throw new IllegalStateException("Unknown finish reason: " + finishReason);
124
66
190
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockLlamaChatModel.java
BedrockLlamaChatModel
getRequestParameters
class BedrockLlamaChatModel extends AbstractBedrockChatModel<BedrockLlamaChatModelResponse> { @Builder.Default private final String model = Types.MetaLlama2Chat70B.getValue(); @Override protected String getModelId() { return model; } @Override protected Map<String, Object> getRequestParameters(String prompt) {<FILL_FUNCTION_BODY>} @Override public Class<BedrockLlamaChatModelResponse> getResponseClassType() { return BedrockLlamaChatModelResponse.class; } /** * Bedrock Llama model ids */ @Getter public enum Types { MetaLlama2Chat13B("meta.llama2-13b-chat-v1"), MetaLlama2Chat70B("meta.llama2-70b-chat-v1"); private final String value; Types(String modelID) { this.value = modelID; } } }
final Map<String, Object> parameters = new HashMap<>(7); parameters.put("prompt", prompt); parameters.put("max_gen_len", getMaxTokens()); parameters.put("temperature", getTemperature()); parameters.put("top_p", getTopP()); return parameters;
278
82
360
<methods>public non-sealed void <init>() ,public Response<dev.langchain4j.data.message.AiMessage> generate(List<dev.langchain4j.data.message.ChatMessage>) <variables>private static final java.lang.String ASSISTANT_PROMPT,private static final java.lang.String HUMAN_PROMPT,private final java.lang.String assistantPrompt,private final BedrockRuntimeClient client,private final AwsCredentialsProvider credentialsProvider,private final java.lang.String humanPrompt,private final java.lang.Integer maxRetries,private final int maxTokens,private final Region region,private final java.lang.String[] stopSequences,private final float temperature,private final float topP
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockLlamaChatModelResponse.java
BedrockLlamaChatModelResponse
getFinishReason
class BedrockLlamaChatModelResponse implements BedrockChatModelResponse { private String generation; private int prompt_token_count; private int generation_token_count; private String stop_reason; @Override public String getOutputText() { return generation; } @Override public FinishReason getFinishReason() {<FILL_FUNCTION_BODY>} @Override public TokenUsage getTokenUsage() { return new TokenUsage(prompt_token_count, generation_token_count); } }
switch (stop_reason) { case "stop": return FinishReason.STOP; case "length": return FinishReason.LENGTH; default: throw new IllegalArgumentException("Unknown stop reason: " + stop_reason); }
146
68
214
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockMistralAiChatModel.java
BedrockMistralAiChatModel
generate
class BedrockMistralAiChatModel extends AbstractBedrockChatModel<BedrockMistralAiChatModelResponse> { @Builder.Default private final int topK = 200; @Builder.Default private final String model = Types.Mistral7bInstructV0_2.getValue(); @Override protected String getModelId() { return model; } @Override protected Map<String, Object> getRequestParameters(String prompt) { final Map<String, Object> parameters = new HashMap<>(7); parameters.put("prompt", prompt); parameters.put("max_tokens", getMaxTokens()); parameters.put("temperature", getTemperature()); parameters.put("top_p", getTopP()); parameters.put("top_k", topK); parameters.put("stop", getStopSequences()); return parameters; } @Override public Response<AiMessage> generate(List<ChatMessage> messages) {<FILL_FUNCTION_BODY>} private String buildPrompt(List<ChatMessage> messages) { StringBuilder promptBuilder = new StringBuilder(); promptBuilder.append("<s>"); for (ChatMessage message : messages) { switch (message.type()) { case USER: promptBuilder.append("[INST] ").append(message.text()).append(" [/INST]"); break; case AI: promptBuilder.append(" ").append(message.text()).append(" "); break; default: throw new IllegalArgumentException("Bedrock Mistral AI does not support the message type: " + message.type()); } } promptBuilder.append("</s>"); return promptBuilder.toString(); } @Override public Class<BedrockMistralAiChatModelResponse> getResponseClassType() { return BedrockMistralAiChatModelResponse.class; } /** * Bedrock Mistral model ids */ @Getter public enum Types { Mistral7bInstructV0_2("mistral.mistral-7b-instruct-v0:2"), MistralMixtral8x7bInstructV0_1("mistral.mixtral-8x7b-instruct-v0:1"); private final String value; Types(String modelID) { this.value = modelID; } } }
String prompt = buildPrompt(messages); final Map<String, Object> requestParameters = getRequestParameters(prompt); final String body = Json.toJson(requestParameters); InvokeModelResponse invokeModelResponse = withRetry(() -> invoke(body), getMaxRetries()); final String response = invokeModelResponse.body().asUtf8String().trim(); final BedrockMistralAiChatModelResponse result = Json.fromJson(response, getResponseClassType()); return new Response<>(new AiMessage(result.getOutputText()), result.getTokenUsage(), result.getFinishReason());
635
157
792
<methods>public non-sealed void <init>() ,public Response<dev.langchain4j.data.message.AiMessage> generate(List<dev.langchain4j.data.message.ChatMessage>) <variables>private static final java.lang.String ASSISTANT_PROMPT,private static final java.lang.String HUMAN_PROMPT,private final java.lang.String assistantPrompt,private final BedrockRuntimeClient client,private final AwsCredentialsProvider credentialsProvider,private final java.lang.String humanPrompt,private final java.lang.Integer maxRetries,private final int maxTokens,private final Region region,private final java.lang.String[] stopSequences,private final float temperature,private final float topP
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockMistralAiChatModelResponse.java
Output
getFinishReason
class Output { private String text; private String stop_reason; } @Override public String getOutputText() { return outputs.get(0).text; } @Override public FinishReason getFinishReason() {<FILL_FUNCTION_BODY>
String stop_reason = outputs.get(0).stop_reason; switch (stop_reason) { case "stop": return FinishReason.STOP; case "length": return FinishReason.LENGTH; default: throw new IllegalArgumentException("Unknown stop reason: " + stop_reason); }
77
85
162
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockStabilityAIChatModel.java
BedrockStabilityAIChatModel
getRequestParameters
class BedrockStabilityAIChatModel extends AbstractBedrockChatModel<BedrockStabilityAIChatModelResponse> { @Getter public enum StylePreset { ThreeDModel("3d-model"), Anime("anime"), Cinematic("cinematic"), ComicBook("comic-book"), DigitalArt("digital-art"), Enhance("enhance"), FantasyArt("fantasy-art"), Isometric("isometric"), LineArt("line-art"), LowPoly("low-poly"), ModelingCompound("modeling-compound"), NeonPunk("neon-punk"), Origami("origami"), Photographic("photographic"), PixelArt("pixel-art"), TileTexture("tile-texture"), AnalogFilm("analog-film"); private final String value; StylePreset(String value) { this.value = value; } } @Builder.Default private final String model = Types.StableDiffuseXlV1.getValue(); @Builder.Default private final int cfgScale = 10; @Builder.Default private final int width = 512; @Builder.Default private final int height = 512; @Builder.Default private final int seed = 0; @Builder.Default private final int steps = 50; @Builder.Default private final double promptWeight = 0.5; @Builder.Default private final StylePreset stylePreset = StylePreset.ThreeDModel; @Override protected Map<String, Object> getRequestParameters(String prompt) {<FILL_FUNCTION_BODY>} @Override protected String getModelId() { return model; } @Override protected Class<BedrockStabilityAIChatModelResponse> getResponseClassType() { return BedrockStabilityAIChatModelResponse.class; } /** * Bedrock Amazon Stability AI model ids */ @Getter public enum Types { StableDiffuseXlV0("stability.stable-diffusion-xl-v0"), StableDiffuseXlV1("stability.stable-diffusion-xl-v1"); private final String value; Types(String modelID) { this.value = modelID; } } }
final Map<String, Object> textPrompt = new HashMap<>(2); textPrompt.put("text", prompt); textPrompt.put("weight", promptWeight); final Map<String, Object> parameters = new HashMap<>(4); parameters.put("text_prompts", Collections.singletonList(textPrompt)); parameters.put("cfg_scale", cfgScale); parameters.put("seed", seed); parameters.put("steps", steps); parameters.put("width", width); parameters.put("height", height); parameters.put("style_preset", stylePreset.getValue()); return parameters;
628
169
797
<methods>public non-sealed void <init>() ,public Response<dev.langchain4j.data.message.AiMessage> generate(List<dev.langchain4j.data.message.ChatMessage>) <variables>private static final java.lang.String ASSISTANT_PROMPT,private static final java.lang.String HUMAN_PROMPT,private final java.lang.String assistantPrompt,private final BedrockRuntimeClient client,private final AwsCredentialsProvider credentialsProvider,private final java.lang.String humanPrompt,private final java.lang.Integer maxRetries,private final int maxTokens,private final Region region,private final java.lang.String[] stopSequences,private final float temperature,private final float topP
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockStabilityAIChatModelResponse.java
Artifact
getFinishReason
class Artifact { private String base64; private int seed; private String finishReason; } private String result; private List<Artifact> artifacts; @Override public String getOutputText() { return artifacts.get(0).base64; } @Override public FinishReason getFinishReason() {<FILL_FUNCTION_BODY>
switch (artifacts.get(0).finishReason) { case "SUCCESS": return FinishReason.STOP; case "CONTENT_FILTERED": return FinishReason.CONTENT_FILTER; default: throw new IllegalArgumentException("Unknown stop reason: " + artifacts.get(0).finishReason); }
106
94
200
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockTitanChatModel.java
BedrockTitanChatModel
getRequestParameters
class BedrockTitanChatModel extends AbstractBedrockChatModel<BedrockTitanChatModelResponse> { @Builder.Default private final String model = Types.TitanTextExpressV1.getValue(); @Override protected Map<String, Object> getRequestParameters(String prompt) {<FILL_FUNCTION_BODY>} @Override protected String getModelId() { return model; } @Override public Class<BedrockTitanChatModelResponse> getResponseClassType() { return BedrockTitanChatModelResponse.class; } /** * Bedrock Amazon Titan model ids */ @Getter public enum Types { TitanTg1Large("amazon.titan-tg1-large"), TitanTextExpressV1("amazon.titan-text-express-v1"); private final String value; Types(String modelID) { this.value = modelID; } } }
final Map<String, Object> textGenerationConfig = new HashMap<>(4); textGenerationConfig.put("maxTokenCount", getMaxTokens()); textGenerationConfig.put("temperature", getTemperature()); textGenerationConfig.put("topP", getTopP()); textGenerationConfig.put("stopSequences", getStopSequences()); final Map<String, Object> parameters = new HashMap<>(2); parameters.put("inputText", prompt); parameters.put("textGenerationConfig", textGenerationConfig); return parameters;
258
146
404
<methods>public non-sealed void <init>() ,public Response<dev.langchain4j.data.message.AiMessage> generate(List<dev.langchain4j.data.message.ChatMessage>) <variables>private static final java.lang.String ASSISTANT_PROMPT,private static final java.lang.String HUMAN_PROMPT,private final java.lang.String assistantPrompt,private final BedrockRuntimeClient client,private final AwsCredentialsProvider credentialsProvider,private final java.lang.String humanPrompt,private final java.lang.Integer maxRetries,private final int maxTokens,private final Region region,private final java.lang.String[] stopSequences,private final float temperature,private final float topP
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/BedrockTitanChatModelResponse.java
BedrockTitanChatModelResponse
getOutputText
class BedrockTitanChatModelResponse implements BedrockChatModelResponse { @Override public String getOutputText() {<FILL_FUNCTION_BODY>} @Override public FinishReason getFinishReason() { if (results.isEmpty()) { throw new IllegalStateException("No results returned"); } final Result result = results.get(0); switch (result.completionReason) { case "FINISH": return FinishReason.STOP; default: return FinishReason.LENGTH; } } @Override public TokenUsage getTokenUsage() { if (results.isEmpty()) { throw new IllegalStateException("No results returned"); } final Result result = results.get(0); return new TokenUsage(inputTextTokenCount, result.tokenCount); } @Getter @Setter public static class Result { private int tokenCount; private String outputText; private String completionReason; } private int inputTextTokenCount; private List<Result> results; }
if (results.isEmpty()) { throw new IllegalStateException("No results returned"); } return results.get(0).outputText;
282
40
322
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/internal/AbstractBedrockChatModel.java
AbstractBedrockChatModel
generate
class AbstractBedrockChatModel<T extends BedrockChatModelResponse> implements ChatLanguageModel { private static final String HUMAN_PROMPT = "Human:"; private static final String ASSISTANT_PROMPT = "Assistant:"; @Builder.Default private final String humanPrompt = HUMAN_PROMPT; @Builder.Default private final String assistantPrompt = ASSISTANT_PROMPT; @Builder.Default private final Integer maxRetries = 5; @Builder.Default private final Region region = Region.US_EAST_1; @Builder.Default private final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build(); @Builder.Default private final int maxTokens = 300; @Builder.Default private final float temperature = 1; @Builder.Default private final float topP = 0.999f; @Builder.Default private final String[] stopSequences = new String[]{}; @Getter(lazy = true) private final BedrockRuntimeClient client = initClient(); @Override public Response<AiMessage> generate(List<ChatMessage> messages) {<FILL_FUNCTION_BODY>} /** * Convert chat message to string * * @param message chat message * @return string */ protected String chatMessageToString(ChatMessage message) { switch (message.type()) { case SYSTEM: return message.text(); case USER: return humanPrompt + " " + message.text(); case AI: return assistantPrompt + " " + message.text(); case TOOL_EXECUTION_RESULT: throw new IllegalArgumentException("Tool execution results are not supported for Bedrock models"); } throw new IllegalArgumentException("Unknown message type: " + message.type()); } /** * Get request parameters * * @param prompt prompt * @return request body */ protected abstract Map<String, Object> getRequestParameters(final String prompt); /** * Get model id * * @return model id */ protected abstract String getModelId(); /** * Get response class type * * @return response class type */ protected abstract Class<T> getResponseClassType(); /** * Invoke call to the API * * @param body body * @return invoke model response */ protected InvokeModelResponse invoke(final String body) { // Invoke model InvokeModelRequest invokeModelRequest = InvokeModelRequest .builder() .modelId(getModelId()) .body(SdkBytes.fromString(body, Charset.defaultCharset())) .build(); return getClient().invokeModel(invokeModelRequest); } /** * Create map with single entry * * @param key key * @param value value * @return map */ protected static Map<String, Object> of(final String key, final Object value) { return new HashMap<String, Object>(1) {{ put(key, value); }}; } /** * Initialize bedrock client * * @return bedrock client */ private BedrockRuntimeClient initClient() { return BedrockRuntimeClient.builder() .region(region) .credentialsProvider(credentialsProvider) .build(); } }
final String context = messages.stream() .filter(message -> message.type() == ChatMessageType.SYSTEM) .map(ChatMessage::text) .collect(joining("\n")); final String userMessages = messages.stream() .filter(message -> message.type() != ChatMessageType.SYSTEM) .map(this::chatMessageToString) .collect(joining("\n")); final String prompt = String.format("%s\n\n%s\n%s", context, userMessages, ASSISTANT_PROMPT); final Map<String, Object> requestParameters = getRequestParameters(prompt); final String body = Json.toJson(requestParameters); InvokeModelResponse invokeModelResponse = withRetry(() -> invoke(body), maxRetries); final String response = invokeModelResponse.body().asUtf8String(); final T result = Json.fromJson(response, getResponseClassType()); return new Response<>(new AiMessage(result.getOutputText()), result.getTokenUsage(), result.getFinishReason());
881
275
1,156
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-bedrock/src/main/java/dev/langchain4j/model/bedrock/internal/AbstractBedrockEmbeddingModel.java
AbstractBedrockEmbeddingModel
invoke
class AbstractBedrockEmbeddingModel<T extends BedrockEmbeddingResponse> implements EmbeddingModel { @Builder.Default private final Region region = Region.US_EAST_1; @Builder.Default private final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build(); @Getter(lazy = true) private final BedrockRuntimeClient client = initClient(); @Builder.Default private final Integer maxRetries = 5; @Override public Response<List<Embedding>> embedAll(List<TextSegment> textSegments) { final List<Map<String, Object>> requestParameters = getRequestParameters(textSegments); final List<T> responses = requestParameters.stream() .map(Json::toJson) .map(body -> withRetry(() -> invoke(body), maxRetries)) .map(invokeModelResponse -> invokeModelResponse.body().asUtf8String()) .map(response -> Json.fromJson(response, getResponseClassType())) .collect(Collectors.toList()); int totalInputToken = 0; final List<Embedding> embeddings = new ArrayList<>(); for (T response : responses) { embeddings.add(response.toEmbedding()); totalInputToken += response.getInputTextTokenCount(); } return Response.from( embeddings, new TokenUsage(totalInputToken)); } /** * Get request body * * @param textSegments Input texts to convert to embedding * @return request body */ protected abstract List<Map<String, Object>> getRequestParameters(final List<TextSegment> textSegments); /** * Get model id * * @return model id */ protected abstract String getModelId(); /** * Get response class type * * @return response class type */ protected abstract Class<T> getResponseClassType(); /** * Invoke model * * @param body body * @return invoke model response */ protected InvokeModelResponse invoke(final String body) {<FILL_FUNCTION_BODY>} /** * Create map with single entry * * @param key key * @param value value * @return map */ protected static Map<String, Object> of(final String key, final Object value) { final Map<String, Object> map = new HashMap<>(1); map.put(key, value); return map; } /** * Initialize bedrock client * * @return bedrock client */ private BedrockRuntimeClient initClient() { return BedrockRuntimeClient.builder() .region(region) .credentialsProvider(credentialsProvider) .build(); } }
// Invoke model InvokeModelRequest invokeModelRequest = InvokeModelRequest .builder() .modelId(getModelId()) .body(SdkBytes.fromString(body, Charset.defaultCharset())) .build(); return getClient().invokeModel(invokeModelRequest);
723
77
800
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-cassandra/src/main/java/dev/langchain4j/store/embedding/astradb/AstraDbEmbeddingStore.java
AstraDbEmbeddingStore
mapJsonResult
class AstraDbEmbeddingStore implements EmbeddingStore<TextSegment> { /** * Saving the text chunk as an attribut. */ public static final String KEY_ATTRIBUTES_BLOB = "body_blob"; /** * Metadata used for similarity. */ public static final String KEY_SIMILARITY = "$similarity"; /** * Client to work with an Astra Collection */ private final AstraDBCollection astraDBCollection; /** * Bulk loading are processed in chunks, size of 1 chunk in between 1 and 20 */ private final int itemsPerChunk; /** * Bulk loading is distributed,the is the number threads */ private final int concurrentThreads; /** * Initialization of the store with an EXISTING collection. * * @param client * astra db collection client */ public AstraDbEmbeddingStore(@NonNull AstraDBCollection client) { this(client, 20, 8); } /** * Initialization of the store with an EXISTING collection. * * @param client * astra db collection client * @param itemsPerChunk * size of 1 chunk in between 1 and 20 */ public AstraDbEmbeddingStore(@NonNull AstraDBCollection client, int itemsPerChunk, int concurrentThreads) { if (itemsPerChunk>20 || itemsPerChunk<1) { throw new IllegalArgumentException("'itemsPerChunk' should be in between 1 and 20"); } if (concurrentThreads<1) { throw new IllegalArgumentException("'concurrentThreads' should be at least 1"); } this.astraDBCollection = client; this.itemsPerChunk = itemsPerChunk; this.concurrentThreads = concurrentThreads; } /** * Delete all records from the table. */ public void clear() { astraDBCollection.deleteAll(); } /** {@inheritDoc} */ @Override public String add(Embedding embedding) { return add(embedding, null); } /** {@inheritDoc} */ @Override public String add(Embedding embedding, TextSegment textSegment) { return astraDBCollection .insertOne(mapRecord(embedding, textSegment)) .getDocument().getId(); } /** {@inheritDoc} */ @Override public void add(String id, Embedding embedding) { astraDBCollection.upsertOne(new JsonDocument().id(id).vector(embedding.vector())); } /** {@inheritDoc} */ @Override public List<String> addAll(List<Embedding> embeddings) { if (embeddings == null) return null; // Map as a JsonDocument list. List<JsonDocument> recordList = embeddings .stream() .map(e -> mapRecord(e, null)) .collect(Collectors.toList()); // No upsert needed as ids will be generated. return astraDBCollection .insertManyChunkedJsonDocuments(recordList, itemsPerChunk, concurrentThreads) .stream() .map(JsonDocumentMutationResult::getDocument) .map(Document::getId) .collect(Collectors.toList()); } /** * Add multiple embeddings as a single action. * * @param embeddingList * list of embeddings * @param textSegmentList * list of text segment * * @return list of new row if (same order as the input) */ public List<String> addAll(List<Embedding> embeddingList, List<TextSegment> textSegmentList) { if (embeddingList == null || textSegmentList == null || embeddingList.size() != textSegmentList.size()) { throw new IllegalArgumentException("embeddingList and textSegmentList must not be null and have the same size"); } // Map as JsonDocument list List<JsonDocument> recordList = new ArrayList<>(); for (int i = 0; i < embeddingList.size(); i++) { recordList.add(mapRecord(embeddingList.get(i), textSegmentList.get(i))); } // No upsert needed (ids will be generated) return astraDBCollection .insertManyChunkedJsonDocuments(recordList, itemsPerChunk, concurrentThreads) .stream() .map(JsonDocumentMutationResult::getDocument) .map(Document::getId) .collect(Collectors.toList()); } /** {@inheritDoc} */ public List<EmbeddingMatch<TextSegment>> findRelevant(Embedding referenceEmbedding, int maxResults, double minScore) { return findRelevant(referenceEmbedding, (Filter) null, maxResults, minScore); } /** * Semantic search with metadata filtering. * * @param referenceEmbedding * vector * @param metaDatafilter * fileter for metadata * @param maxResults * limit * @param minScore * threshold * @return * records */ public List<EmbeddingMatch<TextSegment>> findRelevant(Embedding referenceEmbedding, Filter metaDatafilter, int maxResults, double minScore) { return astraDBCollection.findVector(referenceEmbedding.vector(), metaDatafilter, maxResults) .filter(r -> r.getSimilarity() >= minScore) .map(this::mapJsonResult) .collect(Collectors.toList()); } /** * Mapping the output of the query to a {@link EmbeddingMatch}.. * * @param jsonRes * returned object as Json * @return * embedding match as expected by langchain4j */ private EmbeddingMatch<TextSegment> mapJsonResult(JsonDocumentResult jsonRes) {<FILL_FUNCTION_BODY>} /** * Map from LangChain4j record to AstraDB record. * * @param embedding * embedding (vector) * @param textSegment * text segment (text to encode) * @return * a json document */ private JsonDocument mapRecord(Embedding embedding, TextSegment textSegment) { JsonDocument record = new JsonDocument().vector(embedding.vector()); if (textSegment != null) { record.put(KEY_ATTRIBUTES_BLOB, textSegment.text()); textSegment.metadata().asMap().forEach(record::put); } return record; } }
Double score = (double) jsonRes.getSimilarity(); String embeddingId = jsonRes.getId(); Embedding embedding = Embedding.from(jsonRes.getVector()); TextSegment embedded = null; Map<String, Object> properties = jsonRes.getData(); if (properties!= null) { Object body = properties.get(KEY_ATTRIBUTES_BLOB); if (body != null) { Metadata metadata = new Metadata(properties.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue() == null ? "" : entry.getValue().toString() ))); metadata.remove(KEY_ATTRIBUTES_BLOB); metadata.remove(KEY_SIMILARITY); embedded = new TextSegment(body.toString(), metadata); } } return new EmbeddingMatch<TextSegment>(score, embeddingId, embedding, embedded);
1,733
240
1,973
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-cassandra/src/main/java/dev/langchain4j/store/embedding/cassandra/CassandraEmbeddingStore.java
BuilderAstra
addAll
class BuilderAstra { private String token; private UUID dbId; private String tableName; private int dimension; private String keyspaceName = "default_keyspace"; private String dbRegion = "us-east1"; private CassandraSimilarityMetric metric = CassandraSimilarityMetric.COSINE; private AstraEnvironment env = AstraEnvironment.PROD; public BuilderAstra token(String token) { this.token = token; return this; } public BuilderAstra env(AstraEnvironment env) { this.env = env; return this; } public BuilderAstra databaseId(UUID dbId) { this.dbId = dbId; return this; } public BuilderAstra databaseRegion(String dbRegion) { this.dbRegion = dbRegion; return this; } public BuilderAstra keyspace(String keyspaceName) { this.keyspaceName = keyspaceName; return this; } public BuilderAstra table(String tableName) { this.tableName = tableName; return this; } public BuilderAstra dimension(int dimension) { this.dimension = dimension; return this; } public BuilderAstra metric(CassandraSimilarityMetric metric) { this.metric = metric; return this; } public CassandraEmbeddingStore build() { CqlSession cqlSession = CassIO.init(token, dbId, dbRegion, keyspaceName, env); return new CassandraEmbeddingStore(cqlSession, tableName, dimension, metric); } } /** * Add a new embedding to the store. * - the row id is generated * - text and metadata are not stored * * @param embedding representation of the list of floats * @return newly created row id */ @Override public String add(@NonNull Embedding embedding) { return add(embedding, null); } /** * Add a new embedding to the store. * - the row id is generated * - text and metadata coming from the text Segment * * @param embedding representation of the list of floats * @param textSegment text content and metadata * @return newly created row id */ @Override public String add(@NonNull Embedding embedding, TextSegment textSegment) { MetadataVectorRecord record = new MetadataVectorRecord(embedding.vectorAsList()); if (textSegment != null) { record.setBody(textSegment.text()); record.setMetadata(textSegment.metadata().asMap()); } embeddingTable.put(record); return record.getRowId(); } /** * Add a new embedding to the store. * * @param rowId the row id * @param embedding representation of the list of floats */ @Override public void add(@NonNull String rowId, @NonNull Embedding embedding) { embeddingTable.put(new MetadataVectorRecord(rowId, embedding.vectorAsList())); } /** * Add multiple embeddings as a single action. * * @param embeddingList embeddings list * @return list of new row if (same order as the input) */ @Override public List<String> addAll(List<Embedding> embeddingList) { return embeddingList.stream() .map(Embedding::vectorAsList) .map(MetadataVectorRecord::new) .peek(embeddingTable::putAsync) .map(MetadataVectorRecord::getRowId) .collect(toList()); } /** * Add multiple embeddings as a single action. * * @param embeddingList embeddings * @param textSegmentList text segments * @return list of new row if (same order as the input) */ @Override public List<String> addAll(List<Embedding> embeddingList, List<TextSegment> textSegmentList) {<FILL_FUNCTION_BODY>
if (embeddingList == null || textSegmentList == null || embeddingList.size() != textSegmentList.size()) { throw new IllegalArgumentException("embeddingList and textSegmentList must not be null and have the same size"); } // Looping on both list with an index List<String> ids = new ArrayList<>(); for (int i = 0; i < embeddingList.size(); i++) { ids.add(add(embeddingList.get(i), textSegmentList.get(i))); } return ids;
1,037
138
1,175
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-cassandra/src/main/java/dev/langchain4j/store/memory/chat/cassandra/CassandraChatMemoryStore.java
CassandraChatMemoryStore
toChatMessage
class CassandraChatMemoryStore implements ChatMemoryStore { /** * Default message store. */ public static final String DEFAULT_TABLE_NAME = "message_store"; /** * Message Table. */ private final ClusteredTable messageTable; /** * Constructor for message store * * @param session cassandra session */ public CassandraChatMemoryStore(CqlSession session) { this(session, DEFAULT_TABLE_NAME); } /** * Constructor for message store * * @param session cassandra session * @param tableName table name */ public CassandraChatMemoryStore(CqlSession session, String tableName) { messageTable = new ClusteredTable(session, session.getKeyspace().get().asInternal(), tableName); } /** * Create the table if not exist. */ public void create() { messageTable.create(); } /** * Delete the table. */ public void delete() { messageTable.delete(); } /** * Delete all rows. */ public void clear() { messageTable.clear(); } /** * Access the cassandra session for fined grained operation. * * @return * current cassandra session */ public CqlSession getCassandraSession() { return messageTable.getCqlSession(); } /** * {@inheritDoc} */ @Override public List<ChatMessage> getMessages(@NonNull Object memoryId) { /* * RATIONAL: * In the cassandra table the order is explicitly put to DESC with * latest to come first (for long conversation for instance). Here we ask * for the full history. Instead of changing the multipurpose table * we reverse the list. */ List<ChatMessage> latestFirstList = messageTable .findPartition(getMemoryId(memoryId)) .stream() .map(this::toChatMessage) .collect(toList()); Collections.reverse(latestFirstList); return latestFirstList; } /** * {@inheritDoc} */ @Override public void updateMessages(@NonNull Object memoryId, @NonNull List<ChatMessage> messages) { deleteMessages(memoryId); messageTable.upsertPartition(messages.stream() .map(record -> fromChatMessage(getMemoryId(memoryId), record)) .collect(toList())); } /** * {@inheritDoc} */ @Override public void deleteMessages(@NonNull Object memoryId) { messageTable.deletePartition(getMemoryId(memoryId)); } /** * Unmarshalling Cassandra row as a Message with proper subtype. * * @param record cassandra record * @return chat message */ private ChatMessage toChatMessage(@NonNull ClusteredRecord record) {<FILL_FUNCTION_BODY>} /** * Serialize the {@link ChatMessage} as a Cassandra Row. * * @param memoryId chat session identifier * @param chatMessage chat message * @return cassandra row. */ private ClusteredRecord fromChatMessage(@NonNull String memoryId, @NonNull ChatMessage chatMessage) { try { ClusteredRecord record = new ClusteredRecord(); record.setRowId(Uuids.timeBased()); record.setPartitionId(memoryId); record.setBody(ChatMessageSerializer.messageToJson(chatMessage)); return record; } catch (Exception e) { throw new IllegalArgumentException("Unable to parse message body", e); } } private String getMemoryId(Object memoryId) { if (!(memoryId instanceof String)) { throw new IllegalArgumentException("memoryId must be a String"); } return (String) memoryId; } public static class Builder { public static Integer DEFAULT_PORT = 9042; private List<String> contactPoints; private String localDataCenter; private Integer port = DEFAULT_PORT; private String userName; private String password; protected String keyspace; protected String table = DEFAULT_TABLE_NAME; public CassandraChatMemoryStore.Builder contactPoints(List<String> contactPoints) { this.contactPoints = contactPoints; return this; } public CassandraChatMemoryStore.Builder localDataCenter(String localDataCenter) { this.localDataCenter = localDataCenter; return this; } public CassandraChatMemoryStore.Builder port(Integer port) { this.port = port; return this; } public CassandraChatMemoryStore.Builder userName(String userName) { this.userName = userName; return this; } public CassandraChatMemoryStore.Builder password(String password) { this.password = password; return this; } public CassandraChatMemoryStore.Builder keyspace(String keyspace) { this.keyspace = keyspace; return this; } public CassandraChatMemoryStore.Builder table(String table) { this.table = table; return this; } public Builder() { } public CassandraChatMemoryStore build() { CqlSessionBuilder builder = CqlSession.builder() .withKeyspace(keyspace) .withLocalDatacenter(localDataCenter); if (userName != null && password != null) { builder.withAuthCredentials(userName, password); } contactPoints.forEach(cp -> builder.addContactPoint(new InetSocketAddress(cp, port))); return new CassandraChatMemoryStore(builder.build(), table); } } public static CassandraChatMemoryStore.Builder builder() { return new CassandraChatMemoryStore.Builder(); } public static CassandraChatMemoryStore.BuilderAstra builderAstra() { return new CassandraChatMemoryStore.BuilderAstra(); } public static class BuilderAstra { private String token; private UUID dbId; private String tableName = DEFAULT_TABLE_NAME; private String keyspaceName = "default_keyspace"; private String dbRegion = "us-east1"; private AstraEnvironment env = AstraEnvironment.PROD; public BuilderAstra token(String token) { this.token = token; return this; } public CassandraChatMemoryStore.BuilderAstra databaseId(UUID dbId) { this.dbId = dbId; return this; } public CassandraChatMemoryStore.BuilderAstra env(AstraEnvironment env) { this.env = env; return this; } public CassandraChatMemoryStore.BuilderAstra databaseRegion(String dbRegion) { this.dbRegion = dbRegion; return this; } public CassandraChatMemoryStore.BuilderAstra keyspace(String keyspaceName) { this.keyspaceName = keyspaceName; return this; } public CassandraChatMemoryStore.BuilderAstra table(String tableName) { this.tableName = tableName; return this; } public CassandraChatMemoryStore build() { CqlSession cqlSession = CassIO.init(token, dbId, dbRegion, keyspaceName, env); return new CassandraChatMemoryStore(cqlSession, tableName); } } }
try { return ChatMessageDeserializer.messageFromJson(record.getBody()); } catch (Exception e) { throw new IllegalArgumentException("Unable to parse message body", e); }
1,922
53
1,975
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-chatglm/src/main/java/dev/langchain4j/model/chatglm/ChatGlmChatModel.java
ChatGlmChatModel
generate
class ChatGlmChatModel implements ChatLanguageModel { private final ChatGlmClient client; private final Double temperature; private final Double topP; private final Integer maxLength; private final Integer maxRetries; @Builder public ChatGlmChatModel(String baseUrl, Duration timeout, Double temperature, Integer maxRetries, Double topP, Integer maxLength) { this.client = new ChatGlmClient(baseUrl, timeout); this.temperature = getOrDefault(temperature, 0.7); this.maxRetries = getOrDefault(maxRetries, 3); this.topP = topP; this.maxLength = maxLength; } @Override public Response<AiMessage> generate(List<ChatMessage> messages) {<FILL_FUNCTION_BODY>} private List<List<String>> toHistory(List<ChatMessage> historyMessages) { // Order: User - AI - User - AI ... // so the length of historyMessages must be divisible by 2 if (containsSystemMessage(historyMessages)) { throw new IllegalArgumentException("ChatGLM does not support system prompt"); } if (historyMessages.size() % 2 != 0) { throw new IllegalArgumentException("History must be divisible by 2 because it's order User - AI - User - AI ..."); } List<List<String>> history = new ArrayList<>(); for (int i = 0; i < historyMessages.size() / 2; i++) { history.add(historyMessages.subList(i * 2, i * 2 + 2).stream() .map(ChatMessage::text) .collect(Collectors.toList())); } return history; } private boolean containsSystemMessage(List<ChatMessage> messages) { return messages.stream().anyMatch(message -> message.type() == ChatMessageType.SYSTEM); } public static ChatGlmChatModelBuilder builder() { for (ChatGlmChatModelBuilderFactory factory : loadFactories(ChatGlmChatModelBuilderFactory.class)) { return factory.get(); } return new ChatGlmChatModelBuilder(); } public static class ChatGlmChatModelBuilder { public ChatGlmChatModelBuilder() { // This is public so it can be extended // By default with Lombok it becomes package private } } }
// get last user message String prompt = messages.get(messages.size() - 1).text(); List<List<String>> history = toHistory(messages.subList(0, messages.size() - 1)); ChatCompletionRequest request = ChatCompletionRequest.builder() .prompt(prompt) .temperature(temperature) .topP(topP) .maxLength(maxLength) .history(history) .build(); ChatCompletionResponse response = withRetry(() -> client.chatCompletion(request), maxRetries); return Response.from(AiMessage.from(response.getResponse()));
608
164
772
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-chatglm/src/main/java/dev/langchain4j/model/chatglm/ChatGlmClient.java
ChatGlmClient
toException
class ChatGlmClient { private final ChatGlmApi chatGLMApi; private static final Gson GSON = new GsonBuilder() .setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES) .create(); @Builder public ChatGlmClient(String baseUrl, Duration timeout) { timeout = getOrDefault(timeout, ofSeconds(60)); OkHttpClient okHttpClient = new OkHttpClient.Builder() .callTimeout(timeout) .connectTimeout(timeout) .readTimeout(timeout) .writeTimeout(timeout) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(GSON)) .build(); chatGLMApi = retrofit.create(ChatGlmApi.class); } public ChatCompletionResponse chatCompletion(ChatCompletionRequest request) { try { Response<ChatCompletionResponse> retrofitResponse = chatGLMApi.chatCompletion(request).execute(); if (retrofitResponse.isSuccessful() && retrofitResponse.body() != null && retrofitResponse.body().getStatus() == ChatGlmApi.OK) { return retrofitResponse.body(); } else { throw toException(retrofitResponse); } } catch (IOException e) { throw new RuntimeException(e); } } private RuntimeException toException(Response<?> response) throws IOException {<FILL_FUNCTION_BODY>} }
int code = response.code(); String body = response.errorBody().string(); String errorMessage = String.format("status code: %s; body: %s", code, body); return new RuntimeException(errorMessage);
417
60
477
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-chroma/src/main/java/dev/langchain4j/store/embedding/chroma/AddEmbeddingsRequest.java
Builder
embeddings
class Builder { private List<String> ids = new ArrayList<>(); private List<float[]> embeddings = new ArrayList<>(); private List<String> documents = new ArrayList<>(); private List<Map<String, String>> metadatas = new ArrayList<>(); public Builder ids(List<String> ids) { if (ids != null) { this.ids = ids; } return this; } public Builder embeddings(List<float[]> embeddings) {<FILL_FUNCTION_BODY>} public Builder documents(List<String> documents) { if (documents != null) { this.documents = documents; } return this; } public Builder metadatas(List<Map<String, String>> metadatas) { if (metadatas != null) { this.metadatas = metadatas; } return this; } AddEmbeddingsRequest build() { return new AddEmbeddingsRequest(this); } }
if (embeddings != null) { this.embeddings = embeddings; } return this;
280
32
312
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-chroma/src/main/java/dev/langchain4j/store/embedding/chroma/ChromaClient.java
ChromaClient
toException
class ChromaClient { private final ChromaApi chromaApi; ChromaClient(String baseUrl, Duration timeout) { OkHttpClient okHttpClient = new OkHttpClient.Builder() .callTimeout(timeout) .connectTimeout(timeout) .readTimeout(timeout) .writeTimeout(timeout) .build(); Gson gson = new GsonBuilder() .setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES) .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); this.chromaApi = retrofit.create(ChromaApi.class); } Collection createCollection(CreateCollectionRequest createCollectionRequest) { try { Response<Collection> response = chromaApi.createCollection(createCollectionRequest).execute(); if (response.isSuccessful()) { return response.body(); } else { throw toException(response); } } catch (IOException e) { throw new RuntimeException(e); } } Collection collection(String collectionName) { try { Response<Collection> response = chromaApi.collection(collectionName).execute(); if (response.isSuccessful()) { return response.body(); } else { // if collection is not present, Chroma returns: Status - 500 return null; } } catch (IOException e) { throw new RuntimeException(e); } } boolean addEmbeddings(String collectionId, AddEmbeddingsRequest addEmbeddingsRequest) { try { Response<Boolean> retrofitResponse = chromaApi.addEmbeddings(collectionId, addEmbeddingsRequest) .execute(); if (retrofitResponse.isSuccessful()) { return Boolean.TRUE.equals(retrofitResponse.body()); } else { throw toException(retrofitResponse); } } catch (IOException e) { throw new RuntimeException(e); } } QueryResponse queryCollection(String collectionId, QueryRequest queryRequest) { try { Response<QueryResponse> retrofitResponse = chromaApi.queryCollection(collectionId, queryRequest) .execute(); if (retrofitResponse.isSuccessful()) { return retrofitResponse.body(); } else { throw toException(retrofitResponse); } } catch (IOException e) { throw new RuntimeException(e); } } private static RuntimeException toException(Response<?> response) throws IOException {<FILL_FUNCTION_BODY>} }
int code = response.code(); String body = response.errorBody().string(); String errorMessage = String.format("status code: %s; body: %s", code, body); return new RuntimeException(errorMessage);
709
61
770
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-chroma/src/main/java/dev/langchain4j/store/embedding/chroma/ChromaEmbeddingStore.java
Builder
addAll
class Builder { private String baseUrl; private String collectionName; private Duration timeout; /** * @param baseUrl The base URL of the Chroma service. * @return builder */ public Builder baseUrl(String baseUrl) { this.baseUrl = baseUrl; return this; } /** * @param collectionName The name of the collection in the Chroma service. If not specified, "default" will be used. * @return builder */ public Builder collectionName(String collectionName) { this.collectionName = collectionName; return this; } /** * @param timeout The timeout duration for the Chroma client. If not specified, 5 seconds will be used. * @return builder */ public Builder timeout(Duration timeout) { this.timeout = timeout; return this; } public ChromaEmbeddingStore build() { return new ChromaEmbeddingStore(this.baseUrl, this.collectionName, this.timeout); } } @Override public String add(Embedding embedding) { String id = randomUUID(); add(id, embedding); return id; } @Override public void add(String id, Embedding embedding) { addInternal(id, embedding, null); } @Override public String add(Embedding embedding, TextSegment textSegment) { String id = randomUUID(); addInternal(id, embedding, textSegment); return id; } @Override public List<String> addAll(List<Embedding> embeddings) { List<String> ids = embeddings.stream() .map(embedding -> randomUUID()) .collect(toList()); addAllInternal(ids, embeddings, null); return ids; } @Override public List<String> addAll(List<Embedding> embeddings, List<TextSegment> textSegments) {<FILL_FUNCTION_BODY>
List<String> ids = embeddings.stream() .map(embedding -> randomUUID()) .collect(toList()); addAllInternal(ids, embeddings, textSegments); return ids;
524
61
585
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-cohere/src/main/java/dev/langchain4j/model/cohere/CohereClient.java
CohereClient
toException
class CohereClient { private static final Gson GSON = new GsonBuilder() .setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES) .setPrettyPrinting() .create(); private final CohereApi cohereApi; private final String authorizationHeader; @Builder CohereClient(String baseUrl, String apiKey, Duration timeout, Boolean logRequests, Boolean logResponses) { OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder() .callTimeout(timeout) .connectTimeout(timeout) .readTimeout(timeout) .writeTimeout(timeout); if (logRequests) { okHttpClientBuilder.addInterceptor(new RequestLoggingInterceptor()); } if (logResponses) { okHttpClientBuilder.addInterceptor(new ResponseLoggingInterceptor()); } Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClientBuilder.build()) .addConverterFactory(GsonConverterFactory.create(GSON)) .build(); this.cohereApi = retrofit.create(CohereApi.class); this.authorizationHeader = "Bearer " + ensureNotBlank(apiKey, "apiKey"); } public RerankResponse rerank(RerankRequest request) { try { retrofit2.Response<RerankResponse> retrofitResponse = cohereApi.rerank(request, authorizationHeader).execute(); if (retrofitResponse.isSuccessful()) { return retrofitResponse.body(); } else { throw toException(retrofitResponse); } } catch (IOException e) { throw new RuntimeException(e); } } private static RuntimeException toException(retrofit2.Response<?> response) throws IOException {<FILL_FUNCTION_BODY>} }
int code = response.code(); String body = response.errorBody().string(); String errorMessage = String.format("status code: %s; body: %s", code, body); return new RuntimeException(errorMessage);
500
59
559
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-cohere/src/main/java/dev/langchain4j/model/cohere/CohereScoringModel.java
CohereScoringModel
scoreAll
class CohereScoringModel implements ScoringModel { private static final String DEFAULT_BASE_URL = "https://api.cohere.ai/v1/"; private final CohereClient client; private final String modelName; private final Integer maxRetries; @Builder public CohereScoringModel( String baseUrl, String apiKey, String modelName, Duration timeout, Integer maxRetries, Boolean logRequests, Boolean logResponses ) { this.client = CohereClient.builder() .baseUrl(getOrDefault(baseUrl, DEFAULT_BASE_URL)) .apiKey(ensureNotBlank(apiKey, "apiKey")) .timeout(getOrDefault(timeout, ofSeconds(60))) .logRequests(getOrDefault(logRequests, false)) .logResponses(getOrDefault(logResponses, false)) .build(); this.modelName = modelName; this.maxRetries = getOrDefault(maxRetries, 3); } public static CohereScoringModel withApiKey(String apiKey) { return CohereScoringModel.builder().apiKey(apiKey).build(); } @Override public Response<List<Double>> scoreAll(List<TextSegment> segments, String query) {<FILL_FUNCTION_BODY>} }
RerankRequest request = RerankRequest.builder() .model(modelName) .query(query) .documents(segments.stream() .map(TextSegment::text) .collect(toList())) .build(); RerankResponse response = withRetry(() -> client.rerank(request), maxRetries); List<Double> scores = response.getResults().stream() .sorted(comparingInt(Result::getIndex)) .map(Result::getRelevanceScore) .collect(toList()); return Response.from(scores, new TokenUsage(response.getMeta().getBilledUnits().getSearchUnits()));
352
179
531
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-cohere/src/main/java/dev/langchain4j/model/cohere/RequestLoggingInterceptor.java
RequestLoggingInterceptor
inOneLine
class RequestLoggingInterceptor implements Interceptor { private static final Logger log = LoggerFactory.getLogger(RequestLoggingInterceptor.class); private static final Pattern BEARER_PATTERN = Pattern.compile("(Bearer\\s)(\\w{2})(\\w+)(\\w{2})"); public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); log(request); return chain.proceed(request); } private void log(Request request) { log.debug( "Request:\n" + "- method: {}\n" + "- url: {}\n" + "- headers: {}\n" + "- body: {}", request.method(), request.url(), inOneLine(request.headers()), getBody(request) ); } static String inOneLine(Headers headers) {<FILL_FUNCTION_BODY>} private static String maskAuthorizationHeaderValue(String authorizationHeaderValue) { try { Matcher matcher = BEARER_PATTERN.matcher(authorizationHeaderValue); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, matcher.group(1) + matcher.group(2) + "..." + matcher.group(4)); } matcher.appendTail(sb); return sb.toString(); } catch (Exception e) { return "[failed to mask the API key]"; } } private static String getBody(Request request) { try { Buffer buffer = new Buffer(); request.body().writeTo(buffer); return buffer.readUtf8(); } catch (Exception e) { log.warn("Exception happened while reading request body", e); return "[Exception happened while reading request body. Check logs for more details.]"; } } }
return stream(headers.spliterator(), false) .map((header) -> { String headerKey = header.component1(); String headerValue = header.component2(); if (headerKey.equals("Authorization")) { headerValue = maskAuthorizationHeaderValue(headerValue); } return String.format("[%s: %s]", headerKey, headerValue); }).collect(Collectors.joining(", "));
501
113
614
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-cohere/src/main/java/dev/langchain4j/model/cohere/ResponseLoggingInterceptor.java
ResponseLoggingInterceptor
getBody
class ResponseLoggingInterceptor implements Interceptor { private static final Logger log = LoggerFactory.getLogger(ResponseLoggingInterceptor.class); public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); log(response); return response; } void log(Response response) { log.debug( "Response:\n" + "- status code: {}\n" + "- headers: {}\n" + "- body: {}", response.code(), inOneLine(response.headers()), getBody(response) ); } private String getBody(Response response) {<FILL_FUNCTION_BODY>} }
try { return response.peekBody(Long.MAX_VALUE).string(); } catch (IOException e) { log.warn("Failed to log response", e); return "[failed to log response]"; }
199
59
258
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/agent/tool/JsonSchemaProperty.java
JsonSchemaProperty
enums
class JsonSchemaProperty { /** * A property with key "type" and value "string". */ public static final JsonSchemaProperty STRING = type("string"); /** * A property with key "type" and value "integer". */ public static final JsonSchemaProperty INTEGER = type("integer"); /** * A property with key "type" and value "number". */ public static final JsonSchemaProperty NUMBER = type("number"); /** * A property with key "type" and value "object". */ public static final JsonSchemaProperty OBJECT = type("object"); /** * A property with key "type" and value "array". */ public static final JsonSchemaProperty ARRAY = type("array"); /** * A property with key "type" and value "boolean". */ public static final JsonSchemaProperty BOOLEAN = type("boolean"); /** * A property with key "type" and value "null". */ public static final JsonSchemaProperty NULL = type("null"); private final String key; private final Object value; /** * Construct a property with key and value. * * @param key the key. * @param value the value. */ public JsonSchemaProperty(String key, Object value) { this.key = key; this.value = value; } /** * Get the key. * * @return the key. */ public String key() { return key; } /** * Get the value. * * @return the value. */ public Object value() { return value; } @Override public boolean equals(Object another) { if (this == another) return true; return another instanceof JsonSchemaProperty && equalTo((JsonSchemaProperty) another); } /** * Utility method to compare two {@link JsonSchemaProperty} instances. * * @param another the other instance. * @return true if the two instances are equal. */ private boolean equalTo(JsonSchemaProperty another) { if (!Objects.equals(key, another.key)) return false; if (value instanceof Object[] && another.value instanceof Object[]) { return Arrays.equals((Object[]) value, (Object[]) another.value); } return Objects.equals(value, another.value); } @Override public int hashCode() { int h = 5381; h += (h << 5) + Objects.hashCode(key); int v = (value instanceof Object[]) ? Arrays.hashCode((Object[]) value) : Objects.hashCode(value); h += (h << 5) + v; return h; } @Override public String toString() { String valueString = (value instanceof Object[]) ? Arrays.toString((Object[]) value) : value.toString(); return "JsonSchemaProperty {" + " key = " + quoted(key) + ", value = " + valueString + " }"; } /** * Construct a property with key and value. * * <p>Equivalent to {@code new JsonSchemaProperty(key, value)}. * * @param key the key. * @param value the value. * @return a property with key and value. */ public static JsonSchemaProperty from(String key, Object value) { return new JsonSchemaProperty(key, value); } /** * Construct a property with key and value. * * <p>Equivalent to {@code new JsonSchemaProperty(key, value)}. * * @param key the key. * @param value the value. * @return a property with key and value. */ public static JsonSchemaProperty property(String key, Object value) { return from(key, value); } /** * Construct a property with key "type" and value. * * <p>Equivalent to {@code new JsonSchemaProperty("type", value)}. * * @param value the value. * @return a property with key and value. */ public static JsonSchemaProperty type(String value) { return from("type", value); } /** * Construct a property with key "description" and value. * * <p>Equivalent to {@code new JsonSchemaProperty("description", value)}. * * @param value the value. * @return a property with key and value. */ public static JsonSchemaProperty description(String value) { return from("description", value); } /** * Construct a property with key "enum" and value enumValues. * * @param enumValues enum values as strings. For example: {@code enums("CELSIUS", "FAHRENHEIT")} * @return a property with key "enum" and value enumValues */ public static JsonSchemaProperty enums(String... enumValues) { return from("enum", enumValues); } /** * Construct a property with key "enum" and value enumValues. * * <p>Verifies that each value is a java class. * * @param enumValues enum values. For example: {@code enums(TemperatureUnit.CELSIUS, TemperatureUnit.FAHRENHEIT)} * @return a property with key "enum" and value enumValues */ public static JsonSchemaProperty enums(Object... enumValues) {<FILL_FUNCTION_BODY>} /** * Construct a property with key "enum" and all enum values taken from enumClass. * * @param enumClass enum class. For example: {@code enums(TemperatureUnit.class)} * @return a property with key "enum" and values taken from enumClass */ public static JsonSchemaProperty enums(Class<?> enumClass) { if (!enumClass.isEnum()) { throw new RuntimeException("Class " + enumClass.getName() + " should be enum"); } return enums((Object[]) enumClass.getEnumConstants()); } /** * Wraps the given type in a property with key "items". * * @param type the type * @return a property with key "items" and value type. */ public static JsonSchemaProperty items(JsonSchemaProperty type) { return from("items", singletonMap(type.key, type.value)); } }
List<String> enumNames = new ArrayList<>(); for (Object enumValue : enumValues) { if (!enumValue.getClass().isEnum()) { throw new RuntimeException("Value " + enumValue.getClass().getName() + " should be enum"); } enumNames.add(((Enum<?>) enumValue).name()); } return from("enum", enumNames);
1,659
100
1,759
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/agent/tool/ToolExecutionRequest.java
ToolExecutionRequest
equals
class ToolExecutionRequest { private final String id; private final String name; private final String arguments; /** * Creates a {@link ToolExecutionRequest} from a {@link Builder}. * @param builder the builder. */ private ToolExecutionRequest(Builder builder) { this.id = builder.id; this.name = builder.name; this.arguments = builder.arguments; } /** * Returns the id of the tool. * @return the id of the tool. */ public String id() { return id; } /** * Returns the name of the tool. * @return the name of the tool. */ public String name() { return name; } /** * Returns the arguments of the tool. * @return the arguments of the tool. */ public String arguments() { return arguments; } @Override public boolean equals(Object another) {<FILL_FUNCTION_BODY>} private boolean equalTo(ToolExecutionRequest another) { return Objects.equals(id, another.id) && Objects.equals(name, another.name) && Objects.equals(arguments, another.arguments); } @Override public int hashCode() { int h = 5381; h += (h << 5) + Objects.hashCode(id); h += (h << 5) + Objects.hashCode(name); h += (h << 5) + Objects.hashCode(arguments); return h; } @Override public String toString() { return "ToolExecutionRequest {" + " id = " + quoted(id) + ", name = " + quoted(name) + ", arguments = " + quoted(arguments) + " }"; } /** * Creates builder to build {@link ToolExecutionRequest}. * @return created builder */ public static Builder builder() { return new Builder(); } /** * {@code ToolExecutionRequest} builder static inner class. */ public static final class Builder { private String id; private String name; private String arguments; /** * Creates a builder for {@code ToolExecutionRequest}. */ private Builder() { } /** * Sets the {@code id}. * @param id the {@code id} * @return the {@code Builder} */ public Builder id(String id) { this.id = id; return this; } /** * Sets the {@code name}. * @param name the {@code name} * @return the {@code Builder} */ public Builder name(String name) { this.name = name; return this; } /** * Sets the {@code arguments}. * @param arguments the {@code arguments} * @return the {@code Builder} */ public Builder arguments(String arguments) { this.arguments = arguments; return this; } /** * Returns a {@code ToolExecutionRequest} built from the parameters previously set. * @return a {@code ToolExecutionRequest} */ public ToolExecutionRequest build() { return new ToolExecutionRequest(this); } } }
if (this == another) return true; return another instanceof ToolExecutionRequest && equalTo((ToolExecutionRequest) another);
846
34
880
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/agent/tool/ToolExecutionRequestUtil.java
ToolExecutionRequestUtil
argument
class ToolExecutionRequestUtil { private ToolExecutionRequestUtil() {} /** * Gson instance. */ public static final Gson GSON = new Gson(); /** * Utility {@link TypeToken} describing {@code Map<String, Object>}. */ public static final Type MAP_TYPE = new TypeToken<Map<String, Object>>() { }.getType(); /** * Get an argument value from ToolExecutionRequest. * @param toolExecutionRequest request * @param name argument name * @return argument value * @param <T> the argument type */ public static <T> T argument(ToolExecutionRequest toolExecutionRequest, String name) {<FILL_FUNCTION_BODY>} /** * Convert arguments to map. * @param arguments json string * @return map */ public static Map<String, Object> argumentsAsMap(String arguments) { return GSON.fromJson(arguments, MAP_TYPE); } }
Map<String, Object> arguments = argumentsAsMap(toolExecutionRequest.arguments()); // TODO cache @SuppressWarnings("unchecked") T res = (T) arguments.get(name); return res;
255
57
312
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/agent/tool/ToolParameters.java
ToolParameters
toString
class ToolParameters { private final String type; private final Map<String, Map<String, Object>> properties; private final List<String> required; /** * Creates a {@link ToolParameters} from a {@link Builder}. * @param builder the builder. */ private ToolParameters(Builder builder) { this.type = builder.type; this.properties = builder.properties; this.required = builder.required; } /** * Returns the type of the tool. * @return the type of the tool. */ public String type() { return type; } /** * Returns the properties of the tool. * @return the properties of the tool. */ public Map<String, Map<String, Object>> properties() { return properties; } /** * Returns the required properties of the tool. * @return the required properties of the tool. */ public List<String> required() { return required; } @Override public boolean equals(Object another) { if (this == another) return true; return another instanceof ToolParameters && equalTo((ToolParameters) another); } /** * Utility method to compare two {@link ToolParameters}. * @param another the other {@link ToolParameters}. * @return true if equal, false otherwise. */ private boolean equalTo(ToolParameters another) { return Objects.equals(type, another.type) && Objects.equals(properties, another.properties) && Objects.equals(required, another.required); } @Override public int hashCode() { int h = 5381; h += (h << 5) + Objects.hashCode(type); h += (h << 5) + Objects.hashCode(properties); h += (h << 5) + Objects.hashCode(required); return h; } @Override public String toString() {<FILL_FUNCTION_BODY>} /** * ToolParameters builder static inner class. * @return a {@link Builder}. */ public static Builder builder() { return new Builder(); } /** * {@code ToolParameters} builder static inner class. */ public static final class Builder { private String type = "object"; private Map<String, Map<String, Object>> properties = new HashMap<>(); private List<String> required = new ArrayList<>(); /** * Creates a {@link Builder}. */ private Builder() { } /** * Sets the {@code type}. * @param type the {@code type} * @return the {@code Builder}. */ public Builder type(String type) { this.type = type; return this; } /** * Sets the {@code properties}. * @param properties the {@code properties} * @return the {@code Builder}. */ public Builder properties(Map<String, Map<String, Object>> properties) { this.properties = properties; return this; } /** * Sets the {@code required}. * @param required the {@code required} * @return the {@code Builder}. */ public Builder required(List<String> required) { this.required = required; return this; } /** * Returns a {@code ToolParameters} built from the parameters previously set. * @return a {@code ToolParameters} built with parameters of this {@code ToolParameters.Builder} */ public ToolParameters build() { return new ToolParameters(this); } } }
return "ToolParameters {" + " type = " + quoted(type) + ", properties = " + properties + ", required = " + required + " }";
930
46
976
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/agent/tool/ToolSpecification.java
Builder
addOptionalParameter
class Builder { private String name; private String description; private ToolParameters parameters; /** * Creates a {@link Builder}. */ private Builder() { } /** * Sets the {@code name}. * @param name the {@code name} * @return {@code this} */ public Builder name(String name) { this.name = name; return this; } /** * Sets the {@code description}. * @param description the {@code description} * @return {@code this} */ public Builder description(String description) { this.description = description; return this; } /** * Sets the {@code parameters}. * @param parameters the {@code parameters} * @return {@code this} */ public Builder parameters(ToolParameters parameters) { this.parameters = parameters; return this; } /** * Adds a parameter to the tool. * @param name the name of the parameter. * @param jsonSchemaProperties the properties of the parameter. * @return {@code this} */ public Builder addParameter(String name, JsonSchemaProperty... jsonSchemaProperties) { return addParameter(name, asList(jsonSchemaProperties)); } /** * Adds a parameter to the tool. * @param name the name of the parameter. * @param jsonSchemaProperties the properties of the parameter. * @return {@code this} */ public Builder addParameter(String name, Iterable<JsonSchemaProperty> jsonSchemaProperties) { addOptionalParameter(name, jsonSchemaProperties); this.parameters.required().add(name); return this; } /** * Adds an optional parameter to the tool. * @param name the name of the parameter. * @param jsonSchemaProperties the properties of the parameter. * @return {@code this} */ public Builder addOptionalParameter(String name, JsonSchemaProperty... jsonSchemaProperties) { return addOptionalParameter(name, asList(jsonSchemaProperties)); } /** * Adds an optional parameter to the tool. * @param name the name of the parameter. * @param jsonSchemaProperties the properties of the parameter. * @return {@code this} */ public Builder addOptionalParameter(String name, Iterable<JsonSchemaProperty> jsonSchemaProperties) {<FILL_FUNCTION_BODY>} /** * Returns a {@code ToolSpecification} built from the parameters previously set. * @return a {@code ToolSpecification} built with parameters of this {@code ToolSpecification.Builder} */ public ToolSpecification build() { return new ToolSpecification(this); } }
if (this.parameters == null) { this.parameters = ToolParameters.builder().build(); } Map<String, Object> jsonSchemaPropertiesMap = new HashMap<>(); for (JsonSchemaProperty jsonSchemaProperty : jsonSchemaProperties) { jsonSchemaPropertiesMap.put(jsonSchemaProperty.key(), jsonSchemaProperty.value()); } this.parameters.properties().put(name, jsonSchemaPropertiesMap); return this;
691
112
803
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/agent/tool/ToolSpecifications.java
ToolSpecifications
arrayTypeFrom
class ToolSpecifications { private ToolSpecifications() { } /** * Returns {@link ToolSpecification}s for all methods annotated with @{@link Tool} within the specified class. * * @param classWithTools the class. * @return the {@link ToolSpecification}s. */ public static List<ToolSpecification> toolSpecificationsFrom(Class<?> classWithTools) { return stream(classWithTools.getDeclaredMethods()) .filter(method -> method.isAnnotationPresent(Tool.class)) .map(ToolSpecifications::toolSpecificationFrom) .collect(toList()); } /** * Returns {@link ToolSpecification}s for all methods annotated with @{@link Tool} * within the class of the specified object. * * @param objectWithTools the object. * @return the {@link ToolSpecification}s. */ public static List<ToolSpecification> toolSpecificationsFrom(Object objectWithTools) { return toolSpecificationsFrom(objectWithTools.getClass()); } /** * Returns the {@link ToolSpecification} for the given method annotated with @{@link Tool}. * * @param method the method. * @return the {@link ToolSpecification}. */ public static ToolSpecification toolSpecificationFrom(Method method) { Tool annotation = method.getAnnotation(Tool.class); String name = isNullOrBlank(annotation.name()) ? method.getName() : annotation.name(); String description = String.join("\n", annotation.value()); // TODO provide null instead of "" ? ToolSpecification.Builder builder = ToolSpecification.builder() .name(name) .description(description); for (Parameter parameter : method.getParameters()) { if (parameter.isAnnotationPresent(ToolMemoryId.class)) { continue; } builder.addParameter(parameter.getName(), toJsonSchemaProperties(parameter)); } return builder.build(); } /** * Convert a {@link Parameter} to a {@link JsonSchemaProperty}. * * @param parameter the parameter. * @return the {@link JsonSchemaProperty}. */ static Iterable<JsonSchemaProperty> toJsonSchemaProperties(Parameter parameter) { Class<?> type = parameter.getType(); P annotation = parameter.getAnnotation(P.class); JsonSchemaProperty description = annotation == null ? null : description(annotation.value()); if (type == String.class) { return removeNulls(STRING, description); } if (isBoolean(type)) { return removeNulls(BOOLEAN, description); } if (isInteger(type)) { return removeNulls(INTEGER, description); } if (isNumber(type)) { return removeNulls(NUMBER, description); } if (type.isArray()) { return removeNulls(ARRAY, arrayTypeFrom(type.getComponentType()), description); } if (Collection.class.isAssignableFrom(type)) { return removeNulls(ARRAY, arrayTypeFrom(parameter.getParameterizedType()), description); } if (type.isEnum()) { return removeNulls(STRING, enums((Class<?>) type), description); } return removeNulls(OBJECT, description); // TODO provide internals } private static JsonSchemaProperty arrayTypeFrom(Type type) {<FILL_FUNCTION_BODY>} // TODO put constraints on min and max? private static boolean isNumber(Class<?> type) { return type == float.class || type == Float.class || type == double.class || type == Double.class || type == BigDecimal.class; } private static boolean isInteger(Class<?> type) { return type == byte.class || type == Byte.class || type == short.class || type == Short.class || type == int.class || type == Integer.class || type == long.class || type == Long.class || type == BigInteger.class; } private static boolean isBoolean(Class<?> type) { return type == boolean.class || type == Boolean.class; } private static JsonSchemaProperty arrayTypeFrom(Class<?> clazz) { if (clazz == String.class) { return items(JsonSchemaProperty.STRING); } if (isBoolean(clazz)) { return items(JsonSchemaProperty.BOOLEAN); } if (isInteger(clazz)) { return items(JsonSchemaProperty.INTEGER); } if (isNumber(clazz)) { return items(JsonSchemaProperty.NUMBER); } return items(JsonSchemaProperty.OBJECT); } /** * Remove nulls from the given array. * * @param items the array * @return an iterable of the non-null items. */ static Iterable<JsonSchemaProperty> removeNulls(JsonSchemaProperty... items) { return stream(items) .filter(Objects::nonNull) .collect(toList()); } }
if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments.length == 1) { return arrayTypeFrom((Class<?>) actualTypeArguments[0]); } } return items(JsonSchemaProperty.OBJECT);
1,316
98
1,414
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/data/document/Document.java
Document
equals
class Document { /** * Common metadata key for the name of the file from which the document was loaded. */ public static final String FILE_NAME = "file_name"; /** * Common metadata key for the absolute path of the directory from which the document was loaded. */ public static final String ABSOLUTE_DIRECTORY_PATH = "absolute_directory_path"; /** * Common metadata key for the URL from which the document was loaded. */ public static final String URL = "url"; private final String text; private final Metadata metadata; /** * Creates a new Document from the given text. * * <p>The created document will have empty metadata. * * @param text the text of the document. */ public Document(String text) { this(text, new Metadata()); } /** * Creates a new Document from the given text. * * @param text the text of the document. * @param metadata the metadata of the document. */ public Document(String text, Metadata metadata) { this.text = ensureNotBlank(text, "text"); this.metadata = ensureNotNull(metadata, "metadata"); } /** * Returns the text of this document. * * @return the text. */ public String text() { return text; } /** * Returns the metadata associated with this document. * * @return the metadata. */ public Metadata metadata() { return metadata; } /** * Looks up the metadata value for the given key. * * @param key the key to look up. * @return the metadata value for the given key, or null if the key is not present. */ // TODO deprecate once the new experimental API is settled public String metadata(String key) { return metadata.get(key); } /** * Builds a TextSegment from this document. * * @return a TextSegment. */ public TextSegment toTextSegment() { return TextSegment.from(text, metadata.copy().add("index", "0")); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(text, metadata); } @Override public String toString() { return "Document {" + " text = " + quoted(text) + " metadata = " + metadata.asMap() + " }"; } /** * Creates a new Document from the given text. * * <p>The created document will have empty metadata.</p> * * @param text the text of the document. * @return a new Document. */ public static Document from(String text) { return new Document(text); } /** * Creates a new Document from the given text. * * @param text the text of the document. * @param metadata the metadata of the document. * @return a new Document. */ public static Document from(String text, Metadata metadata) { return new Document(text, metadata); } /** * Creates a new Document from the given text. * * <p>The created document will have empty metadata.</p> * * @param text the text of the document. * @return a new Document. */ public static Document document(String text) { return from(text); } /** * Creates a new Document from the given text. * * @param text the text of the document. * @param metadata the metadata of the document. * @return a new Document. */ public static Document document(String text, Metadata metadata) { return from(text, metadata); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Document that = (Document) o; return Objects.equals(this.text, that.text) && Objects.equals(this.metadata, that.metadata);
1,012
77
1,089
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/data/document/DocumentLoader.java
DocumentLoader
load
class DocumentLoader { private DocumentLoader() { } /** * Loads a document from the given source using the given parser. * * <p>Forwards the source Metadata to the parsed Document. * * @param source The source from which the document will be loaded. * @param parser The parser that will be used to parse the document. * @return The loaded document. * @throws BlankDocumentException when the parsed {@link Document} is blank/empty. */ public static Document load(DocumentSource source, DocumentParser parser) {<FILL_FUNCTION_BODY>} }
try (InputStream inputStream = source.inputStream()) { Document document = parser.parse(inputStream); source.metadata().asMap().forEach((key, value) -> document.metadata().add(key, value)); return document; } catch (BlankDocumentException e) { throw e; } catch (Exception e) { throw new RuntimeException("Failed to load document", e); }
155
104
259
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/data/embedding/Embedding.java
Embedding
equals
class Embedding { private final float[] vector; /** * Creates a new Embedding. * @param vector the vector, takes ownership of the array. */ public Embedding(float[] vector) { this.vector = ensureNotNull(vector, "vector"); } /** * Returns the vector. * @return the vector. */ public float[] vector() { return vector; } /** * Returns a copy of the vector as a list. * @return the vector as a list. */ public List<Float> vectorAsList() { List<Float> list = new ArrayList<>(vector.length); for (float f : vector) { list.add(f); } return list; } /** * Normalize vector */ public void normalize() { double norm = 0.0; for (float f : vector) { norm += f * f; } norm = Math.sqrt(norm); for (int i = 0; i < vector.length; i++) { vector[i] /= norm; } } /** * Returns the dimension of the vector. * @return the dimension of the vector. */ public int dimension() { return vector.length; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Arrays.hashCode(vector); } @Override public String toString() { return "Embedding {" + " vector = " + Arrays.toString(vector) + " }"; } /** * Creates a new Embedding from the given vector. * @param vector the vector, takes ownership of the array. * @return the new Embedding. */ public static Embedding from(float[] vector) { return new Embedding(vector); } /** * Creates a new Embedding from the given vector. * @param vector the vector. * @return the new Embedding. */ public static Embedding from(List<Float> vector) { float[] array = new float[vector.size()]; for (int i = 0; i < vector.size(); i++) { array[i] = vector.get(i); } return new Embedding(array); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Embedding that = (Embedding) o; return Arrays.equals(this.vector, that.vector);
630
64
694
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/data/image/Image.java
Image
toString
class Image { private final URI url; private final String base64Data; private final String mimeType; private final String revisedPrompt; /** * Create a new {@link Image} from the Builder. * @param builder the builder. */ private Image(Builder builder) { this.url = builder.url; this.base64Data = builder.base64Data; this.mimeType = builder.mimeType; this.revisedPrompt = builder.revisedPrompt; } /** * Create a new {@link Builder}. * @return the new {@link Builder}. */ public static Builder builder() { return new Builder(); } /** * Get the url of the image. * @return the url of the image, or null if not set. */ public URI url() { return url; } /** * Get the base64 data of the image. * @return the base64 data of the image, or null if not set. */ public String base64Data() { return base64Data; } /** * Get the mime type of the image. * @return the mime type of the image, or null if not set. */ public String mimeType() { return mimeType; } /** * Get the revised prompt of the image. * @return the revised prompt of the image, or null if not set. */ public String revisedPrompt() { return revisedPrompt; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Image that = (Image) o; return Objects.equals(this.url, that.url) && Objects.equals(this.base64Data, that.base64Data) && Objects.equals(this.mimeType, that.mimeType) && Objects.equals(this.revisedPrompt, that.revisedPrompt); } @Override public int hashCode() { return Objects.hash(url, base64Data, mimeType, revisedPrompt); } @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Builder for {@link Image}. */ public static class Builder { private URI url; private String base64Data; private String mimeType; private String revisedPrompt; /** * Create a new {@link Builder}. */ public Builder() {} /** * Set the url of the image. * @param url the url of the image. * @return {@code this} */ public Builder url(URI url) { this.url = url; return this; } /** * Set the url of the image. * @param url the url of the image. * @return {@code this} */ public Builder url(String url) { return url(URI.create(url)); } /** * Set the base64 data of the image. * @param base64Data the base64 data of the image. * @return {@code this} */ public Builder base64Data(String base64Data) { this.base64Data = base64Data; return this; } /** * Set the mime type of the image. * @param mimeType the mime type of the image. * @return {@code this} */ public Builder mimeType(String mimeType) { this.mimeType = mimeType; return this; } /** * Set the revised prompt of the image. * @param revisedPrompt the revised prompt of the image. * @return {@code this} */ public Builder revisedPrompt(String revisedPrompt) { this.revisedPrompt = revisedPrompt; return this; } /** * Build the {@link Image}. * @return the {@link Image}. */ public Image build() { return new Image(this); } } }
return "Image {" + " url = " + quoted(url) + ", base64Data = " + quoted(base64Data) + ", mimeType = " + quoted(mimeType) + ", revisedPrompt = " + quoted(revisedPrompt) + " }";
1,115
79
1,194
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/data/message/AiMessage.java
AiMessage
equals
class AiMessage implements ChatMessage { private final String text; private final List<ToolExecutionRequest> toolExecutionRequests; /** * Create a new {@link AiMessage} with the given text. * * @param text the text of the message. */ public AiMessage(String text) { this.text = ensureNotNull(text, "text"); this.toolExecutionRequests = null; } /** * Create a new {@link AiMessage} with the given tool execution requests. * * @param toolExecutionRequests the tool execution requests of the message. */ public AiMessage(List<ToolExecutionRequest> toolExecutionRequests) { this.text = null; this.toolExecutionRequests = ensureNotEmpty(toolExecutionRequests, "toolExecutionRequests"); } /** * Create a new {@link AiMessage} with the given text and tool execution requests. * * @param text the text of the message. * @param toolExecutionRequests the tool execution requests of the message. */ public AiMessage(String text, List<ToolExecutionRequest> toolExecutionRequests) { this.text = ensureNotBlank(text, "text"); this.toolExecutionRequests = ensureNotEmpty(toolExecutionRequests, "toolExecutionRequests"); } /** * Get the text of the message. * * @return the text of the message. */ public String text() { return text; } /** * Get the tool execution requests of the message. * * @return the tool execution requests of the message. */ public List<ToolExecutionRequest> toolExecutionRequests() { return toolExecutionRequests; } /** * Check if the message has ToolExecutionRequests. * * @return true if the message has ToolExecutionRequests, false otherwise. */ public boolean hasToolExecutionRequests() { return !isNullOrEmpty(toolExecutionRequests); } @Override public ChatMessageType type() { return AI; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(text, toolExecutionRequests); } @Override public String toString() { return "AiMessage {" + " text = " + quoted(text) + " toolExecutionRequests = " + toolExecutionRequests + " }"; } /** * Create a new {@link AiMessage} with the given text. * * @param text the text of the message. * @return the new {@link AiMessage}. */ public static AiMessage from(String text) { return new AiMessage(text); } /** * Create a new {@link AiMessage} with the given tool execution requests. * * @param toolExecutionRequests the tool execution requests of the message. * @return the new {@link AiMessage}. */ public static AiMessage from(ToolExecutionRequest... toolExecutionRequests) { return from(asList(toolExecutionRequests)); } /** * Create a new {@link AiMessage} with the given tool execution requests. * * @param toolExecutionRequests the tool execution requests of the message. * @return the new {@link AiMessage}. */ public static AiMessage from(List<ToolExecutionRequest> toolExecutionRequests) { return new AiMessage(toolExecutionRequests); } /** * Create a new {@link AiMessage} with the given text. * * @param text the text of the message. * @return the new {@link AiMessage}. */ public static AiMessage aiMessage(String text) { return from(text); } /** * Create a new {@link AiMessage} with the given tool execution requests. * * @param toolExecutionRequests the tool execution requests of the message. * @return the new {@link AiMessage}. */ public static AiMessage aiMessage(ToolExecutionRequest... toolExecutionRequests) { return aiMessage(asList(toolExecutionRequests)); } /** * Create a new {@link AiMessage} with the given tool execution requests. * * @param toolExecutionRequests the tool execution requests of the message. * @return the new {@link AiMessage}. */ public static AiMessage aiMessage(List<ToolExecutionRequest> toolExecutionRequests) { return from(toolExecutionRequests); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AiMessage that = (AiMessage) o; return Objects.equals(this.text, that.text) && Objects.equals(this.toolExecutionRequests, that.toolExecutionRequests);
1,189
87
1,276
<no_super_class>
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/data/message/ChatMessageSerializer.java
ChatMessageSerializer
loadCodec
class ChatMessageSerializer { static final ChatMessageJsonCodec CODEC = loadCodec(); private static ChatMessageJsonCodec loadCodec() {<FILL_FUNCTION_BODY>} /** * Serializes a chat message into a JSON string. * * @param message Chat message to be serialized. * @return A JSON string with the contents of the message. * @see ChatMessageDeserializer For details on deserialization. */ public static String messageToJson(ChatMessage message) { return CODEC.messageToJson(message); } /** * Serializes a list of chat messages into a JSON string. * * @param messages The list of chat messages to be serialized. * @return A JSON string representing provided chat messages. * @see ChatMessageDeserializer For details on deserialization. */ public static String messagesToJson(List<ChatMessage> messages) { return CODEC.messagesToJson(messages); } }
for (ChatMessageJsonCodecFactory factory : loadFactories(ChatMessageJsonCodecFactory.class)) { return factory.create(); } return new GsonChatMessageJsonCodec();
255
51
306
<no_super_class>