repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/KeywordEntity.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @ProtoDoc("@Indexed") public class KeywordEntity { private final String keyword; @ProtoFactory public KeywordEntity(String keyword) { this.keyword = keyword; } @ProtoField(value = 1, required = true) @ProtoDoc("@Field(store = Store.YES, analyze = Analyze.YES, analyzer = @Analyzer(definition = \"keyword\"))") public String getKeyword() { return keyword; } @AutoProtoSchemaBuilder(includeClasses = KeywordEntity.class) public interface KeywordSchema extends GeneratedSchema { KeywordSchema INSTANCE = new KeywordSchemaImpl(); } }
946
30.566667
112
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/Reviewer.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import org.hibernate.search.annotations.Analyze; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Store; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoField; @Indexed public class Reviewer { private String firstName; private String lastName; public Reviewer() { // Default constructor for use by protostream } public Reviewer(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @ProtoField(number = 1, required = true) @Field(index= Index.NO, store= Store.NO, analyze= Analyze.NO) public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; } @ProtoField(number = 2, required = true) @Field(index=Index.NO, store=Store.NO, analyze=Analyze.NO) public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; } @AutoProtoSchemaBuilder(includeClasses = {Reviewer.class, Revision.class}) public interface ReviewerSchema extends GeneratedSchema { ReviewerSchema INSTANCE = new ReviewerSchemaImpl(); } }
1,484
27.557692
77
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/LongAuto.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class LongAuto { private Long purchases; @ProtoFactory public LongAuto(Long purchases) { this.purchases = purchases; } @ProtoField(value = 1) public Long getPurchases() { return purchases; } @AutoProtoSchemaBuilder(includeClasses = LongAuto.class, schemaFilePath = "/protostream", schemaFileName = "long-auto.proto", schemaPackageName = "lab.auto") public interface LongSchema extends GeneratedSchema { } }
783
27
77
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/AddressPB.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.util.Objects; import org.infinispan.query.dsl.embedded.testdomain.Address; /** * @author anistor@redhat.com * @since 7.0 */ public class AddressPB implements Address { private String street; private String postCode; private int number; private boolean isCommercial; @Override public String getStreet() { return street; } @Override public void setStreet(String street) { this.street = street; } @Override public String getPostCode() { return postCode; } @Override public void setPostCode(String postCode) { this.postCode = postCode; } @Override public int getNumber() { return number; } @Override public void setNumber(int number) { this.number = number; } @Override public boolean isCommercial() { return isCommercial; } @Override public void setCommercial(boolean isCommercial) { this.isCommercial = isCommercial; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AddressPB address = (AddressPB) o; return number == address.number && isCommercial == address.isCommercial && Objects.equals(street, address.street) && Objects.equals(postCode, address.postCode); } @Override public int hashCode() { return Objects.hash(street, postCode, number, isCommercial); } @Override public String toString() { return "AddressPB{" + "street='" + street + '\'' + ", postCode='" + postCode + '\'' + ", number=" + number + ", isCommercial=" + isCommercial + '}'; } }
1,821
19.942529
66
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/CalculusAuto.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.math.BigInteger; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.types.java.CommonTypes; public class CalculusAuto { private BigInteger purchases; @ProtoFactory public CalculusAuto(BigInteger purchases) { this.purchases = purchases; } @ProtoField(value = 1) public BigInteger getPurchases() { return purchases; } @AutoProtoSchemaBuilder(includeClasses = CalculusAuto.class, dependsOn = CommonTypes.class, schemaFilePath = "/protostream", schemaFileName = "calculus-auto.proto", schemaPackageName = "lab.auto") public interface CalculusAutoSchema extends GeneratedSchema { } }
944
29.483871
94
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/CalculusManual.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.math.BigInteger; public class CalculusManual { private BigInteger purchases; public CalculusManual(BigInteger purchases) { this.purchases = purchases; } public BigInteger getPurchases() { return purchases; } }
318
17.764706
63
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/Book.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @ProtoDoc("@Indexed") public class Book { private final String title; @ProtoFactory public Book(String title) { this.title = title; } @ProtoField(value = 1) @ProtoDoc("@Field(store = Store.YES, analyze = Analyze.YES, analyzer = @Analyzer(definition = \"lowercase\"))") public String getTitle() { return title; } @AutoProtoSchemaBuilder(includeClasses = Book.class) public interface BookSchema extends GeneratedSchema { BookSchema INSTANCE = new BookSchemaImpl(); } }
883
28.466667
114
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/UserPB.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.time.Instant; import java.util.List; import java.util.Set; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.User; /** * @author anistor@redhat.com * @since 7.0 */ public class UserPB implements User { private int id; private String name; private String surname; private String salutation; private Set<Integer> accountIds; private List<Address> addresses; private Integer age; private Gender gender; private String notes; private Instant creationDate; private Instant passwordExpirationDate; @Override public int getId() { return id; } @Override public void setId(int id) { this.id = id; } @Override public Set<Integer> getAccountIds() { return accountIds; } @Override public void setAccountIds(Set<Integer> accountIds) { this.accountIds = accountIds; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getSurname() { return surname; } @Override public void setSurname(String surname) { this.surname = surname; } @Override public String getSalutation() { return salutation; } @Override public void setSalutation(String salutation) { this.salutation = salutation; } @Override public List<Address> getAddresses() { return addresses; } @Override public void setAddresses(List<Address> addresses) { this.addresses = addresses; } @Override public Integer getAge() { return age; } @Override public void setAge(Integer age) { this.age = age; } @Override public Gender getGender() { return gender; } @Override public void setGender(Gender gender) { this.gender = gender; } @Override public String getNotes() { return notes; } @Override public void setNotes(String notes) { this.notes = notes; } @Override public Instant getCreationDate() { return creationDate; } @Override public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; } @Override public Instant getPasswordExpirationDate() { return passwordExpirationDate; } @Override public void setPasswordExpirationDate(Instant passwordExpirationDate) { this.passwordExpirationDate = passwordExpirationDate; } @Override public String toString() { return "UserPB{" + "id=" + id + ", name='" + name + '\'' + ", surname='" + surname + '\'' + ", salutation='" + salutation + '\'' + ", accountIds=" + accountIds + ", addresses=" + addresses + ", age=" + age + ", gender=" + gender + ", notes=" + notes + ", creationDate='" + creationDate + '\'' + ", passwordExpirationDate=" + passwordExpirationDate + '}'; } }
3,157
19.374194
74
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/AnalyzerTestEntity.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; /** * @author anistor@redhat.com * @since 9.0 */ public class AnalyzerTestEntity { public String f1; public Integer f2; public AnalyzerTestEntity(String f1, Integer f2) { this.f1 = f1; this.f2 = f2; } @Override public String toString() { return "AnalyzerTestEntity{f1='" + f1 + "', f2=" + f2 + '}'; } }
414
17.043478
66
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/Color.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoField; @ProtoDoc("@Indexed") public class Color { private String name; private String description; @ProtoField(value = 1) @ProtoDoc("@Field(store = Store.YES, analyze = Analyze.NO)") public String getName() { return name; } public void setName(String name) { this.name = name; } @ProtoField(value = 2) @ProtoDoc("@Field(store = Store.NO, analyze = Analyze.YES, analyzer = @Analyzer(definition = \"keyword\"))") public String getDesc1() { return description; } public void setDesc1(String description) { this.description = description; } @ProtoField(value = 3) @ProtoDoc("@Field(store = Store.NO, analyze = Analyze.YES, analyzer = @Analyzer(definition = \"keyword\"))") public String getDesc2() { return description; } public void setDesc2(String description) { this.description = description; } @ProtoField(value = 4) @ProtoDoc("@Field(store = Store.NO, analyze = Analyze.YES, analyzer = @Analyzer(definition = \"standard\"))") public String getDesc3() { return description; } public void setDesc3(String description) { this.description = description; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @AutoProtoSchemaBuilder(includeClasses = Color.class) public interface ColorSchema extends GeneratedSchema { ColorSchema INSTANCE = new ColorSchemaImpl(); } }
1,823
25.823529
112
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/TransactionPB.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.math.BigDecimal; import java.util.Date; import org.infinispan.query.dsl.embedded.testdomain.Transaction; /** * @author anistor@redhat.com * @since 7.0 */ public class TransactionPB implements Transaction { private int id; private String description; private String longDescription; private String notes; private int accountId; private Date date; private BigDecimal amount; private boolean isDebit; private boolean isValid; @Override public int getId() { return id; } @Override public void setId(int id) { this.id = id; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public String getLongDescription() { return longDescription; } @Override public String getNotes() { return notes; } @Override public void setNotes(String notes) { this.notes = notes; } @Override public void setLongDescription(String longDescription) { this.longDescription = longDescription; } @Override public int getAccountId() { return accountId; } @Override public void setAccountId(int accountId) { this.accountId = accountId; } @Override public Date getDate() { return date; } @Override public void setDate(Date date) { this.date = date; } @Override public double getAmount() { return amount.doubleValue(); } @Override public void setAmount(double amount) { this.amount = new BigDecimal(amount); } @Override public boolean isDebit() { return isDebit; } @Override public void setDebit(boolean isDebit) { this.isDebit = isDebit; } @Override public boolean isValid() { return isValid; } @Override public void setValid(boolean isValid) { this.isValid = isValid; } @Override public String toString() { return "TransactionPB{" + "id=" + id + ", description='" + description + '\'' + ", longDescription='" + longDescription + '\'' + ", notes='" + notes + '\'' + ", accountId=" + accountId + ", date='" + date + '\'' + ", amount=" + amount + ", isDebit=" + isDebit + ", isValid=" + isValid + '}'; } }
2,522
18.55814
64
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/LimitsMarshaller.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import java.io.IOException; import org.infinispan.client.hotrod.query.testdomain.protobuf.LimitsPB; import org.infinispan.protostream.MessageMarshaller; /** * @author anistor@redhat.com * @since 9.4.1 */ public class LimitsMarshaller implements MessageMarshaller<LimitsPB> { @Override public String getTypeName() { return "sample_bank_account.Account.Limits"; } @Override public Class<LimitsPB> getJavaClass() { return LimitsPB.class; } @Override public LimitsPB readFrom(ProtoStreamReader reader) throws IOException { double maxDailyLimit = reader.readDouble("maxDailyLimit"); double maxTransactionLimit = reader.readDouble("maxTransactionLimit"); String[] payees = reader.readArray("payees", String.class); LimitsPB limits = new LimitsPB(); limits.setMaxDailyLimit(maxDailyLimit); limits.setMaxTransactionLimit(maxTransactionLimit); limits.setPayees(payees); return limits; } @Override public void writeTo(ProtoStreamWriter writer, LimitsPB limits) throws IOException { writer.writeDouble("maxDailyLimit", limits.getMaxDailyLimit()); writer.writeDouble("maxTransactionLimit", limits.getMaxTransactionLimit()); writer.writeArray("payees", limits.getPayees(), String.class); } }
1,380
30.386364
86
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/CalculusManualSCI.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import java.io.UncheckedIOException; import org.infinispan.protostream.FileDescriptorSource; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; public class CalculusManualSCI implements SerializationContextInitializer { @Override public String getProtoFileName() { return "calculus-manual.proto"; } @Override public String getProtoFile() throws UncheckedIOException { return FileDescriptorSource.getResourceAsString(getClass(), "/protostream/" + getProtoFileName()); } @Override public void registerSchema(SerializationContext serCtx) { serCtx.registerProtoFiles(FileDescriptorSource.fromString(getProtoFileName(), getProtoFile())); } @Override public void registerMarshallers(SerializationContext serCtx) { serCtx.registerMarshaller(new CalculusManualMarshaller()); } }
986
30.83871
104
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/GenderMarshaller.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import org.infinispan.protostream.EnumMarshaller; import org.infinispan.query.dsl.embedded.testdomain.User; /** * @author anistor@redhat.com * @since 7.0 */ public class GenderMarshaller implements EnumMarshaller<User.Gender> { @Override public Class<User.Gender> getJavaClass() { return User.Gender.class; } @Override public String getTypeName() { return "sample_bank_account.User.Gender"; } @Override public User.Gender decode(int enumValue) { switch (enumValue) { case 0: return User.Gender.MALE; case 1: return User.Gender.FEMALE; } return null; // unknown value } @Override public int encode(User.Gender gender) { switch (gender) { case MALE: return 0; case FEMALE: return 1; default: throw new IllegalArgumentException("Unexpected User.Gender value : " + gender); } } }
1,045
22.244444
91
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/TestDomainSCI.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import org.infinispan.protostream.FileDescriptorSource; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; public class TestDomainSCI implements SerializationContextInitializer { static final String PROTOBUF_RES = "sample_bank_account/bank.proto"; public static final TestDomainSCI INSTANCE = new TestDomainSCI(); private TestDomainSCI() { } @Override public String getProtoFileName() { return PROTOBUF_RES; } @Override public String getProtoFile() { return FileDescriptorSource.getResourceAsString(getClass(), "/" + PROTOBUF_RES); } @Override public void registerSchema(SerializationContext serCtx) { serCtx.registerProtoFiles(FileDescriptorSource.fromString(getProtoFileName(), getProtoFile())); } @Override public void registerMarshallers(SerializationContext ctx) { ctx.registerMarshaller(new UserMarshaller()); ctx.registerMarshaller(new GenderMarshaller()); ctx.registerMarshaller(new AddressMarshaller()); ctx.registerMarshaller(new AccountMarshaller()); ctx.registerMarshaller(new CurrencyMarshaller()); ctx.registerMarshaller(new LimitsMarshaller()); ctx.registerMarshaller(new TransactionMarshaller()); } }
1,380
33.525
101
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/CurrencyMarshaller.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import org.infinispan.protostream.EnumMarshaller; import org.infinispan.query.dsl.embedded.testdomain.Account; /** * @author anistor@redhat.com * @since 9.4.1 */ public class CurrencyMarshaller implements EnumMarshaller<Account.Currency> { @Override public Class<Account.Currency> getJavaClass() { return Account.Currency.class; } @Override public String getTypeName() { return "sample_bank_account.Account.Currency"; } @Override public Account.Currency decode(int enumValue) { switch (enumValue) { case 0: return Account.Currency.EUR; case 1: return Account.Currency.GBP; case 2: return Account.Currency.USD; case 3: return Account.Currency.BRL; } return null; // unknown value } @Override public int encode(Account.Currency currency) { switch (currency) { case EUR: return 0; case GBP: return 1; case USD: return 2; case BRL: return 3; default: throw new IllegalArgumentException("Unexpected Account.Currency value : " + currency); } } }
1,293
23.415094
98
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/AccountMarshaller.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.infinispan.client.hotrod.query.testdomain.protobuf.AccountPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.LimitsPB; import org.infinispan.protostream.MessageMarshaller; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.Limits; /** * @author anistor@redhat.com * @since 7.0 */ public class AccountMarshaller implements MessageMarshaller<AccountPB> { @Override public String getTypeName() { return "sample_bank_account.Account"; } @Override public Class<AccountPB> getJavaClass() { return AccountPB.class; } @Override public AccountPB readFrom(ProtoStreamReader reader) throws IOException { int id = reader.readInt("id"); String description = reader.readString("description"); long creationDate = reader.readLong("creationDate"); Limits limits = reader.readObject("limits", LimitsPB.class); Limits hardLimits = reader.readObject("hardLimits", LimitsPB.class); List<byte[]> blurb = reader.readCollection("blurb", new ArrayList<>(), byte[].class); Account.Currency[] currencies = reader.readArray("currencies", Account.Currency.class); AccountPB account = new AccountPB(); account.setId(id); account.setDescription(description); account.setCreationDate(new Date(creationDate)); account.setLimits(limits); account.setHardLimits(hardLimits); account.setBlurb(blurb); account.setCurrencies(currencies); return account; } @Override public void writeTo(ProtoStreamWriter writer, AccountPB account) throws IOException { writer.writeInt("id", account.getId()); writer.writeString("description", account.getDescription()); writer.writeDate("creationDate", account.getCreationDate()); writer.writeObject("limits", account.getLimits(), LimitsPB.class); writer.writeObject("hardLimits", account.getHardLimits(), LimitsPB.class); writer.writeCollection("blurb", account.getBlurb(), byte[].class); writer.writeArray("currencies", account.getCurrencies(), Account.Currency.class); } }
2,334
36.66129
93
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/TransactionMarshaller.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import java.io.IOException; import java.util.Date; import org.infinispan.client.hotrod.query.testdomain.protobuf.TransactionPB; import org.infinispan.protostream.MessageMarshaller; /** * @author anistor@redhat.com * @since 7.0 */ public class TransactionMarshaller implements MessageMarshaller<TransactionPB> { @Override public String getTypeName() { return "sample_bank_account.Transaction"; } @Override public Class<TransactionPB> getJavaClass() { return TransactionPB.class; } @Override public TransactionPB readFrom(ProtoStreamReader reader) throws IOException { int id = reader.readInt("id"); String description = reader.readString("description"); String longDescription = reader.readString("longDescription"); String notes = reader.readString("notes"); int accountId = reader.readInt("accountId"); long date = reader.readLong("date"); double amount = reader.readDouble("amount"); boolean isDebit = reader.readBoolean("isDebit"); boolean isValid = reader.readBoolean("isValid"); TransactionPB transaction = new TransactionPB(); transaction.setId(id); transaction.setDescription(description); transaction.setLongDescription(longDescription); transaction.setNotes(notes); transaction.setAccountId(accountId); transaction.setDate(new Date(date)); transaction.setAmount(amount); transaction.setDebit(isDebit); transaction.setValid(isValid); return transaction; } @Override public void writeTo(ProtoStreamWriter writer, TransactionPB transaction) throws IOException { writer.writeInt("id", transaction.getId()); writer.writeString("description", transaction.getDescription()); writer.writeString("longDescription", transaction.getLongDescription()); writer.writeString("notes", transaction.getNotes()); writer.writeInt("accountId", transaction.getAccountId()); writer.writeLong("date", transaction.getDate().getTime()); writer.writeDouble("amount", transaction.getAmount()); writer.writeBoolean("isDebit", transaction.isDebit()); writer.writeBoolean("isValid", transaction.isValid()); } }
2,298
35.492063
96
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/AnalyzerTestEntityMarshaller.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import java.io.IOException; import org.infinispan.client.hotrod.query.testdomain.protobuf.AnalyzerTestEntity; import org.infinispan.protostream.MessageMarshaller; /** * @author anistor@redhat.com * @since 9.0 */ public class AnalyzerTestEntityMarshaller implements MessageMarshaller<AnalyzerTestEntity> { @Override public AnalyzerTestEntity readFrom(ProtoStreamReader reader) throws IOException { String f1 = reader.readString("f1"); Integer f2 = reader.readInt("f2"); return new AnalyzerTestEntity(f1, f2); } @Override public void writeTo(ProtoStreamWriter writer, AnalyzerTestEntity analyzerTestEntity) throws IOException { writer.writeString("f1", analyzerTestEntity.f1); writer.writeInt("f2", analyzerTestEntity.f2); } @Override public Class<AnalyzerTestEntity> getJavaClass() { return AnalyzerTestEntity.class; } @Override public String getTypeName() { return "sample_bank_account.AnalyzerTestEntity"; } }
1,075
28.081081
108
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/AddressMarshaller.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import java.io.IOException; import org.infinispan.client.hotrod.query.testdomain.protobuf.AddressPB; import org.infinispan.protostream.MessageMarshaller; /** * @author anistor@redhat.com * @since 7.0 */ public class AddressMarshaller implements MessageMarshaller<AddressPB> { @Override public String getTypeName() { return "sample_bank_account.User.Address"; } @Override public Class<AddressPB> getJavaClass() { return AddressPB.class; } @Override public AddressPB readFrom(ProtoStreamReader reader) throws IOException { String street = reader.readString("street"); String postCode = reader.readString("postCode"); int number = reader.readInt("number"); Boolean isCommercial = reader.readBoolean("isCommercial"); AddressPB address = new AddressPB(); address.setStreet(street); address.setPostCode(postCode); address.setNumber(number); address.setCommercial(isCommercial); return address; } @Override public void writeTo(ProtoStreamWriter writer, AddressPB address) throws IOException { writer.writeString("street", address.getStreet()); writer.writeString("postCode", address.getPostCode()); writer.writeInt("number", address.getNumber()); writer.writeBoolean("isCommercial", address.isCommercial()); } }
1,424
29.319149
88
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/CalculusManualMarshaller.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import java.io.IOException; import java.math.BigInteger; import org.infinispan.client.hotrod.query.testdomain.protobuf.CalculusManual; import org.infinispan.protostream.MessageMarshaller; public class CalculusManualMarshaller implements MessageMarshaller<CalculusManual> { @Override public CalculusManual readFrom(ProtoStreamReader reader) throws IOException { BigInteger purchases = reader.readObject("purchases", BigInteger.class); return new CalculusManual(purchases); } @Override public void writeTo(ProtoStreamWriter writer, CalculusManual calculus) throws IOException { writer.writeObject("purchases", calculus.getPurchases(), BigInteger.class); } @Override public Class<? extends CalculusManual> getJavaClass() { return CalculusManual.class; } @Override public String getTypeName() { return "lab.manual.Calculus"; } }
974
29.46875
94
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/marshallers/UserMarshaller.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.infinispan.client.hotrod.query.testdomain.protobuf.AddressPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB; import org.infinispan.protostream.MessageMarshaller; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.User; /** * @author anistor@redhat.com * @since 7.0 */ public class UserMarshaller implements MessageMarshaller<UserPB> { @Override public String getTypeName() { return "sample_bank_account.User"; } @Override public Class<UserPB> getJavaClass() { return UserPB.class; } @Override public UserPB readFrom(ProtoStreamReader reader) throws IOException { int id = reader.readInt("id"); Set<Integer> accountIds = reader.readCollection("accountIds", new HashSet<>(), Integer.class); // Read them out of order. It still works but logs a warning! String surname = reader.readString("surname"); String name = reader.readString("name"); String salutation = reader.readString("salutation"); List<Address> addresses = reader.readCollection("addresses", new ArrayList<>(), AddressPB.class); Integer age = reader.readInt("age"); User.Gender gender = reader.readEnum("gender", User.Gender.class); String notes = reader.readString("notes"); Instant creationDate = reader.readInstant("creationDate"); Instant passwordExpirationDate = reader.readInstant("passwordExpirationDate"); UserPB user = new UserPB(); user.setId(id); user.setAccountIds(accountIds); user.setName(name); user.setSurname(surname); user.setSalutation(salutation); user.setAge(age); user.setGender(gender); user.setAddresses(addresses); user.setNotes(notes); user.setCreationDate(creationDate); user.setPasswordExpirationDate(passwordExpirationDate); return user; } @Override public void writeTo(ProtoStreamWriter writer, UserPB user) throws IOException { writer.writeInt("id", user.getId()); writer.writeCollection("accountIds", user.getAccountIds(), Integer.class); writer.writeString("name", user.getName()); writer.writeString("surname", user.getSurname()); writer.writeString("salutation", user.getSalutation()); writer.writeCollection("addresses", user.getAddresses(), AddressPB.class); writer.writeInt("age", user.getAge()); writer.writeEnum("gender", user.getGender()); writer.writeString("notes", user.getNotes()); writer.writeInstant("creationDate", user.getCreationDate()); writer.writeInstant("passwordExpirationDate", user.getPasswordExpirationDate()); } }
2,937
35.725
103
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/company/FootballSchema.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.company; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; @AutoProtoSchemaBuilder(includeClasses = { FootballTeam.class, Player.class }, schemaPackageName = "org.football", schemaFileName = "football.proto", schemaFilePath = "proto") public interface FootballSchema extends GeneratedSchema { }
438
38.909091
114
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/company/FootballTeam.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.company; import java.util.List; import org.infinispan.protostream.annotations.ProtoField; public class FootballTeam { private String name; private List<Player> players; @ProtoField(value = 1) public String getName() { return name; } public void setName(String name) { this.name = name; } @ProtoField(value = 2) public List<Player> getPlayers() { return players; } public void setPlayers(List<Player> players) { this.players = players; } }
570
18.033333
71
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/company/Player.java
package org.infinispan.client.hotrod.query.testdomain.protobuf.company; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class Player { private String name; private FootballTeam footballTeam; @ProtoFactory public Player(String name, FootballTeam footballTeam) { this.name = name; this.footballTeam = footballTeam; } @ProtoField(value = 1) public String getName() { return name; } @ProtoField(value = 2) public FootballTeam getFootballTeam() { return footballTeam; } }
607
21.518519
71
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/schema/SchemaUpdateMetadataTest.java
package org.infinispan.client.hotrod.query.schema; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.Programmer; import org.infinispan.client.hotrod.query.testdomain.protobuf.ProgrammerSchemaImpl; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.objectfilter.impl.ProtobufMatcher; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.objectfilter.impl.syntax.parser.ObjectPropertyHelper; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.descriptors.AnnotationElement; import org.infinispan.protostream.descriptors.Descriptor; import org.infinispan.protostream.descriptors.FieldDescriptor; import org.infinispan.protostream.impl.ResourceUtils; import org.infinispan.query.core.impl.QueryCache; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.model.Developer; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.query.schema.SchemaUpdateMetadataTest") @TestForIssue(jiraKey = "ISPN-14527") public class SchemaUpdateMetadataTest extends SingleHotRodServerTest { public static final ProgrammerSchemaImpl PROGRAMMER_SCHEMA = new ProgrammerSchemaImpl(); public static final String QUERY_SORT = "from io.pro.Programmer p order by p.contributions"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder config = new ConfigurationBuilder(); config.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("io.pro.Programmer"); return TestCacheManagerFactory.createServerModeCacheManager(config); } @Override protected SerializationContextInitializer contextInitializer() { return PROGRAMMER_SCHEMA; } /** * Configure the server, enabling the admin operations * * @return the HotRod server */ @Override protected HotRodServer createHotRodServer() { HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); return HotRodClientTestingUtil.startHotRodServer(cacheManager, serverBuilder); } @Test public void test() throws Exception { RemoteCache<String, Programmer> remoteCache = remoteCacheManager.getCache(); cache.put(1, new Programmer("fax4ever", 300)); QueryFactory queryFactory = Search.getQueryFactory(remoteCache); Query<Developer> kQuery; QueryResult<Developer> kResult; kQuery = queryFactory.create(QUERY_SORT); kResult = kQuery.execute(); assertThat(kResult.count().value()).isEqualTo(1); verifySortable(false); queryIsOnTheCache(true); updateTheSchemaAndReindex(); verifySortable(true); queryIsOnTheCache(false); kQuery = queryFactory.create(QUERY_SORT); kResult = kQuery.execute(); assertThat(kResult.count().value()).isEqualTo(1); queryIsOnTheCache(true); } private void queryIsOnTheCache(boolean isPresent) { QueryCache queryCache = getGlobalQueryCache(); AtomicBoolean present = new AtomicBoolean(true); queryCache.get(cache.getName(), QUERY_SORT, null, IckleParsingResult.class, (qs, accumulators) -> { present.set(false); // true => is not present return null; }); assertThat(present.get()).isEqualTo(isPresent); } private QueryCache getGlobalQueryCache() { return cache.getAdvancedCache().getComponentRegistry().getGlobalComponentRegistry() .getComponent(QueryCache.class); } private void updateTheSchemaAndReindex() { String newProtoFile = ResourceUtils.getResourceAsString(getClass(), "/proto/pro-sortable.proto"); cacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME) .put(PROGRAMMER_SCHEMA.getProtoFileName(), newProtoFile); remoteCacheManager.administration().reindexCache(cache.getName()); } private void verifySortable(boolean expected) { Descriptor descriptor = descriptor(); FieldDescriptor fieldDescriptor = descriptor.findFieldByName("contributions"); Map<String, AnnotationElement.Annotation> annotations = fieldDescriptor.getAnnotations(); assertThat(annotations).containsKey("Basic"); AnnotationElement.Annotation basic = annotations.get("Basic"); AnnotationElement.Value sortable = basic.getAttributeValue("sortable"); assertThat(sortable.toString()).isEqualTo(expected + ""); } private Descriptor descriptor() { ProtobufMatcher matcher = cache.getAdvancedCache().getComponentRegistry() .getComponent(ProtobufMatcher.class); assertThat(matcher).isNotNull(); ObjectPropertyHelper<Descriptor> propertyHelper = matcher.getPropertyHelper(); assertThat(propertyHelper).isNotNull(); Descriptor descriptor = propertyHelper.getEntityMetadata("io.pro.Programmer"); assertThat(descriptor).isNotNull(); return descriptor; } }
6,114
40.317568
109
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/type/BigIntegerAutoTest.java
package org.infinispan.client.hotrod.query.type; import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.query.testdomain.protobuf.CalculusAuto; import org.infinispan.client.hotrod.query.testdomain.protobuf.CalculusAutoSchemaImpl; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.protostream.SerializationContextInitializer; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.query.type.BigIntegerAutoTest") public class BigIntegerAutoTest extends SingleHotRodServerTest { @Override protected SerializationContextInitializer contextInitializer() { return new CalculusAutoSchemaImpl(); } @Test public void test() { RemoteCache<String, CalculusAuto> remoteCache = remoteCacheManager.getCache(); remoteCache.put("1", new CalculusAuto(BigInteger.TEN)); CalculusAuto calculus = remoteCache.get("1"); assertThat(calculus.getPurchases()).isEqualTo(10); } }
1,113
36.133333
101
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/type/BigIntegerBigDecimalIndexedTest.java
package org.infinispan.client.hotrod.query.type; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.assertj.core.api.Assertions.assertThat; import java.math.BigDecimal; import java.math.BigInteger; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.CalculusIndexed; import org.infinispan.client.hotrod.query.testdomain.protobuf.CalculusIndexedSchemaImpl; import org.infinispan.client.hotrod.query.testdomain.protobuf.Product; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.query.type.BigIntegerBigDecimalIndexedTest") public class BigIntegerBigDecimalIndexedTest extends SingleHotRodServerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder config = new ConfigurationBuilder(); config.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("lab.indexed.CalculusIndexed"); return TestCacheManagerFactory.createServerModeCacheManager(config); } @Override protected SerializationContextInitializer contextInitializer() { return new CalculusIndexedSchemaImpl(); } @Test public void test() { RemoteCache<String, CalculusIndexed> remoteCache = remoteCacheManager.getCache(); remoteCache.put("1", new CalculusIndexed("blablabla", BigInteger.TEN, BigDecimal.valueOf(2.2), BigDecimal.valueOf(2.2))); CalculusIndexed calculus = remoteCache.get("1"); assertThat(calculus.getPurchases()).isEqualTo(10); assertThat(calculus.getProspect()).isEqualTo(BigDecimal.valueOf(2.2)); QueryFactory queryFactory = Search.getQueryFactory(remoteCache); Query<Product> query; QueryResult<Product> result; query = queryFactory.create("from lab.indexed.CalculusIndexed c where c.purchases > 9"); result = query.execute(); assertThat(result.list()).extracting("name").containsExactly("blablabla"); query = queryFactory.create("from lab.indexed.CalculusIndexed c where c.prospect = 2.2"); result = query.execute(); assertThat(result.list()).extracting("name").containsExactly("blablabla"); // also 2.0 match since the field prospect is annotated with @Basic and not with @Decimal query = queryFactory.create("from lab.indexed.CalculusIndexed c where c.prospect = 2.0"); result = query.execute(); assertThat(result.list()).extracting("name").containsExactly("blablabla"); query = queryFactory.create("from lab.indexed.CalculusIndexed c where c.prospect = 3.0"); result = query.execute(); assertThat(result.list()).isEmpty(); query = queryFactory.create("from lab.indexed.CalculusIndexed c where c.decimal = 2.2"); result = query.execute(); assertThat(result.list()).extracting("name").containsExactly("blablabla"); query = queryFactory.create("from lab.indexed.CalculusIndexed c where c.decimal = 2.0"); result = query.execute(); assertThat(result.list()).extracting("name").isEmpty(); } }
3,610
43.580247
127
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/type/BigIntegerManualTest.java
package org.infinispan.client.hotrod.query.type; import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.query.testdomain.protobuf.CalculusManual; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.CalculusManualSCI; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.protostream.SerializationContextInitializer; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.query.type.BigIntegerManualTest") public class BigIntegerManualTest extends SingleHotRodServerTest { @Override protected SerializationContextInitializer contextInitializer() { return new CalculusManualSCI(); } @Test public void test() { RemoteCache<String, CalculusManual> remoteCache = remoteCacheManager.getCache(); remoteCache.put("1", new CalculusManual(BigInteger.TEN)); CalculusManual calculus = remoteCache.get("1"); assertThat(calculus.getPurchases()).isEqualTo(10); } }
1,127
36.6
103
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/type/BigIntegerAdapterTest.java
package org.infinispan.client.hotrod.query.type; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.math.BigInteger; import java.time.Instant; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.client.hotrod.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.client.hotrod.query.testdomain.protobuf.Product; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.query.type.BigIntegerAdapterTest") public class BigIntegerAdapterTest extends SingleHotRodServerTest { public static final long OVER_INTEGER_VALUE = (long) Integer.MAX_VALUE + 1000; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder config = new ConfigurationBuilder(); config.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("store.product.Product"); return TestCacheManagerFactory.createServerModeCacheManager(config); } @Override protected SerializationContextInitializer contextInitializer() { return Product.ProductSchema.INSTANCE; } @Test public void test() { RemoteCache<String, Product> remoteCache = remoteCacheManager.getCache(); Product p1 = new Product("Pilsner Urquell", 2178129121111L, 23.78, "Pilsner Urquell is a lager beer brewed by the Pilsner Urquell Brewery in Plzeň, Czech Republic. Pilsner Urquell was the world's first pale lager, and its popularity meant it was much copied, and named pils, pilsner or pilsener. It is hopped with Saaz hops, a noble hop variety which is a key element in its flavour profile, as is the use of soft water.", BigInteger.valueOf(OVER_INTEGER_VALUE), Instant.ofEpochSecond(1675769531, 123000000)); Product p2 = new Product("Lavazza Coffee", 178128739123L, 10.99, "Lavazza imports coffee from around the world, including Brazil, Colombia, Guatemala, Costa Rica, Honduras, Uganda, Indonesia, the United States and Mexico.\n Branded as \"Italy's Favourite Coffee,\" the company claims that 16 million out of the 20 million coffee purchasing families in Italy choose Lavazza.", BigInteger.valueOf(OVER_INTEGER_VALUE), Instant.ofEpochSecond(1675769531, 123000000)); Product p3 = new Product("Puma Backpack", 21233131131L, 40.99, "Lightweight and practical gym bag made of durable material, which can be carried as a backpack. This classic gym sack slings easily over the shoulder and for carrying smaller loads.", BigInteger.valueOf(OVER_INTEGER_VALUE), Instant.ofEpochSecond(1675769531, 123000000)); remoteCache.put("1", p1); remoteCache.put("2", p2); remoteCache.put("3", p3); Product product = remoteCache.get("1"); assertThat(product.getPurchases()).isEqualTo(OVER_INTEGER_VALUE); assertThat(product.getMoment().getEpochSecond()).isEqualTo(1675769531); assertThat(product.getMoment().getNano()).isEqualTo(123000000); // this is the max precision we have at the moment QueryFactory queryFactory = Search.getQueryFactory(remoteCache); Query<Product> query = queryFactory.create("from store.product.Product p where p.name = 'pilsner urquell'"); QueryResult<Product> result = query.execute(); assertThat(result.list()).extracting("name").containsExactly("Pilsner Urquell"); query = queryFactory.create("from store.product.Product p where p.code = 178128739123"); result = query.execute(); assertThat(result.list()).extracting("name").containsExactly("Lavazza Coffee"); query = queryFactory.create("from store.product.Product p where p.price < 30 order by p.price desc"); result = query.execute(); assertThat(result.list()).extracting("name").containsExactly("Pilsner Urquell", "Lavazza Coffee"); query = queryFactory.create("from store.product.Product p where p.description : 'gym'"); result = query.execute(); assertThat(result.list()).extracting("name").containsExactly("Puma Backpack"); } }
4,551
54.512195
367
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/test/PoemTest.java
package org.infinispan.client.hotrod.annotation.test; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.util.List; import org.assertj.core.api.iterable.Extractor; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.annotation.model.Author; import org.infinispan.client.hotrod.annotation.model.Poem; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.annotation.test.PoemTest") public class PoemTest extends SingleHotRodServerTest { private static final Extractor<Object[], Object> FIRST_ELEMENT_OF_THE_ARRAY = (item) -> item[0]; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("poem.Poem"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("poems", builder.build()); return manager; } @Override protected SerializationContextInitializer contextInitializer() { return Poem.PoemSchema.INSTANCE; } @Test public void testSearches() { RemoteCache<Integer, Poem> remoteCache = remoteCacheManager.getCache("poems"); remoteCache.put(1, new Poem(new Author("Edgar Allen Poe"), "The Raven", 1845)); remoteCache.put(2, new Poem(new Author("Emily Dickinson"), "Because I could not stop for Death", 1890)); remoteCache.put(3, new Poem(new Author("Emma Lazarus"), "The New Colossus", 1883)); remoteCache.put(4, new Poem(new Author(null), "Alla Sera", null)); // check index as null QueryFactory queryFactory = Search.getQueryFactory(remoteCache); Query<Object[]> query; List<Object[]> poems; // basic(searchable) && embedded>keyword(projectable) && embedded>keyword(sortable) && index-as-null check // TODO HSEARCH-4584 Restore the original query when it solved: // query = queryFactory.create("select p.author.name from poem.Poem p where p.year < 1885 order by p.author.name"); query = queryFactory.create("select p.author.name from poem.Poem p order by p.author.name"); poems = query.execute().list(); assertThat(poems).extracting(FIRST_ELEMENT_OF_THE_ARRAY) .containsExactly("Edgar Allen Poe", "Emily Dickinson", "Emma Lazarus", null); assertThat(queryFactory.create("from poem.Poem p where p.year < 1885 order by p.author.name").execute().list()) .extracting("year").containsExactly(1845, 1883, 1803); // text(searchable) && text(projectable) && basic(sortable) query = queryFactory.create("select p.description from poem.Poem p where p.description : 'The' order by p.year"); poems = query.execute().list(); assertThat(poems).extracting(FIRST_ELEMENT_OF_THE_ARRAY) .containsExactly("The Raven", "The New Colossus"); // whitespace analyzer: the term `The` is not lower cased filtered. So `the` won't match: assertThat(queryFactory.create("from poem.Poem p where p.description : 'the'").execute().list()).isEmpty(); // embedded>keyword(searchable) with lowercase normalizer && basic(projectable) query = queryFactory.create("select p.year from poem.Poem p where p.author.name = 'eMMA lazaRUS'"); poems = query.execute().list(); assertThat(poems).extracting(FIRST_ELEMENT_OF_THE_ARRAY) .containsExactly(1883); } }
4,048
46.635294
123
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/Poem.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Embedded; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.api.annotations.indexing.option.Structure; import org.infinispan.api.annotations.indexing.option.TermVector; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed public class Poem { private Author author; private String description; private Integer year; @ProtoFactory public Poem(Author author, String description, Integer year) { this.author = author; this.description = description; this.year = year; } @Embedded(includeDepth = 2, structure = Structure.NESTED) @ProtoField(value = 1) public Author getAuthor() { return author; } @Text(projectable = true, analyzer = "whitespace", termVector = TermVector.WITH_OFFSETS) @ProtoField(value = 2) public String getDescription() { return description; } @Basic(projectable = true, sortable = true, indexNullAs = "1803") @ProtoField(value = 3, defaultValue = "1803") public Integer getYear() { return year; } @AutoProtoSchemaBuilder(includeClasses = {Poem.class, Author.class}, schemaPackageName = "poem") public interface PoemSchema extends GeneratedSchema { PoemSchema INSTANCE = new PoemSchemaImpl(); } }
1,657
31.509804
99
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/ModelC.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoName; @Indexed @ProtoName("Model") public class ModelC implements Model { @Deprecated public String original; @Deprecated public String different; public String divergent; @ProtoFactory public ModelC(String original, String different, String divergent) { this.original = original; this.different = different; this.divergent = divergent; } @Deprecated @ProtoField(value = 1) @Basic public String getOriginal() { return original; } @Deprecated @ProtoField(value = 2) @Basic public String getDifferent() { return different; } @ProtoField(value = 3) @Basic public String getDivergent() { return divergent; } }
1,051
20.916667
71
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/Model.java
package org.infinispan.client.hotrod.annotation.model; public interface Model { default String getId() { return null; } }
139
16.5
54
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/Essay.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class Essay { private String title; private String content; @ProtoFactory public Essay(String title, String content) { this.title = title; this.content = content; } @ProtoField(value = 1) public String getTitle() { return title; } @ProtoField(value = 2) public String getContent() { return content; } @AutoProtoSchemaBuilder(includeClasses = {Essay.class}, schemaPackageName = "essay") public interface EssaySchema extends GeneratedSchema { EssaySchema INSTANCE = new EssaySchemaImpl(); } }
872
23.942857
87
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/ModelA.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoName; @Indexed @ProtoName("Model") public class ModelA implements Model { private String original; @ProtoFactory public ModelA(String original) { this.original = original; } @ProtoField(value = 1) @Basic public String getOriginal() { return original; } }
630
23.269231
59
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/Author.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Keyword; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed public class Author { private String name; @ProtoFactory public Author(String name) { this.name = name; } @Keyword(projectable = true, sortable = true, normalizer = "lowercase", indexNullAs = "Ugo Foscolo", norms = false) @ProtoField(value = 1) public String getName() { return name; } public void setName(String name) { this.name = name; } }
691
23.714286
118
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/Image.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoName; @Indexed @ProtoName("Image") public class Image { private String name; @ProtoFactory public Image(String name) { this.name = name; } @ProtoField(value = 1) @Basic public String getName() { return name; } }
587
21.615385
59
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/ModelB.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoName; @Indexed @ProtoName("Model") public class ModelB implements Model { @Deprecated public String original; public String different; @ProtoFactory public ModelB(String original, String different) { this.original = original; this.different = different; } @Deprecated @ProtoField(value = 1) @Basic public String getOriginal() { return original; } @ProtoField(value = 2) @Basic public String getDifferent() { return different; } }
840
21.72973
59
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/SchemaC.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; @AutoProtoSchemaBuilder(includeClasses = { ModelC.class, Image.class }, schemaFileName = "model-schema.proto", schemaPackageName = "model") public interface SchemaC extends GeneratedSchema { SchemaC INSTANCE = new SchemaCImpl(); }
414
33.583333
139
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/SchemaA.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; @AutoProtoSchemaBuilder(includeClasses = ModelA.class, schemaFileName = "model-schema.proto", schemaPackageName = "model") public interface SchemaA extends GeneratedSchema { SchemaA INSTANCE = new SchemaAImpl(); }
397
32.166667
122
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/annotation/model/SchemaB.java
package org.infinispan.client.hotrod.annotation.model; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; @AutoProtoSchemaBuilder(includeClasses = ModelB.class, schemaFileName = "model-schema.proto", schemaPackageName = "model") public interface SchemaB extends GeneratedSchema { SchemaB INSTANCE = new SchemaBImpl(); }
397
32.166667
122
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/counter/StrongCounterHitsAwareTest.java
package org.infinispan.client.hotrod.counter; import static org.testng.AssertJUnit.assertEquals; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import org.infinispan.Cache; import org.infinispan.client.hotrod.HitsAwareCacheManagersTest; import org.infinispan.client.hotrod.RemoteCounterManagerFactory; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.SyncStrongCounter; import org.infinispan.counter.impl.CounterModuleLifecycle; import org.infinispan.counter.impl.entries.CounterKey; import org.infinispan.counter.impl.entries.CounterValue; import org.infinispan.util.ByteString; import org.testng.annotations.Test; /** * Tests if the {@link org.infinispan.counter.api.StrongCounter} operations hits the primary owner of the counter to * save some network hops. * * @author Pedro Ruivo * @since 10.0 */ @Test(groups = "functional", testName = "client.hotrod.counter.StrongCounterHitsAwareTest") public class StrongCounterHitsAwareTest extends HitsAwareCacheManagersTest { private static final int NUM_SERVERS = 3; public void testAddAndGetHits(Method method) { String counterName = method.getName(); doTest(counterName, SyncStrongCounter::incrementAndGet); } public void testGetValueHits(Method method) { String counterName = method.getName(); doTest(counterName, SyncStrongCounter::getValue); } public void testResetHits(Method method) { String counterName = method.getName(); doTest(counterName, SyncStrongCounter::reset); } public void testCompareAndSwapHits(Method method) { String counterName = method.getName(); doTest(counterName, counter -> counter.compareAndSwap(0, 1)); } public void testRemoveHits(Method method) { String counterName = method.getName(); doTest(counterName, SyncStrongCounter::remove); } @Override protected void createCacheManagers() throws Throwable { createHotRodServers(NUM_SERVERS, new ConfigurationBuilder()); waitForClusterToForm(CounterModuleLifecycle.COUNTER_CACHE_NAME); addInterceptors(CounterModuleLifecycle.COUNTER_CACHE_NAME); assertEquals(NUM_SERVERS, getCacheManagers().size()); } @Override protected void resetStats() { caches(CounterModuleLifecycle.COUNTER_CACHE_NAME).stream().map(this::getHitCountInterceptor) .forEach(HitCountInterceptor::reset); } private void doTest(String counterName, Consumer<SyncStrongCounter> action) { defineCounter(counterName); int primaryOwner = findPrimaryOwnerIndex(counterName); //lets hope there are no commands still going throw the cluster :) resetStats(); for (CounterManager cm : clientCounterManagers()) { action.accept(cm.getStrongCounter(counterName).sync()); } assertHits(primaryOwner); } private void defineCounter(String counterName) { CounterManager counterManager = RemoteCounterManagerFactory.asCounterManager(client(0)); counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).build()); //the counter is lazily created and stored in the cache. The increment will make sure it is there! for (CounterManager cm : clientCounterManagers()) { cm.getStrongCounter(counterName).sync().incrementAndGet(); } } private void assertHits(int primaryOwnerIndex) { for (int i = 0; i < NUM_SERVERS; ++i) { Cache<?, ?> cache = cache(i, CounterModuleLifecycle.COUNTER_CACHE_NAME); HitCountInterceptor interceptor = getHitCountInterceptor(cache); if (i == primaryOwnerIndex) { assertEquals("Wrong number of hits on primary owner", NUM_SERVERS, interceptor.getHits()); } else { assertEquals( "Wrong number of hits on " + address(i) + ". Primary owner is " + address(primaryOwnerIndex), 0, interceptor.getHits()); } } } private int findPrimaryOwnerIndex(String counterName) { CounterKey key = findCounterKey(counterName); for (int i = 0; i < NUM_SERVERS; ++i) { Cache<CounterKey, CounterValue> cache = cache(i, CounterModuleLifecycle.COUNTER_CACHE_NAME); if (cache.getAdvancedCache().getDistributionManager().getCacheTopology().getDistribution(key).isPrimary()) { return i; } } throw new IllegalStateException(); } private CounterKey findCounterKey(String counterName) { ByteString bs = ByteString.fromString(counterName); Cache<CounterKey, CounterValue> cache = cache(0, CounterModuleLifecycle.COUNTER_CACHE_NAME); List<CounterKey> keys = new ArrayList<>(cache.keySet()); for (CounterKey counterKey : keys) { if (counterKey.getCounterName().equals(bs)) { return counterKey; } } throw new IllegalStateException(); } private List<CounterManager> clientCounterManagers() { return clients.stream().map(RemoteCounterManagerFactory::asCounterManager).collect(Collectors.toList()); } }
5,368
37.078014
117
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/counter/BaseCounterAPITest.java
package org.infinispan.client.hotrod.counter; import static org.infinispan.server.hotrod.counter.impl.BaseCounterImplTest.assertNextValidEvent; import static org.infinispan.server.hotrod.counter.impl.BaseCounterImplTest.assertNoEvents; import static org.infinispan.server.hotrod.counter.impl.BaseCounterImplTest.assertValidEvent; import static org.infinispan.test.TestingUtil.extractField; import static org.infinispan.test.TestingUtil.waitForNoRebalance; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.stream.Collectors; import org.infinispan.client.hotrod.counter.impl.NotificationManager; import org.infinispan.client.hotrod.counter.impl.RemoteCounterManager; import org.infinispan.counter.api.CounterEvent; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.Handle; import org.infinispan.counter.impl.CounterModuleLifecycle; import org.infinispan.server.hotrod.counter.impl.BaseCounterImplTest; import org.infinispan.commons.test.ExceptionRunnable; import org.testng.annotations.Test; /** * A base test class for {@link org.infinispan.counter.api.StrongCounter} and {@link * org.infinispan.counter.api.WeakCounter} implementation in the Hot Rod client. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional") public abstract class BaseCounterAPITest<T> extends AbstractCounterTest { private static final CounterListener EXCEPTION_LISTENER = entry -> { throw new RuntimeException("induced"); }; public void testExceptionInListener(Method method) throws InterruptedException { final String counterName = method.getName(); T counter = defineAndCreateCounter(counterName, 0); Handle<BaseCounterImplTest.EventLogger> handle1 = addListenerTo(counter, new BaseCounterImplTest.EventLogger()); Handle<CounterListener> handleEx = addListenerTo(counter, EXCEPTION_LISTENER); Handle<BaseCounterImplTest.EventLogger> handle2 = addListenerTo(counter, new BaseCounterImplTest.EventLogger()); add(counter, 1, 1); add(counter, -1, 0); add(counter, 10, 10); add(counter, 1, 11); add(counter, 2, 13); assertNextValidEvent(handle1, 0, 1); assertNextValidEvent(handle1, 1, 0); assertNextValidEvent(handle1, 0, 10); assertNextValidEvent(handle1, 10, 11); assertNextValidEvent(handle1, 11, 13); assertNextValidEvent(handle2, 0, 1); assertNextValidEvent(handle2, 1, 0); assertNextValidEvent(handle2, 0, 10); assertNextValidEvent(handle2, 10, 11); assertNextValidEvent(handle2, 11, 13); assertNoEvents(handle1); assertNoEvents(handle2); handle1.remove(); handle2.remove(); handleEx.remove(); } public void testConcurrentListenerAddAndRemove(Method method) throws InterruptedException { String counterName = method.getName(); defineAndCreateCounter(counterName, 1); List<T> counters = getCounters(counterName); List<IncrementTask> taskList = counters.stream() .map(IncrementTask::new) .collect(Collectors.toList()); List<Future<?>> futureTaskList = taskList.stream() .map(this::fork) .collect(Collectors.toList()); T counter = counters.get(0); Handle<BaseCounterImplTest.EventLogger> handle = addListenerTo(counter, new BaseCounterImplTest.EventLogger()); //lets wait for at least some events... eventually(() -> handle.getCounterListener().size() > 5); handle.remove(); taskList.forEach(IncrementTask::stop); futureTaskList.forEach(this::awaitFuture); drainAndCheckEvents(handle); assertNoEvents(handle); increment(counter); assertNoEvents(handle); } public void testListenerFailover(Method method) throws Exception { String counterName = method.getName(); T counter = defineAndCreateCounter(counterName, 2); Handle<BaseCounterImplTest.EventLogger> handle = addListenerTo(counter, new BaseCounterImplTest.EventLogger()); add(counter, 1, 3); assertNextValidEvent(handle, 2, 3); InetSocketAddress eventAddress = findEventServer(); int killIndex = -1; for (int i = 0; i < servers.size(); ++i) { if (servers.get(i).getAddress().getPort() == eventAddress.getPort()) { killIndex = i; break; } } assert killIndex != -1; try { killServer(killIndex); add(counter, 1, 4); add(counter, 1, 5); //sometimes, it takes some time to reconnect. //In any case, the first operation triggers a new topology and it should be reconnect after it! CounterEvent event = handle.getCounterListener().waitingPoll(); if (event.getOldValue() == 3) { assertValidEvent(event, 3, 4); assertNextValidEvent(handle, 4, 5); } else { assertValidEvent(event, 4, 5); } handle.remove(); } finally { // Make sure that we don't disturb other tests by ongoing rebalance waitForNoRebalance(caches(CounterModuleLifecycle.COUNTER_CACHE_NAME)); } } abstract void increment(T counter); abstract void add(T counter, long delta, long result); abstract T defineAndCreateCounter(String counterName, long initialValue); abstract <L extends CounterListener> Handle<L> addListenerTo(T counter, L logger); abstract List<T> getCounters(String name); private InetSocketAddress findEventServer() { Object notificationManager = extractField(RemoteCounterManager.class, counterManager(), "notificationManager"); Object dispatcher = extractField(NotificationManager.class, notificationManager, "dispatcher"); SocketAddress address = extractField(dispatcher, "address"); return (InetSocketAddress) address; } private void awaitFuture(Future<?> future) { try { future.get(); } catch (InterruptedException e) { //no-op } catch (ExecutionException e) { throw new RuntimeException(e); } } private void drainAndCheckEvents(Handle<BaseCounterImplTest.EventLogger> handle) throws InterruptedException { //we don't know how many but they must be ordered. //at least, one event! CounterEvent event = handle.getCounterListener().waitingPoll(); log.tracef("First Event=%s", event); long preValue = event.getOldValue(); assertValidEvent(event, preValue, ++preValue); while ((event = handle.getCounterListener().poll()) != null) { log.tracef("Next Event=%s", event); assertValidEvent(event, preValue, ++preValue); } } private class IncrementTask implements ExceptionRunnable { private final T counter; private volatile boolean run; private IncrementTask(T counter) { this.counter = counter; this.run = true; } @Override public void run() { while (run) { increment(counter); } } void stop() { run = false; } } }
7,266
33.117371
118
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/counter/StrongCounterAPITest.java
package org.infinispan.client.hotrod.counter; import java.lang.reflect.Method; import java.util.List; import java.util.stream.Collectors; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.Handle; import org.infinispan.counter.api.StrongCounter; import org.infinispan.server.hotrod.counter.StrongCounterTestStrategy; import org.infinispan.server.hotrod.counter.impl.StrongCounterImplTestStrategy; import org.testng.annotations.Test; /** * A {@link StrongCounter} implementation test. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "client.hotrod.counter.StrongCounterAPITest") public class StrongCounterAPITest extends BaseCounterAPITest<StrongCounter> implements StrongCounterTestStrategy { private final StrongCounterImplTestStrategy strategy; public StrongCounterAPITest() { strategy = new StrongCounterImplTestStrategy(this::counterManager, this::counterManagers); } @Override public void testCompareAndSet(Method method) { strategy.testCompareAndSet(method); } @Override public void testCompareAndSwap(Method method) { strategy.testCompareAndSwap(method); } @Override public void testBoundaries(Method method) { strategy.testBoundaries(method); } @Test(groups = "unstable", description = "ISPN-9053") @Override public void testListenerWithBounds(Method method) throws InterruptedException { strategy.testListenerWithBounds(method); } @Override public void testSet(Method method) { strategy.testSet(method); } @Override public void testAdd(Method method) { strategy.testAdd(method); } @Override public void testReset(Method method) { strategy.testReset(method); } @Override public void testNameAndConfigurationTest(Method method) { strategy.testNameAndConfigurationTest(method); } @Override public void testRemove(Method method) { strategy.testRemove(method); } @Test(groups = "unstable", description = "ISPN-9053") @Override public void testListenerAddAndRemove(Method method) throws InterruptedException { strategy.testListenerAddAndRemove(method); } @Test(groups = "unstable", description = "ISPN-9053") @Override public void testExceptionInListener(Method method) throws InterruptedException { super.testExceptionInListener(method); } @Test(groups = "unstable", description = "ISPN-9053") @Override public void testConcurrentListenerAddAndRemove(Method method) throws InterruptedException { super.testConcurrentListenerAddAndRemove(method); } @Test(groups = "unstable", description = "ISPN-9053") @Override public void testListenerFailover(Method method) throws Exception { super.testListenerFailover(method); } @Override void increment(StrongCounter counter) { counter.sync().incrementAndGet(); } @Override void add(StrongCounter counter, long delta, long result) { strategy.add(counter, delta, result); } @Override StrongCounter defineAndCreateCounter(String counterName, long initialValue) { return strategy.defineAndCreateCounter(counterName, initialValue); } @Override <L extends CounterListener> Handle<L> addListenerTo(StrongCounter counter, L logger) { return strategy.addListenerTo(counter, logger); } @Override List<StrongCounter> getCounters(String name) { return counterManagers().stream() .map(counterManager -> counterManager.getStrongCounter(name)) .collect(Collectors.toList()); } }
3,627
27.566929
114
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/counter/RemoteCounterManagerTest.java
package org.infinispan.client.hotrod.counter; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import java.io.File; import java.lang.reflect.Method; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import org.infinispan.client.hotrod.RemoteCounterManagerFactory; import org.infinispan.commons.util.Util; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.counter.api.CounterManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.counter.CounterManagerTestStrategy; import org.infinispan.server.hotrod.counter.impl.CounterManagerImplTestStrategy; import org.infinispan.util.logging.Log; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * A {@link CounterManager} implementation test. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "client.hotrod.counter.RemoteCounterManagerTest") public class RemoteCounterManagerTest extends AbstractCounterTest implements CounterManagerTestStrategy { private static final String PERSISTENT_LOCATION = tmpDirectory("RemoteCounterManagerTest"); private static final String TMP_LOCATION = Paths.get(PERSISTENT_LOCATION, "tmp").toString(); private static final String SHARED_LOCATION = Paths.get(PERSISTENT_LOCATION,"shared").toString(); private final CounterManagerTestStrategy strategy; public RemoteCounterManagerTest() { strategy = new CounterManagerImplTestStrategy(this::allTestCounterManagers, this::log, this::cacheManager); } @BeforeClass(alwaysRun = true) @Override public void createBeforeClass() throws Throwable { Util.recursiveFileRemove(PERSISTENT_LOCATION); if (!new File(PERSISTENT_LOCATION).mkdirs()) { log.warnf("Unable to create persistent location file: '%s'", PERSISTENT_LOCATION); } super.createBeforeClass(); } @Override public void testWeakCounter(Method method) { strategy.testWeakCounter(method); } @Override public void testUnboundedStrongCounter(Method method) { strategy.testUnboundedStrongCounter(method); } @Override public void testUpperBoundedStrongCounter(Method method) { strategy.testUpperBoundedStrongCounter(method); } @Override public void testLowerBoundedStrongCounter(Method method) { strategy.testLowerBoundedStrongCounter(method); } @Override public void testBoundedStrongCounter(Method method) { strategy.testBoundedStrongCounter(method); } @Override public void testUndefinedCounter() { strategy.testUndefinedCounter(); } @Override public void testRemove(Method method) { strategy.testRemove(method); } @Override public void testGetCounterNames(Method method) { strategy.testGetCounterNames(method); } @AfterClass(alwaysRun = true) @Override protected void destroy() { super.destroy(); Util.recursiveFileRemove(PERSISTENT_LOCATION); } @Override protected void modifyGlobalConfiguration(GlobalConfigurationBuilder builder) { char id = 'A'; id += cacheManagers.size(); builder.globalState().enable() .persistentLocation(Paths.get(PERSISTENT_LOCATION, Character.toString(id)).toString()) .temporaryLocation(TMP_LOCATION) .sharedPersistentLocation(SHARED_LOCATION); } private Log log() { return log; } private List<CounterManager> allTestCounterManagers() { return clients.stream().map(RemoteCounterManagerFactory::asCounterManager).collect(Collectors.toList()); } private EmbeddedCacheManager cacheManager() { return manager(0); } }
3,803
30.180328
113
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/counter/WeakCounterAPITest.java
package org.infinispan.client.hotrod.counter; import java.lang.reflect.Method; import java.util.List; import java.util.stream.Collectors; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.Handle; import org.infinispan.counter.api.WeakCounter; import org.infinispan.server.hotrod.counter.WeakCounterTestStrategy; import org.infinispan.server.hotrod.counter.impl.WeakCounterImplTestStrategy; import org.testng.annotations.Test; /** * A {@link WeakCounter} implementation test. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "client.hotrod.counter.WeakCounterAPITest") public class WeakCounterAPITest extends BaseCounterAPITest<WeakCounter> implements WeakCounterTestStrategy { private final WeakCounterImplTestStrategy strategy; public WeakCounterAPITest() { strategy = new WeakCounterImplTestStrategy(this::counterManager, this::counterManagers); } @Override public void testAdd(Method method) { strategy.testAdd(method); } @Override public void testReset(Method method) { strategy.testReset(method); } @Override public void testNameAndConfigurationTest(Method method) { strategy.testNameAndConfigurationTest(method); } @Override public void testRemove(Method method) { strategy.testRemove(method); } @Test(groups = "unstable", description = "ISPN-9053") @Override public void testListenerAddAndRemove(Method method) throws InterruptedException { strategy.testListenerAddAndRemove(method); } @Test(groups = "unstable", description = "ISPN-9053") @Override public void testExceptionInListener(Method method) throws InterruptedException { super.testExceptionInListener(method); } @Test(groups = "unstable", description = "ISPN-9053") @Override public void testConcurrentListenerAddAndRemove(Method method) throws InterruptedException { super.testConcurrentListenerAddAndRemove(method); } @Test(groups = "unstable", description = "ISPN-9053") @Override public void testListenerFailover(Method method) throws Exception { super.testListenerFailover(method); } @Override void increment(WeakCounter counter) { counter.sync().increment(); } @Override void add(WeakCounter counter, long delta, long result) { strategy.add(counter, delta, result); } @Override WeakCounter defineAndCreateCounter(String counterName, long initialValue) { return strategy.defineAndCreateCounter(counterName, initialValue); } @Override <L extends CounterListener> Handle<L> addListenerTo(WeakCounter counter, L logger) { return strategy.addListenerTo(counter, logger); } @Override List<WeakCounter> getCounters(String name) { return counterManagers().stream() .map(counterManager -> counterManager.getWeakCounter(name)) .collect(Collectors.toList()); } }
2,960
28.61
108
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/counter/AbstractCounterTest.java
package org.infinispan.client.hotrod.counter; import static org.infinispan.client.hotrod.RemoteCounterManagerFactory.asCounterManager; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.infinispan.test.TestingUtil.blockUntilCacheStatusAchieved; import static org.infinispan.test.TestingUtil.blockUntilViewReceived; import java.util.List; import java.util.stream.Collectors; import org.infinispan.client.hotrod.RemoteCounterManagerFactory; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.impl.CounterModuleLifecycle; import org.infinispan.lifecycle.ComponentStatus; import org.testng.annotations.BeforeMethod; /** * A base class for counter tests. * * @author Pedro Ruivo * @since 9.2 */ public abstract class AbstractCounterTest extends MultiHotRodServersTest { private static final int NUMBER_SERVERS = 3; @BeforeMethod(alwaysRun = true) public void restoreServer() { if (servers.size() < NUMBER_SERVERS) { // Start Hot Rod servers while (servers.size() < NUMBER_SERVERS) { addHotRodServer(hotRodCacheConfiguration()); } // Block until views have been received blockUntilViewReceived(manager(0).getCache(), NUMBER_SERVERS); // Verify that caches running for (int i = 0; i < NUMBER_SERVERS; i++) { blockUntilCacheStatusAchieved(manager(i).getCache(), ComponentStatus.RUNNING, 10000); } } waitForClusterToForm(CounterModuleLifecycle.COUNTER_CACHE_NAME); } List<CounterManager> counterManagers() { return clients.stream().map(RemoteCounterManagerFactory::asCounterManager).collect(Collectors.toList()); } CounterManager counterManager() { return asCounterManager(client(0)); } @Override protected void createCacheManagers() throws Throwable { createHotRodServers(NUMBER_SERVERS, hotRodCacheConfiguration()); } }
2,045
34.275862
110
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/DefaultTemplate.java
package org.infinispan.client.hotrod; /** * This enum lists the cache configuration templates names that are available in the server by default. * * @since 10 * @author Katia Aresti */ public enum DefaultTemplate { LOCAL("org.infinispan.LOCAL"), REPL_SYNC("org.infinispan.REPL_SYNC"), REPL_ASYNC("org.infinispan.REPL_ASYNC"), DIST_SYNC("org.infinispan.DIST_SYNC"), DIST_ASYNC("org.infinispan.DIST_ASYNC"), INVALIDATION_SYNC("org.infinispan.INVALIDATION_SYNC"), INVALIDATION_ASYNC("org.infinispan.INVALIDATION_ASYNC"), SCATTERED_SYNC("org.infinispan.SCATTERED_SYNC") ; private final String name; DefaultTemplate(String name) { this.name = name; } /** * Use this method to retrieve the value of a template configured in the infinispan-defaults.xml file * * @return name of the template */ public String getTemplateName() { return name; } }
920
25.314286
104
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/TransportFactory.java
package org.infinispan.client.hotrod; import java.util.concurrent.ExecutorService; import org.infinispan.client.hotrod.impl.transport.netty.DefaultTransportFactory; import org.infinispan.client.hotrod.impl.transport.netty.NativeTransport; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.SocketChannel; /** * TransportFactory is responsible for creating Netty's {@link SocketChannel}s and {@link EventLoopGroup}s. * * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ public interface TransportFactory { TransportFactory DEFAULT = new DefaultTransportFactory(); /** * Returns the Netty {@link SocketChannel} class to use in the transport. */ Class<? extends SocketChannel> socketChannelClass(); /** * Returns the Netty {@link DatagramChannel} class to use for DNS resolution. */ default Class<? extends DatagramChannel> datagramChannelClass() { return NativeTransport.datagramChannelClass(); } /** * Creates an event loop group * * @param maxExecutors the maximum number of executors * @param executorService the executor service to use * @return an instance of Netty's {@link EventLoopGroup} */ EventLoopGroup createEventLoopGroup(int maxExecutors, ExecutorService executorService); }
1,361
31.428571
107
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/package-info.java
/** * Hot Rod client API. * * @api.public */ package org.infinispan.client.hotrod;
87
11.571429
37
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/Versioned.java
package org.infinispan.client.hotrod; /** * Versioned * @author Tristan Tarrant * @since 9.0 */ public interface Versioned { long getVersion(); }
153
14.4
37
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/VersionedValue.java
package org.infinispan.client.hotrod; /** * Besides the key and value, also contains an version. To be used in versioned operations, e.g. {@link * org.infinispan.client.hotrod.RemoteCache#removeWithVersion(Object, long)}. * * @author Mircea.Markus@jboss.com */ public interface VersionedValue<V> extends Versioned { V getValue(); }
342
25.384615
103
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/DataFormat.java
package org.infinispan.client.hotrod; import static org.infinispan.client.hotrod.marshall.MarshallerUtil.bytes2obj; import static org.infinispan.client.hotrod.marshall.MarshallerUtil.obj2bytes; import org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration; import org.infinispan.client.hotrod.impl.MarshallerRegistry; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.AdaptiveBufferSizePredictor; import org.infinispan.commons.marshall.BufferSizePredictor; import org.infinispan.commons.marshall.IdentityMarshaller; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.util.Util; /** * Defines data format for keys and values during Hot Rod client requests. * * @since 9.3 */ public final class DataFormat { private static final Log log = LogFactory.getLog(DataFormat.class, Log.class); private final MediaType keyType; private final MediaType valueType; private final Marshaller keyMarshaller; private final Marshaller valueMarshaller; private MarshallerRegistry marshallerRegistry; private Marshaller defaultMarshaller; private boolean isObjectStorage; private final BufferSizePredictor keySizePredictor = new AdaptiveBufferSizePredictor(); private final BufferSizePredictor valueSizePredictor = new AdaptiveBufferSizePredictor(); private DataFormat(MediaType keyType, MediaType valueType, Marshaller keyMarshaller, Marshaller valueMarshaller) { this.keyType = keyType; this.valueType = valueType; this.keyMarshaller = keyMarshaller; this.valueMarshaller = valueMarshaller; } public DataFormat withoutValueType() { DataFormat dataFormat = new DataFormat(keyType, null, keyMarshaller, null); dataFormat.marshallerRegistry = this.marshallerRegistry; dataFormat.defaultMarshaller = this.defaultMarshaller; dataFormat.isObjectStorage = this.isObjectStorage; return dataFormat; } public MediaType getKeyType() { if (keyType != null) return keyType; Marshaller marshaller = resolveKeyMarshaller(); return marshaller == null ? null : marshaller.mediaType(); } public MediaType getValueType() { if (valueType != null) return valueType; Marshaller marshaller = resolveValueMarshaller(); return marshaller == null ? null : marshaller.mediaType(); } /** * @deprecated Replaced by {@link #initialize(RemoteCacheManager, String, boolean)}. */ @Deprecated public void initialize(RemoteCacheManager remoteCacheManager, boolean serverObjectStorage) { this.marshallerRegistry = remoteCacheManager.getMarshallerRegistry(); this.defaultMarshaller = remoteCacheManager.getMarshaller(); this.isObjectStorage = serverObjectStorage; } public void initialize(RemoteCacheManager remoteCacheManager, String cacheName, boolean serverObjectStorage) { this.marshallerRegistry = remoteCacheManager.getMarshallerRegistry(); this.isObjectStorage = serverObjectStorage; this.defaultMarshaller = remoteCacheManager.getMarshaller(); RemoteCacheConfiguration remoteCacheConfiguration = remoteCacheManager.getConfiguration().remoteCaches().get(cacheName); if (remoteCacheConfiguration != null) { Marshaller cacheMarshaller = remoteCacheConfiguration.marshaller(); if (cacheMarshaller != null) { defaultMarshaller = cacheMarshaller; } else { Class<? extends Marshaller> marshallerClass = remoteCacheConfiguration.marshallerClass(); if (marshallerClass != null) { Marshaller registryMarshaller = marshallerRegistry.getMarshaller(marshallerClass); defaultMarshaller = registryMarshaller != null ? registryMarshaller : Util.getInstance(marshallerClass); } } } } private Marshaller resolveValueMarshaller() { if (valueMarshaller != null) return valueMarshaller; if (valueType == null) return defaultMarshaller; Marshaller forValueType = marshallerRegistry.getMarshaller(valueType); if (forValueType != null) return forValueType; log.debugf("No marshaller registered for %s, using no-op marshaller", valueType); return IdentityMarshaller.INSTANCE; } public boolean isObjectStorage() { return isObjectStorage; } private Marshaller resolveKeyMarshaller() { if (keyMarshaller != null) return keyMarshaller; if (keyType == null) return defaultMarshaller; Marshaller forKeyType = marshallerRegistry.getMarshaller(keyType); if (forKeyType != null) return forKeyType; log.debugf("No marshaller registered for %s, using no-op marshaller", keyType); return IdentityMarshaller.INSTANCE; } /** * @deprecated Since 12.0, will be removed in 15.0 */ @Deprecated public byte[] keyToBytes(Object key, int estimateKeySize, int estimateValueSize) { return keyToBytes(key); } public byte[] keyToBytes(Object key) { Marshaller keyMarshaller = resolveKeyMarshaller(); return obj2bytes(keyMarshaller, key, keySizePredictor); } /** * @deprecated Since 12.0, will be removed in 15.0 */ @Deprecated public byte[] valueToBytes(Object value, int estimateKeySize, int estimateValueSize) { return valueToBytes(value); } public byte[] valueToBytes(Object value) { Marshaller valueMarshaller = resolveValueMarshaller(); return obj2bytes(valueMarshaller, value, valueSizePredictor); } public <T> T keyToObj(byte[] bytes, ClassAllowList allowList) { Marshaller keyMarshaller = resolveKeyMarshaller(); return bytes2obj(keyMarshaller, bytes, isObjectStorage, allowList); } public <T> T valueToObj(byte[] bytes, ClassAllowList allowList) { Marshaller valueMarshaller = resolveValueMarshaller(); return bytes2obj(valueMarshaller, bytes, isObjectStorage, allowList); } @Override public String toString() { return "DataFormat{" + "keyType=" + keyType + ", valueType=" + valueType + ", keyMarshaller=" + keyMarshaller + ", valueMarshaller=" + valueMarshaller + ", marshallerRegistry=" + marshallerRegistry + ", defaultMarshaller=" + defaultMarshaller + '}'; } public static Builder builder() { return new Builder(); } public static class Builder { private MediaType keyType; private MediaType valueType; private Marshaller valueMarshaller; private Marshaller keyMarshaller; public Builder from(DataFormat dataFormat) { this.keyType = dataFormat.keyType; this.valueType = dataFormat.valueType; this.keyMarshaller = dataFormat.keyMarshaller; this.valueMarshaller = dataFormat.valueMarshaller; return this; } public Builder valueMarshaller(Marshaller valueMarshaller) { this.valueMarshaller = valueMarshaller; return this; } public Builder keyMarshaller(Marshaller keyMarshaller) { this.keyMarshaller = keyMarshaller; return this; } public Builder keyType(MediaType keyType) { this.keyType = keyType; return this; } public Builder valueType(MediaType valueType) { this.valueType = valueType; return this; } public DataFormat build() { return new DataFormat(keyType, valueType, keyMarshaller, valueMarshaller); } } }
7,721
35.084112
126
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/CacheTopologyInfo.java
package org.infinispan.client.hotrod; import java.net.SocketAddress; import java.util.Map; import java.util.Set; /** * Contains information about cache topology including servers and owned segments. * * @author gustavonalle * @since 8.0 */ public interface CacheTopologyInfo { /** * @return The number of configured segments for the cache. */ Integer getNumSegments(); /** * @return Segments owned by each server. */ Map<SocketAddress, Set<Integer>> getSegmentsPerServer(); Integer getTopologyId(); }
542
19.111111
82
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/ServerStatistics.java
package org.infinispan.client.hotrod; import java.util.Map; /** * Defines the possible list of statistics defined by the Hot Rod server. * Can be obtained through {@link RemoteCache#stats()} * * @author Mircea.Markus@jboss.com * @since 4.1 */ public interface ServerStatistics { /** * Number of seconds since Hot Rod started. */ String TIME_SINCE_START = "timeSinceStart"; /** * Number of entries currently in the Hot Rod server * @deprecated Since 14.0, please use {@link #APPROXIMATE_ENTRIES} */ @Deprecated String CURRENT_NR_OF_ENTRIES = "currentNumberOfEntries"; /** * Approximate current number of entry replicas in the cache on the server that receives the request. * * <p>Includes both entries in memory and in persistent storage.</p> */ String APPROXIMATE_ENTRIES = "approximateEntries"; /** * Approximate current number of entries for which the server that receives the request is the primary owner. * * <p>Includes both entries in memory and in persistent storage.</p> */ String APPROXIMATE_ENTRIES_UNIQUE = "approximateEntriesUnique"; /** * Number of entries stored in the cache by the server that receives the request since the cache started running. */ String STORES = "stores"; /** * Number of get operations. */ String RETRIEVALS = "retrievals"; /** * Number of get hits. */ String HITS = "hits"; /** * Number of get misses. */ String MISSES = "misses"; /** * Number of removal hits. */ String REMOVE_HITS = "removeHits"; /** * Number of removal misses. */ String REMOVE_MISSES = "removeMisses"; /** * Approximate current number of entry replicas currently in the cache cluster-wide. * * <p>Includes both entries in memory and in persistent storage.</p> */ String CLUSTER_APPROXIMATE_ENTRIES = "globalApproximateEntries"; /** * Approximate current number of unique entries in the cache cluster-wide. * * <p>Includes both entries in memory and in persistent storage. * Entries owned by multiple nodes are counted only once.</p> */ String CLUSTER_APPROXIMATE_ENTRIES_UNIQUE = "globalApproximateEntriesUnique"; Map<String, String> getStatsMap(); String getStatistic(String statsName); Integer getIntStatistic(String statsName); }
2,387
24.677419
116
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/FailoverRequestBalancingStrategy.java
package org.infinispan.client.hotrod; import java.net.SocketAddress; import java.util.Collection; import java.util.Set; import net.jcip.annotations.NotThreadSafe; /** * Defines what servers will be selected when a smart-routed request fails. */ @NotThreadSafe public interface FailoverRequestBalancingStrategy { /** * Inform the strategy about the currently alive servers. * @param servers */ void setServers(Collection<SocketAddress> servers); /** * @param failedServers * @return Address of the next server the request should be routed to. */ SocketAddress nextServer(Set<SocketAddress> failedServers); }
649
24
75
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/MetadataValue.java
package org.infinispan.client.hotrod; /** * Besides the value, also contains a version and expiration information. Time values are server * time representations as returned by {@link org.infinispan.commons.time.TimeService#wallClockTime} * * @author Tristan Tarrant * @since 5.2 */ public interface MetadataValue<V> extends VersionedValue<V>, Metadata { }
364
27.076923
100
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/RemoteCache.java
package org.infinispan.client.hotrod; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.jmx.RemoteCacheClientStatisticsMXBean; import org.infinispan.commons.api.BasicCache; import org.infinispan.commons.api.TransactionalCache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.CloseableIteratorCollection; import org.infinispan.commons.util.CloseableIteratorSet; import org.infinispan.commons.util.IntSet; import org.infinispan.query.dsl.Query; import org.reactivestreams.Publisher; /** * Provides remote reference to a Hot Rod server/cluster. It implements {@link BasicCache}, but given its * nature (remote) some operations are not supported. All these unsupported operations are being overridden within this * interface and documented as such. * <p/> * <b>New operations</b>: besides the operations inherited from {@link BasicCache}, RemoteCache also adds new * operations to optimize/reduce network traffic: e.g. versioned put operation. * <p/> * <b>Concurrency</b>: implementors of this interface will support multi-threaded access, similar to the way {@link * BasicCache} supports it. * <p/> * <b>Return values</b>: previously existing values for certain {@link java.util.Map} operations are not returned, null * is returned instead. E.g. {@link java.util.Map#put(Object, Object)} returns the previous value associated to the * supplied key. In case of RemoteCache, this returns null. * <p/> * <b>Changing default behavior through {@link org.infinispan.client.hotrod.Flag}s</b>: it is possible to change the * default cache behaviour by using flags on an per invocation basis. E.g. * <pre> * RemoteCache cache = getRemoteCache(); * Object oldValue = cache.withFlags(Flag.FORCE_RETURN_VALUE).put(aKey, aValue); * </pre> * In the previous example, using {@link org.infinispan.client.hotrod.Flag#FORCE_RETURN_VALUE} will make the client to * also return previously existing value associated with <tt>aKey</tt>. If this flag would not be present, Infinispan * would return (by default) <tt>null</tt>. This is in order to avoid fetching a possibly large object from the remote * server, which might not be needed. The flags as set by the {@link org.infinispan.client.hotrod.RemoteCache#withFlags(Flag...)} * operation only apply for the very next operation executed <b>by the same thread</b> on the RemoteCache. * <p/> * * <b>Note on default expiration values:</b> Due to limitations on the first * version of the protocol, it's not possible for clients to rely on default * lifespan and maxIdle values set on the server. This is because the protocol * does not support a way to tell the server that no expiration lifespan and/or * maxIdle were provided and that default values should be used. This will be * resolved in a future revision of the protocol. In the mean time, the * workaround is to explicitly provide the desired expiry lifespan/maxIdle * values in each remote cache operation. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public interface RemoteCache<K, V> extends BasicCache<K, V>, TransactionalCache { /** * Removes the given entry only if its version matches the supplied version. A typical use case looks like this: * <pre> * VersionedEntry ve = remoteCache.getVersioned(key); * //some processing * remoteCache.removeWithVersion(key, ve.getVersion(); * </pre> * Lat call (removeWithVersion) will make sure that the entry will only be removed if it hasn't been changed in * between. * * @return true if the entry has been removed * @see VersionedValue * @see #getWithMetadata(Object) */ boolean removeWithVersion(K key, long version); /** * {@inheritDoc} * <p> * The returned value is only sent back if {@link Flag#FORCE_RETURN_VALUE} is enabled. */ @Override V remove(Object key); /** * {@inheritDoc} * <p> * This method requires 2 round trips to the server. The first to retrieve the value and version and a second to * remove the key with the version if the value matches. If possible user should use * {@link RemoteCache#getWithMetadata(Object)} and {@link RemoteCache#removeWithVersion(Object, long)}. */ @Override boolean remove(Object key, Object value); /** * {@inheritDoc} * <p> * This method requires 2 round trips to the server. The first to retrieve the value and version and a second to * replace the key with the version if the value matches. If possible user should use * {@link RemoteCache#getWithMetadata(Object)} and * {@link RemoteCache#replaceWithVersion(Object, Object, long)}. */ @Override boolean replace(K key, V oldValue, V newValue); /** * {@inheritDoc} * <p> * This method requires 2 round trips to the server. The first to retrieve the value and version and a second to * replace the key with the version if the value matches. If possible user should use * {@link RemoteCache#getWithMetadata(Object)} and * {@link RemoteCache#replaceWithVersion(Object, Object, long, long, TimeUnit, long, TimeUnit)}. */ @Override boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit unit); /** * {@inheritDoc} * <p> * This method requires 2 round trips to the server. The first to retrieve the value and version and a second to * replace the key with the version if the value matches. If possible user should use * {@link RemoteCache#getWithMetadata(Object)} and * {@link RemoteCache#replaceWithVersion(Object, Object, long, long, TimeUnit, long, TimeUnit)} if possible. */ @Override boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit); /** * @see #remove(Object, Object) */ CompletableFuture<Boolean> removeWithVersionAsync(K key, long version); /** * Replaces the given value only if its version matches the supplied version. * See {@link #removeWithVersion(Object, long)} for a sample usage of the * version-based methods. * * @param version numeric version that should match the one in the server * for the operation to succeed * @return true if the value has been replaced * @see #getWithMetadata(Object) * @see VersionedValue */ boolean replaceWithVersion(K key, V newValue, long version); /** * A overloaded form of {@link #replaceWithVersion(Object, Object, long)} * which takes in lifespan parameters. * * @param key key to use * @param newValue new value to be associated with the key * @param version numeric version that should match the one in the server * for the operation to succeed * @param lifespanSeconds lifespan of the entry * @return true if the value was replaced */ boolean replaceWithVersion(K key, V newValue, long version, int lifespanSeconds); /** * A overloaded form of {@link #replaceWithVersion(Object, Object, long)} * which takes in lifespan and maximum idle time parameters. * * @param key key to use * @param newValue new value to be associated with the key * @param version numeric version that should match the one in the server * for the operation to succeed * @param lifespanSeconds lifespan of the entry * @param maxIdleTimeSeconds the maximum amount of time this key is allowed * to be idle for before it is considered as expired * @return true if the value was replaced */ boolean replaceWithVersion(K key, V newValue, long version, int lifespanSeconds, int maxIdleTimeSeconds); /** * A overloaded form of {@link #replaceWithVersion(Object, Object, long)} * which takes in lifespan and maximum idle time parameters. * * @param key key to use * @param newValue new value to be associated with the key * @param version numeric version that should match the one in the server * for the operation to succeed * @param lifespan lifespan of the entry * @param lifespanTimeUnit {@link java.util.concurrent.TimeUnit} for lifespan * @param maxIdle the maximum amount of time this key is allowed * to be idle for before it is considered as expired * @param maxIdleTimeUnit {@link java.util.concurrent.TimeUnit} for maxIdle * @return true if the value was replaced */ boolean replaceWithVersion(K key, V newValue, long version, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit); /** * @see #replaceWithVersion(Object, Object, long) */ CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version); /** * @see #replaceWithVersion(Object, Object, long) */ CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version, int lifespanSeconds); /** * @see #replaceWithVersion(Object, Object, long) */ CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version, int lifespanSeconds, int maxIdleSeconds); /** * @see #replaceWithVersion(Object, Object, long) */ CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version, long lifespanSeconds, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit); /** * @see #retrieveEntries(String, Object[], java.util.Set, int) */ default CloseableIterator<Entry<Object, Object>> retrieveEntries(String filterConverterFactory, Set<Integer> segments, int batchSize) { return retrieveEntries(filterConverterFactory, null, segments, batchSize); } /** * Retrieve entries from the server. * * @param filterConverterFactory Factory name for the KeyValueFilterConverter or null for no filtering. * @param filterConverterParams Parameters to the KeyValueFilterConverter * @param segments The segments to iterate. If null all segments will be iterated. An empty set will filter out all entries. * @param batchSize The number of entries transferred from the server at a time. * @return Iterator for the entries */ CloseableIterator<Entry<Object, Object>> retrieveEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize); /** * Publishes the entries from the server in a non blocking fashion. * <p> * Any subscriber that subscribes to the returned Publisher must not block. It is therefore recommended to offload * any blocking or long running operations to a different thread and not use the invoking one. Failure to do so * may cause concurrent operations to stall. * @param filterConverterFactory Factory name for the KeyValueFilterConverter or null for no filtering. * @param filterConverterParams Parameters to the KeyValueFilterConverter * @param segments The segments to utilize. If null all segments will be utilized. An empty set will filter out all entries. * @param batchSize The number of entries transferred from the server at a time. * @return Publisher for the entries */ <E> Publisher<Entry<K, E>> publishEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize); /** * @see #retrieveEntries(String, Object[], java.util.Set, int) */ default CloseableIterator<Entry<Object, Object>> retrieveEntries(String filterConverterFactory, int batchSize) { return retrieveEntries(filterConverterFactory, null, null, batchSize); } /** * Retrieve entries from the server matching a query. * * @param filterQuery {@link Query} * @param segments The segments to iterate. If null all segments will be iterated. An empty set will filter out all entries. * @param batchSize The number of entries transferred from the server at a time. * @return {@link CloseableIterator} */ CloseableIterator<Entry<Object, Object>> retrieveEntriesByQuery(Query<?> filterQuery, Set<Integer> segments, int batchSize); /** * Publish entries from the server matching a query. * <p> * Any subscriber that subscribes to the returned Publisher must not block. It is therefore recommended to offload * any blocking or long running operations to a different thread and not use the invoking one. Failure to do so * may cause concurrent operations to stall. * @param filterQuery {@link Query} * @param segments The segments to utilize. If null all segments will be utilized. An empty set will filter out all entries. * @param batchSize The number of entries transferred from the server at a time. * @return Publisher containing matching entries */ <E> Publisher<Entry<K, E>> publishEntriesByQuery(Query<?> filterQuery, Set<Integer> segments, int batchSize); /** * Retrieve entries with metadata information */ CloseableIterator<Entry<Object, MetadataValue<Object>>> retrieveEntriesWithMetadata(Set<Integer> segments, int batchSize); /** * Publish entries with metadata information * <p> * Any subscriber that subscribes to the returned Publisher must not block. It is therefore recommended to offload * any blocking or long running operations to a different thread and not use the invoking one. Failure to do so * may cause concurrent operations to stall. * @param segments The segments to utilize. If null all segments will be utilized. An empty set will filter out all entries. * @param batchSize The number of entries transferred from the server at a time. * @return Publisher containing entries along with metadata */ Publisher<Entry<K, MetadataValue<V>>> publishEntriesWithMetadata(Set<Integer> segments, int batchSize); /** * Returns the {@link MetadataValue} associated to the supplied key param, or null if it doesn't exist. */ MetadataValue<V> getWithMetadata(K key); /** * Asynchronously returns the {@link MetadataValue} associated to the supplied key param, or null if it doesn't exist. */ CompletableFuture<MetadataValue<V>> getWithMetadataAsync(K key); /** * @inheritDoc * <p> * Due to this set being backed by the remote cache, each invocation on this set may require remote invocations * to retrieve or update the remote cache. The main benefit of this set being backed by the remote cache is that * this set internally does not require having to store any keys locally in memory and allows for the user to * iteratively retrieve keys from the cache which is more memory conservative. * <p> * If you do wish to create a copy of this set (requires all entries in memory), the user may invoke * <code>keySet().stream().collect(Collectors.toSet())</code> to copy the data locally. Then all operations on the * resulting set will not require remote access, however updates will not be reflected from the remote cache. * <p> * NOTE: this method returns a {@link CloseableIteratorSet} which requires the iterator, spliterator or stream * returned from it to be closed. Failure to do so may cause additional resources to not be freed. */ @Override default CloseableIteratorSet<K> keySet() { return keySet(null); } /** * This method is identical to {@link #keySet()} except that it will only return keys that map to the given segments. * Note that these segments will be determined by the remote server. Thus you should be aware of how many segments * it has configured and hashing algorithm it is using. If the segments and hashing algorithm are not the same * this method may return unexpected keys. * @param segments the segments of keys to return - null means all available * @return set containing keys that map to the given segments * @see #keySet() * @since 9.4 */ CloseableIteratorSet<K> keySet(IntSet segments); /** * @inheritDoc * <p> * Due to this collection being backed by the remote cache, each invocation on this collection may require remote * invocations to retrieve or update the remote cache. The main benefit of this collection being backed by the remote * cache is that this collection internally does not require having to store any values locally in memory and allows * for the user to iteratively retrieve values from the cache which is more memory conservative. * <p> * If you do wish to create a copy of this collection (requires all entries in memory), the user may invoke * <code>values().stream().collect(Collectors.toList())</code> to copy the data locally. Then all operations on the * resulting list will not require remote access, however updates will not be reflected from the remote cache. * <p> * NOTE: this method returns a {@link CloseableIteratorCollection} which requires the iterator, spliterator or stream * returned from it to be closed. Failure to do so may cause additional resources to not be freed. */ @Override default CloseableIteratorCollection<V> values() { return values(null); } /** * This method is identical to {@link #values()} except that it will only return values that map to the given segments. * Note that these segments will be determined by the remote server. Thus you should be aware of how many segments * it has configured and hashing algorithm it is using. If the segments and hashing algorithm are not the same * this method may return unexpected values. * @param segments the segments of values to return - null means all available * @return collection containing values that map to the given segments * @see #values() * @since 9.4 */ CloseableIteratorCollection<V> values(IntSet segments); /** * @inheritDoc * <p> * Due to this set being backed by the remote cache, each invocation on this set may require remote invocations * to retrieve or update the remote cache. The main benefit of this set being backed by the remote cache is that * this set internally does not require having to store any entries locally in memory and allows for the user to * iteratively retrieve entries from the cache which is more memory conservative. * <p> * The {@link CloseableIteratorSet#remove(Object)} method requires two round trips to the server to properly remove * an entry. This is because they first must retrieve the value and version * to see if it matches and if it does remove it using it's version. * <p> * If you do wish to create a copy of this set (requires all entries in memory), the user may invoke * <code>entrySet().stream().collect(Collectors.toSet())</code> to copy the data locally. Then all operations on the * resulting set will not require remote access, however updates will not be reflected from the remote cache. * <p> * NOTE: this method returns a {@link CloseableIteratorSet} which requires the iterator, spliterator or stream * returned from it to be closed. Failure to do so may cause additional resources to not be freed. */ @Override default CloseableIteratorSet<Entry<K, V>> entrySet() { return entrySet(null); } /** * This method is identical to {@link #entrySet()} except that it will only return entries that map to the given segments. * Note that these segments will be determined by the remote server. Thus you should be aware of how many segments * it has configured and hashing algorithm it is using. If the segments and hashing algorithm are not the same * this method may return unexpected entries. * @param segments the segments of entries to return - null means all available * @return set containing entries that map to the given segments * @see #entrySet() * @since 9.4 */ CloseableIteratorSet<Entry<K, V>> entrySet(IntSet segments); /** * Adds or overrides each specified entry in the remote cache. This operation provides better performance than calling put() for each entry. */ @Override void putAll(Map<? extends K, ? extends V> map, long lifespan, TimeUnit unit); /** * Adds or overrides each specified entry in the remote cache. This operation provides better performance than calling put() for each entry. * * @see #putAll(java.util.Map, long, java.util.concurrent.TimeUnit) */ @Override void putAll(Map<? extends K, ? extends V> map, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit); /** * Adds or overrides each specified entry in the remote cache. This operation provides better performance than calling put() for each entry. * * @see #putAll(java.util.Map, long, java.util.concurrent.TimeUnit) */ @Override CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data); /** * Adds or overrides each specified entry in the remote cache. This operation provides better performance than calling put() for each entry. * * @see #putAll(java.util.Map, long, java.util.concurrent.TimeUnit) */ @Override CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data, long lifespan, TimeUnit unit); /** * Adds or overrides each specified entry in the remote cache. This operation provides better performance than calling put() for each entry. * * @see #putAll(java.util.Map, long, java.util.concurrent.TimeUnit) */ @Override CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); /** * Adds or overrides each specified entry in the remote cache. This operation provides better performance than calling put() for each entry. * * @see #putAll(java.util.Map, long, java.util.concurrent.TimeUnit) */ @Override void putAll(Map<? extends K, ? extends V> m); /** * Returns server-side statistics for this cache. * @deprecated use {@link #serverStatistics()} instead */ @Deprecated default ServerStatistics stats() { return serverStatistics(); } /** * Returns client-side statistics for this cache. */ RemoteCacheClientStatisticsMXBean clientStatistics(); /** * Returns server-side statistics for this cache. */ ServerStatistics serverStatistics(); /** * Returns server-side statistics for this cache. */ CompletionStage<ServerStatistics> serverStatisticsAsync(); /** * Applies one or more {@link Flag}s to the scope of a single invocation. See the {@link Flag} enumeration to for * information on available flags. * <p /> * Sample usage: * <pre> * remoteCache.withFlags(Flag.FORCE_RETURN_VALUE).put("hello", "world"); * </pre> * @param flags * @return the current RemoteCache instance to continue running operations on. */ RemoteCache<K, V> withFlags(Flag... flags); /** * Returns the {@link org.infinispan.client.hotrod.RemoteCacheContainer} that created this cache. */ RemoteCacheContainer getRemoteCacheContainer(); /** * Returns the {@link org.infinispan.client.hotrod.RemoteCacheManager} that created this cache. * @deprecated Since 14.0. Use {@link #getRemoteCacheContainer()} instead. */ @Deprecated default RemoteCacheManager getRemoteCacheManager() { return (RemoteCacheManager) this.getRemoteCacheContainer(); } /** * Retrieves all of the entries for the provided keys. A key will not be present in * the resulting map if the entry was not found in the cache. * @param keys The keys to find values for * @return The entries that were present for the given keys */ public Map<K, V> getAll(Set<? extends K> keys); /** * Returns the HotRod protocol version supported by this RemoteCache implementation */ String getProtocolVersion(); /** * Add a client listener to receive events that happen in the remote cache. * The listener object must be annotated with @{@link org.infinispan.client.hotrod.annotation.ClientListener} annotation. */ void addClientListener(Object listener); /** * Add a client listener to receive events that happen in the remote cache. * The listener object must be annotated with @ClientListener annotation. */ void addClientListener(Object listener, Object[] filterFactoryParams, Object[] converterFactoryParams); /** * Remove a previously added client listener. If the listener was not added * before, this operation is a no-op. */ void removeClientListener(Object listener); /** * Returns a set with all the listeners registered by this client for the * given cache. * * @deprecated Since 10.0, with no replacement */ @Deprecated Set<Object> getListeners(); /** * Executes a remote task without passing any parameters */ default <T> T execute(String taskName) { return execute(taskName, Collections.emptyMap()); } /** * Executes a remote task passing a set of named parameters */ <T> T execute(String taskName, Map<String, ?> params); /** * Executes a remote task passing a set of named parameters, hinting that the task should be executed * on the server that is expected to store given key. The key itself is not transferred to the server. */ default <T> T execute(String taskName, Map<String, ?> params, Object key) { return execute(taskName, params); } /** * Returns {@link CacheTopologyInfo} for this cache. */ CacheTopologyInfo getCacheTopologyInfo(); /** * Returns a cache where values are manipulated using {@link java.io.InputStream} and {@link java.io.OutputStream} */ StreamingRemoteCache<K> streaming(); /** * Return a new instance of {@link RemoteCache} using the supplied {@link DataFormat}. */ <T, U> RemoteCache<T, U> withDataFormat(DataFormat dataFormat); /** * Return the currently {@link DataFormat} being used. */ DataFormat getDataFormat(); /** * @return {@code true} if the cache can participate in a transaction, {@code false} otherwise. */ boolean isTransactional(); }
26,512
44.554983
176
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/StreamingRemoteCache.java
package org.infinispan.client.hotrod; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.TimeUnit; /** * StreamingRemoteCache implements streaming versions of most {@link RemoteCache} methods * * @author Tristan Tarrant * @since 9.0 */ public interface StreamingRemoteCache<K> { /** * Retrieves the value of the specified key as an {@link InputStream}. It is up to the application to ensure * that the stream is consumed and closed. The marshaller is ignored, i.e. all data will be read in its * raw binary form. The returned input stream implements the {@link VersionedMetadata} interface. * The returned input stream is not thread-safe. * * @param key key to use */ <T extends InputStream & VersionedMetadata> T get(K key); /** * Initiates a streaming put operation. It is up to the application to write to the returned {@link OutputStream} * and close it when there is no more data to write. The marshaller is ignored, i.e. all data will be written in its * raw binary form. The returned output stream is not thread-safe. * * @param key key to use */ OutputStream put(K key); /** * An overloaded form of {@link #put(Object)}, which takes in lifespan parameters. * The returned output stream is not thread-safe. * * @param key key to use * @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan. * @param lifespanUnit unit of measurement for the lifespan */ OutputStream put(K key, long lifespan, TimeUnit lifespanUnit); /** * An overloaded form of {@link #put(Object)}, which takes in lifespan and maxIdle parameters. * The returned output stream is not thread-safe. * * @param key key to use * @param lifespan lifespan of the entry * @param lifespanUnit {@link java.util.concurrent.TimeUnit} for lifespan * @param maxIdle the maximum amount of time this key is allowed * to be idle for before it is considered as expired * @param maxIdleUnit {@link java.util.concurrent.TimeUnit} for maxIdle */ OutputStream put(K key, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); /** * A conditional form of put which inserts an entry into the cache only if no mapping for the key is already present. * The operation is atomic. The server only performs the operation once the stream has been closed. * The returned output stream is not thread-safe. * * @param key key to use */ OutputStream putIfAbsent(K key); /** * An overloaded form of {@link #putIfAbsent(Object)} which takes in lifespan parameters. * The returned output stream is not thread-safe. * * @param key key to use * @param lifespan lifespan of the entry * @param lifespanUnit {@link java.util.concurrent.TimeUnit} for lifespan */ OutputStream putIfAbsent(K key, long lifespan, TimeUnit lifespanUnit); /** * An overloaded form of {@link #putIfAbsent(Object)} which takes in lifespan and maxIdle parameters. * The returned output stream is not thread-safe. * * @param key key to use * @param lifespan lifespan of the entry * @param lifespanUnit {@link java.util.concurrent.TimeUnit} for lifespan * @param maxIdle the maximum amount of time this key is allowed * to be idle for before it is considered as expired * @param maxIdleUnit {@link java.util.concurrent.TimeUnit} for maxIdle */ OutputStream putIfAbsent(K key, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); /** * A form of {@link #put(Object)}, which takes in a version. The value will be replaced on the server only if * the existing entry's version matches. The returned output stream is not thread-safe. * * @param key key to use * @param version the version to check for */ OutputStream replaceWithVersion(K key, long version); /** * An overloaded form of {@link #replaceWithVersion(Object, long)} which takes in lifespan parameters. * The returned output stream is not thread-safe. * * @param key key to use * @param version the version to check for * @param lifespan lifespan of the entry * @param lifespanUnit {@link java.util.concurrent.TimeUnit} for lifespan */ OutputStream replaceWithVersion(K key, long version, long lifespan, TimeUnit lifespanUnit); /** * An overloaded form of {@link #replaceWithVersion(Object, long)} which takes in lifespan and maxIdle parameters. * The returned output stream is not thread-safe. * * @param key key to use * @param version the version to check for * @param lifespan lifespan of the entry * @param lifespanUnit {@link java.util.concurrent.TimeUnit} for lifespan * @param maxIdle the maximum amount of time this key is allowed * to be idle for before it is considered as expired * @param maxIdleUnit {@link java.util.concurrent.TimeUnit} for maxIdle */ OutputStream replaceWithVersion(K key, long version, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); }
5,293
42.393443
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/Search.java
package org.infinispan.client.hotrod; import org.infinispan.client.hotrod.event.impl.ContinuousQueryImpl; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.impl.query.RemoteQueryFactory; import org.infinispan.query.api.continuous.ContinuousQuery; import org.infinispan.query.dsl.QueryFactory; /** * @author anistor@redhat.com * @since 6.0 */ public final class Search { private Search() { } public static QueryFactory getQueryFactory(RemoteCache<?, ?> cache) { if (cache == null) { throw new IllegalArgumentException("cache parameter cannot be null"); } return new RemoteQueryFactory((InternalRemoteCache<?, ?>) cache); } public static <K, V> ContinuousQuery<K, V> getContinuousQuery(RemoteCache<K, V> cache) { return new ContinuousQueryImpl<>(cache); } }
864
27.833333
91
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/RemoteCacheManagerAdmin.java
package org.infinispan.client.hotrod; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.configuration.BasicConfiguration; /** * Remote Administration operations * * @author Tristan Tarrant * @since 9.1 */ public interface RemoteCacheManagerAdmin extends CacheContainerAdmin<RemoteCacheManagerAdmin, BasicConfiguration> { /** * Creates a cache on the remote server cluster using the specified template name. * * @param name the name of the cache to create * @param template the template to use for the cache. If null, the configuration marked as default on the server * will be used * @return the cache * @throws HotRodClientException */ @Override <K, V> RemoteCache<K, V> createCache(String name, String template) throws HotRodClientException; /** * Creates a cache on the remote server cluster using the specified default configuration template * present in the server. * * @param name the name of the cache to create * @param template {@link DefaultTemplate} enum * @return the cache * @throws HotRodClientException */ <K, V> RemoteCache<K, V> createCache(String name, DefaultTemplate template) throws HotRodClientException; /** * Creates a cache on the remote server cluster using the specified configuration * * @param name the name of the cache to create * @param configuration a concrete cache configuration that will be sent to the server in one of the supported formats: * XML, JSON, and YAML. The server detects the format automatically. The configuration must conform * to the Infinispan embedded configuration schema version that is supported by the server. * * @return the cache * @throws HotRodClientException */ @Override <K, V> RemoteCache<K, V> createCache(String name, BasicConfiguration configuration) throws HotRodClientException; /** * Retrieves an existing cache on the remote server cluster. If it doesn't exist, it will be created using the * specified template name. * * @param name the name of the cache to create * @param template the template to use for the cache. If null, the configuration marked as default on the server * will be used * @return the cache * @throws HotRodClientException */ @Override <K, V> RemoteCache<K, V> getOrCreateCache(String name, String template) throws HotRodClientException; /** * Retrieves an existing cache on the remote server cluster. If it doesn't exist, it will be created using the * specified default template that is present in the server. * * @param name the name of the cache to create * @param template {@link DefaultTemplate} enum * @return the cache * @throws HotRodClientException */ <K, V> RemoteCache<K, V> getOrCreateCache(String name, DefaultTemplate template) throws HotRodClientException; /** * Retrieves an existing cache on the remote server cluster. If it doesn't exist, it will be created using the * specified configuration. * * @param name the name of the cache to create * @param configuration a concrete cache configuration of that will be sent to the server in one of the supported formats: * XML, JSON and YAML. The format will be detected automatically. The configuration must use the * Infinispan embedded configuration schema in a version supported by the server. * @return the cache * @throws HotRodClientException */ @Override <K, V> RemoteCache<K, V> getOrCreateCache(String name, BasicConfiguration configuration) throws HotRodClientException; /** * Removes a cache from the remote server cluster. * * @param name the name of the cache to remove * @throws HotRodClientException */ @Override void removeCache(String name) throws HotRodClientException; /** * Performs a mass reindexing of the specified cache. The command will return immediately and the reindexing will * be performed asynchronously * @param name the name of the cache to reindex * @throws HotRodClientException */ void reindexCache(String name) throws HotRodClientException; /** * Updates the index schema state for the given cache, * the cache engine is hot restarted so that index persisted or not persisted state will be preserved. * * @param cacheName the name of the cache on which the index schema will be updated * @throws HotRodClientException */ void updateIndexSchema(String cacheName) throws HotRodClientException; /** * Updates a mutable configuration attribute for the given cache. * * @param cacheName the name of the cache on which the attribute will be updated * @param attribute the path of the attribute we want to change * @param value the new value to apply to the attribute * @throws HotRodClientException */ void updateConfigurationAttribute(String cacheName, String attribute, String value) throws HotRodClientException; }
5,228
40.173228
125
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/RemoteCacheManager.java
package org.infinispan.client.hotrod; import static org.infinispan.client.hotrod.impl.Util.await; import static org.infinispan.client.hotrod.impl.Util.checkTransactionSupport; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.management.MBeanServer; import javax.management.ObjectName; import jakarta.transaction.TransactionManager; import javax.transaction.xa.XAResource; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.configuration.NearCacheConfiguration; import org.infinispan.client.hotrod.configuration.NearCacheMode; import org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration; import org.infinispan.client.hotrod.configuration.StatisticsConfiguration; import org.infinispan.client.hotrod.configuration.TransactionMode; import org.infinispan.client.hotrod.counter.impl.RemoteCounterManager; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.HotRodURI; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.impl.InvalidatedNearRemoteCache; import org.infinispan.client.hotrod.impl.MarshallerRegistry; import org.infinispan.client.hotrod.impl.RemoteCacheImpl; import org.infinispan.client.hotrod.impl.RemoteCacheManagerAdminImpl; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.operations.PingResponse; import org.infinispan.client.hotrod.impl.protocol.CodecHolder; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transaction.SyncModeTransactionTable; import org.infinispan.client.hotrod.impl.transaction.TransactionOperationFactory; import org.infinispan.client.hotrod.impl.transaction.TransactionTable; import org.infinispan.client.hotrod.impl.transaction.TransactionalRemoteCacheImpl; import org.infinispan.client.hotrod.impl.transaction.XaModeTransactionTable; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.jmx.RemoteCacheManagerMXBean; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.client.hotrod.marshall.BytesOnlyMarshaller; import org.infinispan.client.hotrod.near.NearCacheService; import org.infinispan.client.hotrod.transaction.lookup.GenericTransactionManagerLookup; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.commons.executors.ExecutorFactory; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.commons.marshall.UserContextInitializerImpl; import org.infinispan.commons.time.DefaultTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.commons.util.GlobUtils; import org.infinispan.commons.util.Util; import org.infinispan.commons.util.Version; import org.infinispan.counter.api.CounterManager; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; /** * <p>Factory for {@link RemoteCache}s.</p> * <p>In order to be able to use a {@link RemoteCache}, the * {@link RemoteCacheManager} must be started first: this instantiates connections to Hot Rod server(s). Starting the * {@link RemoteCacheManager} can be done either at creation by passing start==true to the constructor or by using a * constructor that does that for you; or after construction by calling {@link #start()}.</p> * <p><b>NOTE:</b> this is an "expensive" object, as it manages a set of persistent TCP connections to the Hot Rod * servers. It is recommended to only have one instance of this per JVM, and to cache it between calls to the server * (i.e. remoteCache operations)</p> * <p>{@link #stop()} needs to be called explicitly in order to release all the resources (e.g. threads, * TCP connections).</p> * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class RemoteCacheManager implements RemoteCacheContainer, Closeable, RemoteCacheManagerMXBean { private static final Log log = LogFactory.getLog(RemoteCacheManager.class); public static final String HOTROD_CLIENT_PROPERTIES = "hotrod-client.properties"; public static final String JSON_STRING_ARRAY_ELEMENT_REGEX = "(?:\")([^\"]*)(?:\",?)"; private volatile boolean started = false; private final Map<RemoteCacheKey, RemoteCacheHolder> cacheName2RemoteCache = new HashMap<>(); private final MarshallerRegistry marshallerRegistry = new MarshallerRegistry(); private final Configuration configuration; private Marshaller marshaller; protected ChannelFactory channelFactory; protected ClientListenerNotifier listenerNotifier; private final Runnable start = this::start; private final Runnable stop = this::stop; private final RemoteCounterManager counterManager; private final TransactionTable syncTransactionTable; private final XaModeTransactionTable xaTransactionTable; private ObjectName mbeanObjectName; private TimeService timeService = DefaultTimeService.INSTANCE; private ExecutorService asyncExecutorService; /** * Create a new RemoteCacheManager using the supplied {@link Configuration}. The RemoteCacheManager will be started * automatically * * @param configuration the configuration to use for this RemoteCacheManager * @since 5.3 */ public RemoteCacheManager(Configuration configuration) { this(configuration, true); } /** * Create a new RemoteCacheManager using the supplied URI. The RemoteCacheManager will be started * automatically * * @param uri the URI to use for this RemoteCacheManager * @since 11.0 */ public RemoteCacheManager(String uri) { this(HotRodURI.create(uri)); } /** * Create a new RemoteCacheManager using the supplied URI. The RemoteCacheManager will be started * automatically * * @param uri the URI to use for this RemoteCacheManager * @since 11.0 */ public RemoteCacheManager(URI uri) { this(HotRodURI.create(uri)); } private RemoteCacheManager(HotRodURI uri) { this(uri.toConfigurationBuilder().build()); } /** * Create a new RemoteCacheManager using the supplied {@link Configuration}. The RemoteCacheManager will be started * automatically only if the start parameter is true * * @param configuration the configuration to use for this RemoteCacheManager * @param start whether or not to start the manager on return from the constructor. * @since 5.3 */ public RemoteCacheManager(Configuration configuration, boolean start) { this.configuration = configuration; this.counterManager = new RemoteCounterManager(); this.syncTransactionTable = new SyncModeTransactionTable(configuration.transactionTimeout()); this.xaTransactionTable = new XaModeTransactionTable(configuration.transactionTimeout()); registerMBean(); if (start) start(); } /** * @since 5.3 */ @Override public Configuration getConfiguration() { return configuration; } /** * <p>Similar to {@link RemoteCacheManager#RemoteCacheManager(Configuration, boolean)}, but it will try to lookup * the config properties in the classpath, in a file named <tt>hotrod-client.properties</tt>. If no properties can be * found in the classpath, defaults will be used, attempting to connect to <tt>127.0.0.1:11222</tt></p> * * <p>Refer to * {@link ConfigurationBuilder} for a detailed list of available properties.</p> * * @param start whether or not to start the RemoteCacheManager * @throws HotRodClientException if such a file cannot be found in the classpath */ public RemoteCacheManager(boolean start) { ConfigurationBuilder builder = new ConfigurationBuilder(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); builder.classLoader(cl); InputStream stream = FileLookupFactory.newInstance().lookupFile(HOTROD_CLIENT_PROPERTIES, cl); if (stream == null) { HOTROD.couldNotFindPropertiesFile(HOTROD_CLIENT_PROPERTIES); } else { try { builder.withProperties(loadFromStream(stream)); } finally { Util.close(stream); } } this.configuration = builder.build(); this.counterManager = new RemoteCounterManager(); this.syncTransactionTable = new SyncModeTransactionTable(configuration.transactionTimeout()); this.xaTransactionTable = new XaModeTransactionTable(configuration.transactionTimeout()); registerMBean(); if (start) actualStart(); } /** * Same as {@link #RemoteCacheManager(boolean)} and it also starts the cache. */ public RemoteCacheManager() { this(true); } private void registerMBean() { StatisticsConfiguration configuration = this.configuration.statistics(); if (configuration.jmxEnabled()) { try { MBeanServer mbeanServer = configuration.mbeanServerLookup().getMBeanServer(); mbeanObjectName = new ObjectName(String.format("%s:type=HotRodClient,name=%s", configuration.jmxDomain(), configuration.jmxName())); mbeanServer.registerMBean(this, mbeanObjectName); } catch (Exception e) { throw HOTROD.jmxRegistrationFailure(e); } } } private void unregisterMBean() { if (mbeanObjectName != null) { try { MBeanServer mBeanServer = configuration.statistics().mbeanServerLookup().getMBeanServer(); if (mBeanServer.isRegistered(mbeanObjectName)) { mBeanServer.unregisterMBean(mbeanObjectName); } else { HOTROD.debugf("MBean not registered: %s", mbeanObjectName); } } catch (Exception e) { throw HOTROD.jmxUnregistrationFailure(e); } } } /** * Retrieves a named cache from the remote server if the cache has been defined, otherwise if the cache name is * undefined, it will return null. * * @param cacheName name of cache to retrieve * @return a cache instance identified by cacheName or null if the cache name has not been defined */ @Override public <K, V> RemoteCache<K, V> getCache(String cacheName) { return getCache(cacheName, configuration.forceReturnValues(), null, null); } @Override public Set<String> getCacheNames() { OperationsFactory operationsFactory = new OperationsFactory(channelFactory, listenerNotifier, configuration); String names = await(operationsFactory.newAdminOperation("@@cache@names", Collections.emptyMap()).execute()); Set<String> cacheNames = new HashSet<>(); // Simple pattern that matches the result which is represented as a JSON string array, e.g. ["cache1","cache2"] Pattern pattern = Pattern.compile(JSON_STRING_ARRAY_ELEMENT_REGEX); Matcher matcher = pattern.matcher(names); while (matcher.find()) { cacheNames.add(matcher.group(1)); } return cacheNames; } /** * Retrieves the default cache from the remote server. * * @return a remote cache instance that can be used to send requests to the default cache in the server */ @Override public <K, V> RemoteCache<K, V> getCache() { return getCache(configuration.forceReturnValues()); } @Override public <K, V> RemoteCache<K, V> getCache(String cacheName, TransactionMode transactionMode, TransactionManager transactionManager) { return createRemoteCache(cacheName, configuration.forceReturnValues(), transactionMode, transactionManager); } @Override public <K, V> RemoteCache<K, V> getCache(String cacheName, boolean forceReturnValue, TransactionMode transactionMode, TransactionManager transactionManager) { return createRemoteCache(cacheName, forceReturnValue, transactionMode, transactionManager); } public CompletableFuture<Void> startAsync() { // The default async executor service is dedicated for Netty, therefore here we'll use common FJP. // TODO: This needs to be fixed at some point to not use an additional thread return CompletableFuture.runAsync(start, ForkJoinPool.commonPool()); } public CompletableFuture<Void> stopAsync() { // The default async executor service is dedicated for Netty, therefore here we'll use common FJP. // TODO: This needs to be fixed at some point to not use an additional thread return CompletableFuture.runAsync(stop, ForkJoinPool.commonPool()); } @Override public void start() { if (!started) { actualStart(); } } private void actualStart() { log.debugf("Starting remote cache manager %x", System.identityHashCode(this)); channelFactory = createChannelFactory(); marshallerRegistry.registerMarshaller(BytesOnlyMarshaller.INSTANCE); marshallerRegistry.registerMarshaller(new UTF8StringMarshaller()); marshallerRegistry.registerMarshaller(new JavaSerializationMarshaller(configuration.getClassAllowList())); registerProtoStreamMarshaller(); boolean customMarshallerInstance = true; marshaller = configuration.marshaller(); if (marshaller == null) { Class<? extends Marshaller> clazz = configuration.marshallerClass(); marshaller = marshallerRegistry.getMarshaller(clazz); if (marshaller == null) { marshaller = Util.getInstance(clazz); } else { customMarshallerInstance = false; } } if (customMarshallerInstance) { if (!configuration.serialAllowList().isEmpty()) { marshaller.initialize(configuration.getClassAllowList()); } if (marshaller instanceof ProtoStreamMarshaller) { initializeProtoStreamMarshaller((ProtoStreamMarshaller) marshaller); } // Replace any default marshaller with the same media type marshallerRegistry.registerMarshaller(marshaller); } listenerNotifier = new ClientListenerNotifier(marshaller, channelFactory, configuration); ExecutorFactory executorFactory = configuration.asyncExecutorFactory().factory(); if (executorFactory == null) { executorFactory = Util.getInstance(configuration.asyncExecutorFactory().factoryClass()); } asyncExecutorService = executorFactory.getExecutor(configuration.asyncExecutorFactory().properties()); channelFactory.start(configuration, marshaller, asyncExecutorService, listenerNotifier, marshallerRegistry); counterManager.start(channelFactory, configuration, listenerNotifier); TransactionOperationFactory txOperationFactory = new TransactionOperationFactory(configuration, channelFactory); syncTransactionTable.start(txOperationFactory); xaTransactionTable.start(txOperationFactory); // Print version to help figure client version run HOTROD.version(Version.printVersion()); started = true; } private void registerProtoStreamMarshaller() { try { ProtoStreamMarshaller protoMarshaller = new ProtoStreamMarshaller(); marshallerRegistry.registerMarshaller(protoMarshaller); initializeProtoStreamMarshaller(protoMarshaller); } catch (NoClassDefFoundError e) { // Ignore the error, it the protostream dependency is missing } } private void initializeProtoStreamMarshaller(ProtoStreamMarshaller protoMarshaller) { SerializationContext ctx = protoMarshaller.getSerializationContext(); // Register some useful builtin schemas, which the user can override later. registerDefaultSchemas(ctx, "org.infinispan.protostream.types.java.CommonContainerTypesSchema", "org.infinispan.protostream.types.java.CommonTypesSchema"); registerSerializationContextInitializer(ctx, new UserContextInitializerImpl()); // Register the configured schemas. for (SerializationContextInitializer sci : configuration.getContextInitializers()) { registerSerializationContextInitializer(ctx, sci); } } private static void registerSerializationContextInitializer(SerializationContext ctx, SerializationContextInitializer sci) { sci.registerSchema(ctx); sci.registerMarshallers(ctx); } private static void registerDefaultSchemas(SerializationContext ctx, String... classNames) { for (String className : classNames) { SerializationContextInitializer sci; try { Class<?> clazz = Class.forName(className); Object instance = clazz.getDeclaredConstructor().newInstance(); sci = (SerializationContextInitializer) instance; } catch (Exception e) { log.failedToCreatePredefinedSerializationContextInitializer(className, e); continue; } registerSerializationContextInitializer(ctx, sci); } } public ChannelFactory createChannelFactory() { return new ChannelFactory(new CodecHolder(configuration.version().getCodec())); } @Override public boolean isTransactional(String cacheName) { ClientStatistics stats = ClientStatistics.dummyClientStatistics(timeService); OperationsFactory factory = createOperationFactory(cacheName, false, stats); return checkTransactionSupport(cacheName, factory, log); } public MarshallerRegistry getMarshallerRegistry() { return marshallerRegistry; } /** * Stop the remote cache manager, disconnecting all existing connections. As part of the disconnection, all * registered client cache listeners will be removed since client no longer can receive callbacks. */ @Override public void stop() { if (isStarted()) { log.debugf("Stopping remote cache manager %x", System.identityHashCode(this)); synchronized (cacheName2RemoteCache) { for (Map.Entry<RemoteCacheKey, RemoteCacheHolder> cache : cacheName2RemoteCache.entrySet()) { cache.getValue().remoteCache().stop(); } cacheName2RemoteCache.clear(); } listenerNotifier.stop(); counterManager.stop(); channelFactory.destroy(); } unregisterMBean(); started = false; } @Override public boolean isStarted() { return started; } @Override public boolean switchToCluster(String clusterName) { return channelFactory.manualSwitchToCluster(clusterName); } @Override public boolean switchToDefaultCluster() { return channelFactory.manualSwitchToCluster(ChannelFactory.DEFAULT_CLUSTER_NAME); } private Properties loadFromStream(InputStream stream) { Properties properties = new Properties(); try { properties.load(stream); } catch (IOException e) { throw new HotRodClientException("Issues configuring from client hotrod-client.properties", e); } return properties; } private RemoteCacheConfiguration findConfiguration(String cacheName) { if (configuration.remoteCaches().containsKey(cacheName)) { return configuration.remoteCaches().get(cacheName); } // Search for wildcard configurations for (Map.Entry<String, RemoteCacheConfiguration> c : configuration.remoteCaches().entrySet()) { String key = c.getKey(); if (GlobUtils.isGlob(key) && cacheName.matches(GlobUtils.globToRegex(key))) { return c.getValue(); } } return null; } private <K, V> RemoteCache<K, V> createRemoteCache(String cacheName, boolean forceReturnValueOverride, TransactionMode transactionModeOverride, TransactionManager transactionManagerOverride) { RemoteCacheConfiguration cacheConfiguration = findConfiguration(cacheName); boolean forceReturnValue = forceReturnValueOverride || (cacheConfiguration != null ? cacheConfiguration.forceReturnValues() : configuration.forceReturnValues()); RemoteCacheKey key = new RemoteCacheKey(cacheName, forceReturnValue); if (cacheName2RemoteCache.containsKey(key)) { return cacheName2RemoteCache.get(key).remoteCache(); } OperationsFactory operationsFactory = createOperationFactory(cacheName, forceReturnValue, null); PingResponse pingResponse; if (started) { // Verify if the cache exists on the server first pingResponse = await(operationsFactory.newFaultTolerantPingOperation().execute()); // If ping not successful assume that the cache does not exist if (pingResponse.isCacheNotFound()) { // We may be able to create it. Don't use RemoteCacheAdmin for this, since it would end up calling this method again Map<String, byte[]> params = new HashMap<>(2); params.put(RemoteCacheManagerAdminImpl.CACHE_NAME, cacheName.getBytes(HotRodConstants.HOTROD_STRING_CHARSET)); if (cacheConfiguration != null && cacheConfiguration.templateName() != null) { params.put(RemoteCacheManagerAdminImpl.CACHE_TEMPLATE, cacheConfiguration.templateName().getBytes(HotRodConstants.HOTROD_STRING_CHARSET)); } else if (cacheConfiguration != null && cacheConfiguration.configuration() != null) { params.put(RemoteCacheManagerAdminImpl.CACHE_CONFIGURATION, new StringConfiguration(cacheConfiguration.configuration()).toStringConfiguration(cacheName).getBytes(HotRodConstants.HOTROD_STRING_CHARSET)); } else { // We cannot create the cache return null; } // Create and re-ping OperationsFactory adminOperationsFactory = new OperationsFactory(channelFactory, listenerNotifier, configuration); pingResponse = await(adminOperationsFactory.newAdminOperation("@@cache@getorcreate", params).execute().thenCompose(s -> operationsFactory.newFaultTolerantPingOperation().execute())); } } else { pingResponse = PingResponse.EMPTY; } TransactionMode transactionMode = getTransactionMode(transactionModeOverride, cacheConfiguration); InternalRemoteCache<K, V> remoteCache; if (transactionMode == TransactionMode.NONE) { remoteCache = createRemoteCache(cacheName); } else { if (!await(checkTransactionSupport(cacheName, operationsFactory).toCompletableFuture())) { throw HOTROD.cacheDoesNotSupportTransactions(cacheName); } else { TransactionManager transactionManager = getTransactionManager(transactionManagerOverride, cacheConfiguration); remoteCache = createRemoteTransactionalCache(cacheName, forceReturnValueOverride, transactionMode == TransactionMode.FULL_XA, transactionMode, transactionManager); } } synchronized (cacheName2RemoteCache) { startRemoteCache(remoteCache, forceReturnValue); RemoteCacheHolder holder = new RemoteCacheHolder(remoteCache, forceReturnValueOverride); remoteCache.resolveStorage(pingResponse.isObjectStorage()); cacheName2RemoteCache.putIfAbsent(key, holder); return remoteCache; } } private <K, V> InternalRemoteCache<K, V> createRemoteCache(String cacheName) { RemoteCacheConfiguration remoteCacheConfiguration = configuration.remoteCaches().get(cacheName); NearCacheConfiguration nearCache; if (remoteCacheConfiguration != null) { nearCache = new NearCacheConfiguration(remoteCacheConfiguration.nearCacheMode(), remoteCacheConfiguration.nearCacheMaxEntries(), remoteCacheConfiguration.nearCacheBloomFilter(), null, remoteCacheConfiguration.nearCacheFactory()); } else { Pattern pattern = configuration.nearCache().cacheNamePattern(); if (pattern == null || pattern.matcher(cacheName).matches()) { nearCache = configuration.nearCache(); } else { nearCache = new NearCacheConfiguration(NearCacheMode.DISABLED, -1, false); } } if (nearCache.mode() == NearCacheMode.INVALIDATED) { Pattern pattern = nearCache.cacheNamePattern(); if (pattern == null || pattern.matcher(cacheName).matches()) { if (log.isTraceEnabled()) { log.tracef("Enabling near-caching for cache '%s'", cacheName); } NearCacheService<K, V> nearCacheService = createNearCacheService(cacheName, nearCache); return InvalidatedNearRemoteCache.delegatingNearCache( new RemoteCacheImpl<>(this, cacheName, timeService, nearCacheService) , nearCacheService); } } return new RemoteCacheImpl<>(this, cacheName, timeService); } protected <K, V> NearCacheService<K, V> createNearCacheService(String cacheName, NearCacheConfiguration cfg) { return NearCacheService.create(cfg, listenerNotifier); } private void startRemoteCache(InternalRemoteCache<?, ?> remoteCache, boolean forceReturnValue) { OperationsFactory operationsFactory = createOperationFactory(remoteCache.getName(), forceReturnValue, remoteCache.clientStatistics()); initRemoteCache(remoteCache, operationsFactory); remoteCache.start(); } // Method that handles cache initialization - needed as a placeholder private void initRemoteCache(InternalRemoteCache<?, ?> remoteCache, OperationsFactory operationsFactory) { if (configuration.statistics().jmxEnabled()) { remoteCache.init(operationsFactory, configuration, mbeanObjectName); } else { remoteCache.init(operationsFactory, configuration); } } @Override public Marshaller getMarshaller() { return marshaller; } public static byte[] cacheNameBytes(String cacheName) { return cacheName.getBytes(HotRodConstants.HOTROD_STRING_CHARSET); } public static byte[] cacheNameBytes() { return HotRodConstants.DEFAULT_CACHE_NAME_BYTES; } /** * Access to administration operations (cache creation, removal, etc) * * @return an instance of {@link RemoteCacheManagerAdmin} which can perform administrative operations on the server. */ public RemoteCacheManagerAdmin administration() { OperationsFactory operationsFactory = new OperationsFactory(channelFactory, listenerNotifier, configuration); return new RemoteCacheManagerAdminImpl(this, operationsFactory, EnumSet.noneOf(CacheContainerAdmin.AdminFlag.class), name -> { synchronized (cacheName2RemoteCache) { // Remove any mappings cacheName2RemoteCache.remove(new RemoteCacheKey(name, true)); cacheName2RemoteCache.remove(new RemoteCacheKey(name, false)); } }); } /** * See {@link #stop()} */ @Override public void close() { stop(); } /** * Access to counter operations * * @return an instance of {@link CounterManager} which can perform counter operations on the server. */ CounterManager getCounterManager() { return counterManager; } /** * This method is not a part of the public API. It is exposed for internal purposes only. */ public ChannelFactory getChannelFactory() { return channelFactory; } /** * Returns the {@link XAResource} which can be used to do transactional recovery. * * @return An instance of {@link XAResource} */ public XAResource getXaResource() { return xaTransactionTable.getXaResource(); } private TransactionManager getTransactionManager(TransactionManager override, RemoteCacheConfiguration cacheConfiguration) { try { return override == null ? (cacheConfiguration == null ? GenericTransactionManagerLookup.getInstance().getTransactionManager() : cacheConfiguration.transactionManagerLookup().getTransactionManager()) : override; } catch (Exception e) { throw new HotRodClientException(e); } } private TransactionMode getTransactionMode(TransactionMode override, RemoteCacheConfiguration cacheConfiguration) { return override == null ? (cacheConfiguration == null ? TransactionMode.NONE : cacheConfiguration.transactionMode()) : override; } private TransactionTable getTransactionTable(TransactionMode transactionMode) { switch (transactionMode) { case NON_XA: return syncTransactionTable; case NON_DURABLE_XA: case FULL_XA: return xaTransactionTable; default: throw new IllegalStateException(); } } private <K, V> TransactionalRemoteCacheImpl<K, V> createRemoteTransactionalCache(String cacheName, boolean forceReturnValues, boolean recoveryEnabled, TransactionMode transactionMode, TransactionManager transactionManager) { return new TransactionalRemoteCacheImpl<>(this, cacheName, forceReturnValues, recoveryEnabled, transactionManager, getTransactionTable(transactionMode), timeService); } /* * The following methods are exposed through the MBean */ @Override public String[] getServers() { Collection<InetSocketAddress> addresses = channelFactory.getServers(); return addresses.stream().map(socketAddress -> socketAddress.getHostString() + ":" + socketAddress.getPort()).toArray(String[]::new); } @Override public int getActiveConnectionCount() { return channelFactory.getNumActive(); } @Override public int getConnectionCount() { return channelFactory.getNumActive() + channelFactory.getNumIdle(); } @Override public int getIdleConnectionCount() { return channelFactory.getNumIdle(); } @Override public long getRetries() { return channelFactory.getRetries(); } private OperationsFactory createOperationFactory(String cacheName, boolean forceReturnValue, ClientStatistics stats) { return new OperationsFactory(channelFactory, cacheName, forceReturnValue, listenerNotifier, configuration, stats); } public ExecutorService getAsyncExecutorService() { return asyncExecutorService; } private static class RemoteCacheKey { final String cacheName; final boolean forceReturnValue; RemoteCacheKey(String cacheName, boolean forceReturnValue) { this.cacheName = cacheName; this.forceReturnValue = forceReturnValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RemoteCacheKey)) return false; RemoteCacheKey that = (RemoteCacheKey) o; if (forceReturnValue != that.forceReturnValue) return false; return Objects.equals(cacheName, that.cacheName); } @Override public int hashCode() { int result = cacheName != null ? cacheName.hashCode() : 0; result = 31 * result + (forceReturnValue ? 1 : 0); return result; } } private static class RemoteCacheHolder { final InternalRemoteCache<?, ?> remoteCache; final boolean forceReturnValue; RemoteCacheHolder(InternalRemoteCache<?, ?> remoteCache, boolean forceReturnValue) { this.remoteCache = remoteCache; this.forceReturnValue = forceReturnValue; } <K, V> InternalRemoteCache<K, V> remoteCache() { return (InternalRemoteCache) remoteCache; } } }
33,230
41.278626
217
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/RemoteCacheContainer.java
package org.infinispan.client.hotrod; import jakarta.transaction.TransactionManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.TransactionMode; import org.infinispan.commons.api.BasicCacheContainer; import org.infinispan.commons.marshall.Marshaller; public interface RemoteCacheContainer extends BasicCacheContainer { /** * @see BasicCacheContainer#getCache() */ @Override <K, V> RemoteCache<K, V> getCache(); /** * @see BasicCacheContainer#getCache(String) */ @Override <K, V> RemoteCache<K, V> getCache(String cacheName); /** * Retrieves the configuration currently in use. The configuration object * is immutable. If you wish to change configuration, you should use the * following pattern: * * <pre><code> * ConfigurationBuilder builder = new ConfigurationBuilder(); * builder.read(remoteCacheManager.getConfiguration()); * // modify builder * remoteCacheManager.stop(); * remoteCacheManager = new RemoteCacheManager(builder.build()); * </code></pre> * * @return The configuration of this RemoteCacheManager */ Configuration getConfiguration(); /** * Same as {@code getCache(cacheName, forceReturnValue, null, null)} * * @see #getCache(String, boolean, TransactionMode, TransactionManager) * @deprecated since 11.0. Use {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#remoteCache(String)} to configure the cache and then {@link #getCache(String)} to obtain it. */ @Deprecated default <K, V> RemoteCache<K, V> getCache(String cacheName, boolean forceReturnValue) { return getCache(cacheName, forceReturnValue, null, null); } /** * Same as {@code getCache("", forceReturnValue, null, null)} * * @see #getCache(String, boolean, TransactionMode, TransactionManager) * @deprecated since 11.0. Use {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#remoteCache(String)} to configure the cache and then {@link #getCache(String)} to obtain it. */ @Deprecated default <K, V> RemoteCache<K, V> getCache(boolean forceReturnValue) { return getCache("", forceReturnValue, null, null); } /** * Same as {@code getCache(cacheName, transactionMode, null)} * * @see #getCache(String, TransactionMode, TransactionManager) * @deprecated since 11.0. Use {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#remoteCache(String)} to configure the cache and then {@link #getCache(String)} to obtain it. */ @Deprecated default <K, V> RemoteCache<K, V> getCache(String cacheName, TransactionMode transactionMode) { return getCache(cacheName, transactionMode, null); } /** * Same as {@code getCache(cacheName, forceReturnValue, transactionMode, null)} * * @see #getCache(String, boolean, TransactionMode, TransactionManager) * @deprecated since 11.0. Use {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#remoteCache(String)} to configure the cache and then {@link #getCache(String)} to obtain it. */ @Deprecated default <K, V> RemoteCache<K, V> getCache(String cacheName, boolean forceReturnValue, TransactionMode transactionMode) { return getCache(cacheName, forceReturnValue, transactionMode, null); } /** * Same as {@code getCache(cacheName, null, transactionManager)} * * @see #getCache(String, TransactionMode, TransactionManager) * @deprecated since 11.0. Use {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#remoteCache(String)} to configure the cache and then {@link #getCache(String)} to obtain it. */ @Deprecated default <K, V> RemoteCache<K, V> getCache(String cacheName, TransactionManager transactionManager) { return getCache(cacheName, null, transactionManager); } /** * Same as {@code getCache(cacheName, forceReturnValue, null, transactionManager)} * * @see #getCache(String, boolean, TransactionMode, TransactionManager) * @deprecated since 11.0. Use {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#remoteCache(String)} to configure the cache and then {@link #getCache(String)} to obtain it. */ @Deprecated default <K, V> RemoteCache<K, V> getCache(String cacheName, boolean forceReturnValue, TransactionManager transactionManager) { return getCache(cacheName, forceReturnValue, null, transactionManager); } /** * * @param cacheName The cache's name. * @param transactionMode The {@link TransactionMode} to override. If {@code null}, it uses the configured value. * @param transactionManager The {@link TransactionManager} to override. If {@code null}, it uses the configured value. * @return the {@link RemoteCache} implementation. * @deprecated since 11.0. Use {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#remoteCache(String)} to configure the cache and then {@link #getCache(String)} to obtain it. */ @Deprecated <K, V> RemoteCache<K, V> getCache(String cacheName, TransactionMode transactionMode, TransactionManager transactionManager); /** * @param cacheName The cache's name. * @param forceReturnValue {@code true} to force a return value when it is not needed. * @param transactionMode The {@link TransactionMode} to override. If {@code null}, it uses the configured value. * @param transactionManager The {@link TransactionManager} to override. If {@code null}, it uses the configured * value. * @return the {@link RemoteCache} implementation. * @deprecated since 11.0. Use {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#remoteCache(String)} to configure the cache and then {@link #getCache(String)} to obtain it. */ @Deprecated <K, V> RemoteCache<K, V> getCache(String cacheName, boolean forceReturnValue, TransactionMode transactionMode, TransactionManager transactionManager); boolean isStarted(); /** * Switch remote cache manager to a different cluster, previously * declared via configuration. If the switch was completed successfully, * this method returns {@code true}, otherwise it returns {@code false}. * * @param clusterName name of the cluster to which to switch to * @return {@code true} if the cluster was switched, {@code false} otherwise */ boolean switchToCluster(String clusterName); /** * Switch remote cache manager to a the default cluster, previously * declared via configuration. If the switch was completed successfully, * this method returns {@code true}, otherwise it returns {@code false}. * * @return {@code true} if the cluster was switched, {@code false} otherwise */ boolean switchToDefaultCluster(); Marshaller getMarshaller(); /** * @return {@code true} if the cache with name {@code cacheName} can participate in transactions. */ boolean isTransactional(String cacheName); }
7,145
43.111111
197
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/RemoteCounterManagerFactory.java
package org.infinispan.client.hotrod; import org.infinispan.counter.api.CounterManager; /** * A {@link CounterManager} factory for Hot Rod client. * * @author Pedro Ruivo * @since 9.2 */ public final class RemoteCounterManagerFactory { private RemoteCounterManagerFactory() { } public static CounterManager asCounterManager(RemoteCacheManager cacheManager) { return cacheManager.getCounterManager(); } }
432
19.619048
83
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/Metadata.java
package org.infinispan.client.hotrod; /** * Represents metadata about an entry, such as creation and access times and expiration information. Time values are server * time representations as returned by {@link org.infinispan.commons.time.TimeService#wallClockTime} * * @author Tristan Tarrant * @since 9.0 */ public interface Metadata { /** * * @return Time when entry was created. -1 for immortal entries. */ long getCreated(); /** * * @return Lifespan of the entry in seconds. Negative values are interpreted as unlimited * lifespan. */ int getLifespan(); /** * * @return Time when entry was last used. -1 for immortal entries. */ long getLastUsed(); /** * * @return The maximum amount of time (in seconds) this key is allowed to be idle for before it * is considered as expired. */ int getMaxIdle(); }
911
23.648649
123
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/ProtocolVersion.java
package org.infinispan.client.hotrod; import java.util.Locale; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.Codec20; import org.infinispan.client.hotrod.impl.protocol.Codec21; import org.infinispan.client.hotrod.impl.protocol.Codec22; import org.infinispan.client.hotrod.impl.protocol.Codec23; import org.infinispan.client.hotrod.impl.protocol.Codec24; import org.infinispan.client.hotrod.impl.protocol.Codec25; import org.infinispan.client.hotrod.impl.protocol.Codec26; import org.infinispan.client.hotrod.impl.protocol.Codec27; import org.infinispan.client.hotrod.impl.protocol.Codec28; import org.infinispan.client.hotrod.impl.protocol.Codec29; import org.infinispan.client.hotrod.impl.protocol.Codec30; import org.infinispan.client.hotrod.impl.protocol.Codec31; import org.infinispan.client.hotrod.impl.protocol.Codec40; /** * Enumeration of supported Hot Rod client protocol VERSIONS. * * @author Radoslav Husar * @since 9.0 */ public enum ProtocolVersion { // These need to go in order: lowest version is first - this way compareTo works for VERSIONS PROTOCOL_VERSION_20(2, 0, new Codec20()), PROTOCOL_VERSION_21(2, 1, new Codec21()), PROTOCOL_VERSION_22(2, 2, new Codec22()), PROTOCOL_VERSION_23(2, 3, new Codec23()), PROTOCOL_VERSION_24(2, 4, new Codec24()), PROTOCOL_VERSION_25(2, 5, new Codec25()), PROTOCOL_VERSION_26(2, 6, new Codec26()), PROTOCOL_VERSION_27(2, 7, new Codec27()), PROTOCOL_VERSION_28(2, 8, new Codec28()), PROTOCOL_VERSION_29(2, 9, new Codec29()), PROTOCOL_VERSION_30(3, 0, new Codec30()), PROTOCOL_VERSION_31(3, 1, new Codec31()), PROTOCOL_VERSION_40(4, 0, new Codec40()), // New VERSIONS go above this line to satisfy compareTo of enum working for VERSIONS // The version here doesn't matter as long as it is >= 3.0. It must be the LAST version PROTOCOL_VERSION_AUTO(4, 0, "AUTO", new Codec40()), ; private static final ProtocolVersion[] VERSIONS = values(); public static final ProtocolVersion DEFAULT_PROTOCOL_VERSION = PROTOCOL_VERSION_AUTO; public static final ProtocolVersion HIGHEST_PROTOCOL_VERSION = VERSIONS[VERSIONS.length - 2]; public static final ProtocolVersion SAFE_HANDSHAKE_PROTOCOL_VERSION = PROTOCOL_VERSION_31; private final String textVersion; private final int version; private final Codec codec; ProtocolVersion(int major, int minor, Codec codec) { this(major, minor, String.format(Locale.ROOT, "%d.%d", major, minor), codec); } ProtocolVersion(int major, int minor, String name, Codec codec) { assert minor < 10; this.textVersion = name; this.version = major * 10 + minor; this.codec = codec; } @Override public String toString() { return textVersion; } public int getVersion() { return version; } public Codec getCodec() { return codec; } public static ProtocolVersion parseVersion(String version) { if ("AUTO".equalsIgnoreCase(version)) { return PROTOCOL_VERSION_AUTO; } for (ProtocolVersion v : VERSIONS) { if (v.textVersion.equals(version)) return v; } throw new IllegalArgumentException("Illegal version " + version); } public static ProtocolVersion getBestVersion(int version) { // We skip the last version (auto) for (int i = VERSIONS.length - 2; i > 0; i--) { if (version >= VERSIONS[i].version) return VERSIONS[i]; } throw new IllegalArgumentException("Illegal version " + version); } public ProtocolVersion choose(ProtocolVersion serverVersion) { if (serverVersion == null) { return this; } return (serverVersion.compareTo(this) >= 0) ? this : serverVersion; } }
3,817
33.709091
96
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/Flag.java
package org.infinispan.client.hotrod; /** * Defines all the flags available in the Hot Rod client that can influence the behavior of operations. * <p /> * Available flags: * <ul> * <li>{@link #FORCE_RETURN_VALUE} - By default, previously existing values for {@link java.util.Map} operations are not * returned. E.g. {@link RemoteCache#put(Object, Object)} does <i>not</i> return * the previous value associated with the key. By applying this flag, this default * behavior is overridden for the scope of a single invocation, and the previous * existing value is returned.</li> * <li>{@link #DEFAULT_LIFESPAN} This flag can either be used as a request flag during a put operation to mean * that the default server lifespan should be applied or as a response flag meaning that * the return entry has a default lifespan value</li> * <li>{@link #DEFAULT_MAXIDLE} This flag can either be used as a request flag during a put operation to mean * that the default server maxIdle should be applied or as a response flag meaning that * the return entry has a default maxIdle value</li> * <li>{@link #SKIP_CACHE_LOAD} Skips loading an entry from any configured * {@link org.infinispan.persistence.spi.CacheLoader}s.</li> * <li>{@link #SKIP_INDEXING} Used by the Query module only, it will prevent the indexes to be updated as a result * of the current operations. * <li>{@link #SKIP_LISTENER_NOTIFICATION} Used when an operation wants to skip notifications to the registered listeners * </ul> * * @author Mircea.Markus@jboss.com * @since 4.1 */ public enum Flag { /** * By default, previously existing values for {@link java.util.Map} operations are not returned. E.g. {@link RemoteCache#put(Object, Object)} * does <i>not</i> return the previous value associated with the key. * <p /> * By applying this flag, this default behavior is overridden for the scope of a single invocation, and the previous * existing value is returned. */ FORCE_RETURN_VALUE(0x0001), /** * This flag can either be used as a request flag during a put operation to mean that the default * server lifespan should be applied or as a response flag meaning that the return entry has a * default lifespan value */ DEFAULT_LIFESPAN(0x0002), /** * This flag can either be used as a request flag during a put operation to mean that the default * server maxIdle should be applied or as a response flag meaning that the return entry has a * default maxIdle value */ DEFAULT_MAXIDLE(0x0004), /** * Skips loading an entry from any configured {@link org.infinispan.persistence.spi.CacheLoader}s. */ SKIP_CACHE_LOAD(0x0008), /** * Used by the Query module only, it will prevent the indexes to be updated as a result of the current operations. */ SKIP_INDEXING(0x0010), /** * It will skip client listeners to be notified. * @since 9.4.15 */ SKIP_LISTENER_NOTIFICATION(0x0020) ; private int flagInt; Flag(int flagInt) { this.flagInt = flagInt; } public int getFlagInt() { return flagInt; } }
3,533
45.5
144
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/VersionedMetadata.java
package org.infinispan.client.hotrod; /** * VersionedMetadata * @author Tristan Tarrant * @since 9.0 */ public interface VersionedMetadata extends Versioned, Metadata { }
176
16.7
64
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/NearCacheMode.java
package org.infinispan.client.hotrod.configuration; /** * Decides how client-side near caching should work. * * @since 7.1 */ public enum NearCacheMode { // TODO: Add SELECTIVE (or similar) when ISPN-5545 implemented /** * Near caching is disabled. */ DISABLED, /** * Near cache is invalidated, so when entries are updated or removed * server-side, invalidation messages will be sent to clients to remove * them from the near cache. */ INVALIDATED; public boolean enabled() { return this != DISABLED; } public boolean invalidated() { return this == INVALIDATED; } }
640
18.424242
74
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ClusterConfiguration.java
package org.infinispan.client.hotrod.configuration; import java.util.List; import org.infinispan.commons.util.Util; /** * @since 8.1 */ public class ClusterConfiguration { private final List<ServerConfiguration> serverCluster; private final String clusterName; private final ClientIntelligence intelligence; public ClusterConfiguration(List<ServerConfiguration> serverCluster, String clusterName, ClientIntelligence intelligence) { this.serverCluster = serverCluster; this.clusterName = clusterName; this.intelligence = intelligence; } public List<ServerConfiguration> getCluster() { return serverCluster; } public String getClusterName() { return clusterName; } public ClientIntelligence getClientIntelligence() { return intelligence; } @Override public String toString() { return "ClusterConfiguration{" + "serverCluster=" + Util.toStr(serverCluster) + ", clusterName='" + clusterName + '\'' + ", intelligence=" + intelligence + '}'; } }
1,082
24.785714
126
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/SaslStrength.java
package org.infinispan.client.hotrod.configuration; /** * SaslStrength. Possible values for the SASL strength property. * * @author Tristan Tarrant * @since 7.0 */ public enum SaslStrength { LOW("low"), MEDIUM("medium"), HIGH("high"); private String v; SaslStrength(String v) { this.v = v; } @Override public String toString() { return v; } }
385
15.782609
64
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/StatisticsConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.configuration.StatisticsConfiguration.ENABLED; import static org.infinispan.client.hotrod.configuration.StatisticsConfiguration.JMX_DOMAIN; import static org.infinispan.client.hotrod.configuration.StatisticsConfiguration.JMX_ENABLED; import static org.infinispan.client.hotrod.configuration.StatisticsConfiguration.JMX_NAME; import static org.infinispan.client.hotrod.configuration.StatisticsConfiguration.MBEAN_SERVER_LOOKUP; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.JMX; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.STATISTICS; import java.util.Properties; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.util.TypedProperties; /** * Configures client-side statistics * * @author Tristan Tarrant * @since 9.4 */ public class StatisticsConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<StatisticsConfiguration> { AttributeSet attributes = StatisticsConfiguration.attributeDefinitionSet(); StatisticsConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } /** * Enables or disables client-side statistics collection * * @param enabled whether to enable client-side statistics */ public StatisticsConfigurationBuilder enabled(boolean enabled) { attributes.attribute(ENABLED).set(enabled); return this; } /** * Enables client-side statistics collection */ public StatisticsConfigurationBuilder enable() { return enabled(true); } /** * Disables client-side statistics collection */ public StatisticsConfigurationBuilder disable() { return enabled(false); } /** * Enables or disables exposure of client-side statistics over JMX */ public StatisticsConfigurationBuilder jmxEnabled(boolean enabled) { attributes.attribute(JMX_ENABLED).set(enabled); return this; } /** * Enables exposure of client-side statistics over JMX */ public StatisticsConfigurationBuilder jmxEnable() { return jmxEnabled(true); } /** * Disables exposure of client-side statistics over JMX */ public StatisticsConfigurationBuilder jmxDisable() { return jmxEnabled(false); } /** * Sets the JMX domain name with which MBeans are exposed. Defaults to "org.infinispan" ({@link StatisticsConfiguration#JMX_DOMAIN}) * @param jmxDomain the JMX domain name */ public StatisticsConfigurationBuilder jmxDomain(String jmxDomain) { attributes.attribute(JMX_DOMAIN).set(jmxDomain); return this; } /** * Sets the name of the MBean. Defaults to "Default" ({@link StatisticsConfiguration#JMX_NAME}) * @param jmxName */ public StatisticsConfigurationBuilder jmxName(String jmxName) { attributes.attribute(JMX_NAME).set(jmxName); return this; } /** * Sets the instance of the {@link org.infinispan.commons.jmx.MBeanServerLookup} class to be used to bound JMX MBeans * to. * * @param mBeanServerLookupInstance An instance of {@link org.infinispan.commons.jmx.MBeanServerLookup} */ public StatisticsConfigurationBuilder mBeanServerLookup(MBeanServerLookup mBeanServerLookupInstance) { attributes.attribute(MBEAN_SERVER_LOOKUP).set(mBeanServerLookupInstance); return this; } @Override public StatisticsConfiguration create() { return new StatisticsConfiguration(attributes.protect()); } @Override public Builder<?> read(StatisticsConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public ConfigurationBuilder withProperties(Properties properties) { TypedProperties typed = TypedProperties.toTypedProperties(properties); enabled(typed.getBooleanProperty(STATISTICS, ENABLED.getDefaultValue())); jmxEnabled(typed.getBooleanProperty(JMX, JMX_ENABLED.getDefaultValue())); jmxDomain(typed.getProperty(ConfigurationProperties.JMX_DOMAIN, JMX_DOMAIN.getDefaultValue())); jmxName(typed.getProperty(ConfigurationProperties.JMX_NAME, JMX_NAME.getDefaultValue())); return builder; } }
4,646
33.169118
135
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ClientIntelligence.java
package org.infinispan.client.hotrod.configuration; /** * ClientIntelligence specifies the level of intelligence used by the client. * <ul> <li><b>BASIC</b> means that the * client doesn't handle server topology changes and therefore will only used the list of servers supplied at * configuration time</li> * <li><b>TOPOLOGY_AWARE</b> means that the client wants to receive topology updates from the * servers so that it can deal with added / removed servers dynamically. Requests will go to the servers using a * round-robin approach</li> * <li><b>HASH_DISTRIBUTION_AWARE</b> like <i>TOPOLOGY_AWARE</i> but with the additional * advantage that each request involving keys will be routed to the server who is the primary owner which improves * performance greatly. This is the default</li> * </ul> * * @author Tristan Tarrant * @since 9.0 */ public enum ClientIntelligence { BASIC(1), TOPOLOGY_AWARE(2), HASH_DISTRIBUTION_AWARE(3); final byte value; ClientIntelligence(int value) { this.value = (byte) value; } public byte getValue() { return value; } public static ClientIntelligence getDefault() { return HASH_DISTRIBUTION_AWARE; } }
1,204
30.710526
114
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/package-info.java
/** * Hot Rod client configuration API. * * <p>It is possible to configure the {@link org.infinispan.client.hotrod.RemoteCacheManager} either programmatically, * using a URI or by constructing a {@link org.infinispan.client.hotrod.configuration.Configuration} using a {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder} * or declaratively, by placing a properties file named <tt>hotrod-client.properties</tt> in the classpath.</p> * * <p>A Hot Rod URI follows the following format: * <code>hotrod[s]://[user[:password]@]host[:port][,host2[:port]][?property=value[&property2=value2]]</code> * </p> * <ul> * <li><b>hotrod</b> or <b>hotrods</b> specifies whether to use a plain connection or TLS/SSL encryption.</li> * <li><b>user</b> and <b>password</b> optionally specify authentication credentials.</li> * <li><b>host</b> and <b>port</b> comma-separated list of one or more servers.</li> * <li><b>property</b> and <b>value</b> one or more ampersand-separated (&amp;) property name/value pairs. The property name must omit the infinispan.client.hotrod prefix.</li> * </ul> * * <p>The following table describes the individual properties * and the related programmatic configuration API.</p> * * <table cellspacing="0" cellpadding="3" border="1"> * <thead> * <tr> * <th>Name</th> * <th>Type</th> * <th>Default</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <th colspan="4">Connection properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.uri</b></td> * <td>String</td> * <td>N/A</td> * <td>Configures the client via a URI</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.server_list</b></td> * <td>String</td> * <td>N/A</td> * <td>Adds a list of remote servers in the form: host1[:port][;host2[:port]]...</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.tcp_no_delay</b></td> * <td>Boolean</td> * <td>true</td> * <td>Enables/disables the {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#tcpNoDelay(boolean) TCP_NO_DELAY} flag</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.tcp_keep_alive</b></td> * <td>Boolean</td> * <td>false</td> * <td>Enables/disables the {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#tcpKeepAlive(boolean) TCP_KEEPALIVE} flag</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.client_intelligence</b></td> * <td>String</td> * <td>{@link org.infinispan.client.hotrod.configuration.ClientIntelligence#HASH_DISTRIBUTION_AWARE HASH_DISTRIBUTION_AWARE}</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#clientIntelligence(ClientIntelligence) ClientIntelligence}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.request_balancing_strategy</b></td> * <td>String (class name)</td> * <td>{@link org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy RoundRobinBalancingStrategy}</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#balancingStrategy(String) FailoverRequestBalancingStrategy}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.socket_timeout</b></td> * <td>Integer</td> * <td>2000</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#socketTimeout(int) timeout} for socket read/writes</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.connect_timeout</b></td> * <td>Integer</td> * <td>2000</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#connectionTimeout(int) timeout} for connections</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.max_retries</b></td> * <td>Integer</td> * <td>2</td> * <td>The maximum number of operation {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#maxRetries(int) retries}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.batch_size</b></td> * <td>Integer</td> * <td>10000</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#batchSize(int) size} of a batches when iterating</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.protocol_version</b></td> * <td>String</td> * <td>Latest version supported by the client in use</td> * <td>The Hot Rod {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#version(org.infinispan.client.hotrod.ProtocolVersion) version}.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.dns_resolver_min_ttl</b></td> * <td>Integer</td> * <td>0</td> * <td>The minimum TTL of the cached DNS resource records (in seconds). If the TTL of the DNS resource record returned by the DNS server is less than the minimum TTL, the resolver will ignore the TTL from the DNS server and use the minimum TTL instead. The defaults respect the DNS server TTL.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.dns_resolver_max_ttl</b></td> * <td>Integer</td> * <td>Integer.MAX_VALUE</td> * <td>The maximum TTL of the cached DNS resource records (in seconds). If the TTL of the DNS resource record returned by the DNS server is greater than the maximum TTL, the resolver will ignore the TTL from the DNS server and use the maximum TTL instead. The defaults respect the DNS server TTL.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.dns_resolver_negative_ttl</b></td> * <td>Integer</td> * <td>0</td> * <td>Sets the TTL of the cache for the failed DNS queries (in seconds).</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.transport_factory</b></td> * <td>String</td> * <td>{@link org.infinispan.client.hotrod.impl.transport.netty.DefaultTransportFactory}</td> * <td>Specifies the transport factory to use.</td> * </tr> * <tr> * <th colspan="4">Connection pool properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.connection_pool.max_active</b></td> * <td>Integer</td> * <td>-1 (no limit)</td> * <td>Maximum number of {@link org.infinispan.client.hotrod.configuration.ConnectionPoolConfigurationBuilder#maxActive(int) connections} per server</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.connection_pool.exhausted_action</b></td> * <td>String</td> * <td>{@link org.infinispan.client.hotrod.configuration.ExhaustedAction#WAIT WAIT}</td> * <td>Specifies what happens when asking for a connection from a server's pool, and that pool is {@link org.infinispan.client.hotrod.configuration.ConnectionPoolConfigurationBuilder#exhaustedAction(org.infinispan.client.hotrod.configuration.ExhaustedAction) exhausted}.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.connection_pool.max_wait</b></td> * <td>Long</td> * <td>-1 (no limit)</td> * <td>{@link org.infinispan.client.hotrod.configuration.ConnectionPoolConfigurationBuilder#maxWait(long) Time} to wait in milliseconds for a connection to become available when exhausted_action is WAIT</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.connection_pool.min_idle</b></td> * <td>Integer</td> * <td>1</td> * <td>Minimum number of idle {@link org.infinispan.client.hotrod.configuration.ConnectionPoolConfigurationBuilder#minIdle(int) connections} that each server should have available.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.connection_pool.min_evictable_idle_time</b></td> * <td>Integer</td> * <td>180000</td> * <td>Minimum amount of {@link org.infinispan.client.hotrod.configuration.ConnectionPoolConfigurationBuilder#minEvictableIdleTime(long) time} in milliseconds that an connection may sit idle in the pool</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.connection_pool.max_pending_requests</b></td> * <td>Integer</td> * <td>5</td> * <td>Specifies maximum number of {@link org.infinispan.client.hotrod.configuration.ConnectionPoolConfigurationBuilder#maxPendingRequests(int) requests} sent over single connection at one instant.</td> * </tr> * <tr> * <th colspan="4">Thread pool properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.async_executor_factory</b></td> * <td>String (class name)</td> * <td>{@link org.infinispan.client.hotrod.impl.async.DefaultAsyncExecutorFactory DefaultAsyncExecutorFactory}</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ExecutorFactoryConfigurationBuilder#factoryClass(String) factory} for creating threads</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.default_executor_factory.pool_size</b></td> * <td>Integer</td> * <td>99</td> * <td>Size of the thread pool</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.default_executor_factory.threadname_prefix</b></td> * <td>String</td> * <td>HotRod-client-async-pool</td> * <td>Prefix for the default executor thread names</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.default_executor_factory.threadname_suffix</b></td> * <td>String</td> * <td>"" (empty value)</td> * <td>Suffix for the default executor thread names</td> * </tr> * <tr> * <th colspan="4">Marshalling properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.marshaller</b></td> * <td>String (class name)</td> * <td>{@link org.infinispan.jboss.marshalling.commons.GenericJBossMarshaller} if the infinispan-jboss-marshalling module is present on the classpath, otherwise {@link org.infinispan.commons.marshall.ProtoStreamMarshaller} is used</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#marshaller(String) marshaller} that serializes keys and values</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.key_size_estimate</b></td> * <td>Integer</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#keySizeEstimate(int) estimated&nbsp;size} of keys in bytes when marshalled. This configuration property is deprecated and does not take effect.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.value_size_estimate</b></td> * <td>Integer</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#valueSizeEstimate(int) estimated&nbsp;size} of values in bytes when marshalled. This configuration property is deprecated and does not take effect.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.force_return_values</b></td> * <td>Boolean</td> * <td>false</td> * <td>Whether to {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#forceReturnValues(boolean) return&nbsp;values} for puts/removes</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.java_serial_allowlist</b></td> * <td>String</td> * <td>N/A</td> * <td>A {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#addJavaSerialAllowList(String...) class&nbsp;allowList} which are trusted for unmarshalling.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.hash_function_impl.2</b></td> * <td>String</td> * <td>{@link org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashV2 ConsistentHashV2}</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#consistentHashImpl(int, String) hash&nbsp;function} to use.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.context-initializers</b></td> * <td>String (class names)</td> * <td>"" (empty value)</td> * <td>A list of {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#addContextInitializers(org.infinispan.protostream.SerializationContextInitializer... contextInitializers) SerializationContextInitializer implementation}</td> * </tr> * <tr> * <th colspan="4">Encryption (TLS/SSL) properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.use_ssl</b></td> * <td>Boolean</td> * <td>false</td> * <td>{@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#enable() Enable&nbsp;TLS} (implicitly enabled if a trust store is set)</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.key_store_file_name</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#keyStoreFileName(String) filename} of a keystore to use when using client certificate authentication.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.key_store_type</b></td> * <td>String</td> * <td>JKS</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#keyStoreType(String) keystore&nbsp;type}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.key_store_password</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#keyStorePassword(char[]) keystore&nbsp;password}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.key_alias</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#keyAlias(String) alias} of the </td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.key_store_certificate_password</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#keyStoreCertificatePassword(char[]) certificate&nbsp;password} in the keystore.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.trust_store_file_name</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#trustStoreFileName(String) path} of the trust store.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.trust_store_type</b></td> * <td>String</td> * <td>JKS</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#trustStoreType(String) type} of the trust store. Valid values are <tt>JKS</tt>, <tt>JCEKS</tt>, <tt>PCKS12</tt> and <tt>PEM</tt></td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.trust_store_password</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#trustStorePassword(char[]) password} of the trust store.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.sni_host_name</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#sniHostName(String) SNI&nbsp;hostname} to connect to.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.ssl_ciphers</b></td> * <td>String</td> * <td>N/A</td> * <td>A list of ciphers, separated with spaces and in order of preference, that are used during the SSL handshake to negotiate * a cryptographic algorithm for key encrytion. By default, the SSL protocol (e.g. TLSv1.2) determines which ciphers to use. * You should customize the cipher list with caution to avoid vulnerabilities from weak algorithms. * For details about cipher lists and possible values, refer to OpenSSL documentation at <a href="https://www.openssl.org/docs/man1.1.1/man1/ciphers">https://www.openssl.org/docs/man1.1.1/man1/ciphers</a></td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.ssl_protocol</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.SslConfigurationBuilder#protocol(String) SSL&nbsp;protocol} to use (e.g. TLSv1.2).</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.ssl_provider</b></td> * <td>String</td> * <td>N/A</td> * <td>The security provider to use when creating the SSL engine. If left unspecified, it will attempt to use the <tt>openssl</tt> for the high-performance native implementation, otherwise the internal JDK will be used.</td> * </tr> * <tr> * <th colspan="4">Authentication properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.use_auth</b></td> * <td>Boolean</td> * <td>Enabled implicitly with other authentication properties.</td> * <td>{@link org.infinispan.client.hotrod.configuration.AuthenticationConfigurationBuilder#enabled(boolean) Enable} authentication.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.sasl_mechanism</b></td> * <td>String</td> * <td><pre>SCRAM-SHA-512</pre> if username and password are set<br>EXTERNAL if a trust store is set.</td> * <td>The {@link org.infinispan.client.hotrod.configuration.AuthenticationConfigurationBuilder#saslMechanism(String) SASL&nbsp;mechanism} to use for authentication.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.auth_callback_handler</b></td> * <td>String</td> * <td>Automatically selected based on the configured SASL mechanism.</td> * <td>The {@link org.infinispan.client.hotrod.configuration.AuthenticationConfigurationBuilder#callbackHandler(javax.security.auth.callback.CallbackHandler) CallbackHandler} to use for providing credentials for authentication.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.auth_server_name</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.AuthenticationConfigurationBuilder#serverName(String) server&nbsp;name} to use (for Kerberos).</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.auth_username</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.AuthenticationConfigurationBuilder#username(String) username}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.auth_password</b></td> * <td>String</td> * <td>N/A</td> * <td>The {@link org.infinispan.client.hotrod.configuration.AuthenticationConfigurationBuilder#password(char[]) password}</td> * </tr> * <tr> * * <td><b>infinispan.client.hotrod.auth_token</b></td> * * <td>String</td> * * <td>N/A</td> * * <td>The {@link org.infinispan.client.hotrod.configuration.AuthenticationConfigurationBuilder#token(String) OAuth token}</td> * * </tr> * <tr> * <td><b>infinispan.client.hotrod.auth_realm</b></td> * <td>String</td> * <td>default</td> * <td>The {@link org.infinispan.client.hotrod.configuration.AuthenticationConfigurationBuilder#realm(String) realm} (for DIGEST-MD5 authentication).</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.sasl_properties.*</b></td> * <td>String</td> * <td>N/A</td> * <td>A {@link org.infinispan.client.hotrod.configuration.AuthenticationConfigurationBuilder#saslProperties(java.util.Map) SASL&nbsp;property} (mech-specific)</td> * </tr> * <tr> * <th colspan="4">Transaction properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.transaction.transaction_manager_lookup</b></td> * <td>String (class name)</td> * <td>{@link org.infinispan.client.hotrod.configuration.TransactionConfigurationBuilder#defaultTransactionManagerLookup() GenericTransactionManagerLookup}</td> * <td>[Deprecated] A class to {@link org.infinispan.client.hotrod.configuration.TransactionConfigurationBuilder#transactionManagerLookup(org.infinispan.commons.tx.lookup.TransactionManagerLookup) lookup} available transaction managers.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.transaction.transaction_mode</b></td> * <td>String ({@link org.infinispan.client.hotrod.configuration.TransactionMode} enum name)</td> * <td>{@link org.infinispan.client.hotrod.configuration.TransactionMode#NONE NONE}</td> * <td>[Deprecated] The default {@link org.infinispan.client.hotrod.configuration.TransactionConfigurationBuilder#transactionMode(TransactionMode) transaction&nbsp;mode}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.transaction.timeout</b></td> * <td>long</td> * <td>60000L</td> * <td>The {@link org.infinispan.client.hotrod.configuration.TransactionConfigurationBuilder#timeout(long, java.util.concurrent.TimeUnit)} timeout.</td> * </tr> * <tr> * <th colspan="4">Near cache properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.near_cache.mode</b></td> * <td>String ({@link org.infinispan.client.hotrod.configuration.NearCacheMode} enum name)</td> * <td>{@link org.infinispan.client.hotrod.configuration.NearCacheMode#DISABLED DISABLED}</td> * <td>The default near-cache {@link org.infinispan.client.hotrod.configuration.NearCacheConfigurationBuilder#mode(NearCacheMode) mode}. It is preferable to use the per-cache configuration.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.near_cache.max_entries</b></td> * <td>Integer</td> * <td>-1 (no limit)</td> * <td>The {@link org.infinispan.client.hotrod.configuration.NearCacheConfigurationBuilder#maxEntries(int) maximum} number of entries to keep in the local cache. It is preferable to use the per-cache configuration.</td> * </tr> * <tr> * <td><b><s>infinispan.client.hotrod.near_cache.name_pattern</s></b></td> * <td>String (regex pattern, see {@link java.util.regex.Pattern})</td> * <td>null (matches all cache names)</td> * <td>A {@link org.infinispan.client.hotrod.configuration.NearCacheConfigurationBuilder#cacheNamePattern(String) regex} which matches caches for which near-caching should be enabled. This property is deprecated and it is preferable to use the per-cache configuration.</td> * </tr> * <tr> * <th colspan="4">Cross-site replication properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cluster.SITE</b></td> * <td>String HOST and int PORT configuration</td> * <td>Example for siteA and siteB:<br/> * infinispan.client.hotrod.cluster.siteA=hostA1:11222; hostA2:11223`<br/> * infinispan.client.hotrod.cluster.siteB=hostB1:11222; hostB2:11223` * </td> * <td>Relates to {@link org.infinispan.client.hotrod.configuration.ClusterConfigurationBuilder#addCluster(java.lang.String)} and * {@link org.infinispan.client.hotrod.configuration.ClusterConfigurationBuilder#addClusterNode(java.lang.String, int)}</td> * </tr> * <tr> * <th colspan="4">Statistics properties</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.statistics</b></td> * <td>Boolean</td> * <td>Default value {@link org.infinispan.client.hotrod.configuration.StatisticsConfiguration#ENABLED}</td> * <td>Relates to {@link org.infinispan.client.hotrod.configuration.StatisticsConfigurationBuilder#enabled(boolean)}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.jmx</b></td> * <td>Boolean</td> * <td>Default value {@link org.infinispan.client.hotrod.configuration.StatisticsConfiguration#JMX_ENABLED}</td> * <td>Relates to {@link org.infinispan.client.hotrod.configuration.StatisticsConfigurationBuilder#jmxEnabled(boolean)}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.jmx_name</b></td> * <td>String</td> * <td>Default value {@link org.infinispan.client.hotrod.configuration.StatisticsConfiguration#JMX_NAME}</td> * <td>Relates to {@link org.infinispan.client.hotrod.configuration.StatisticsConfigurationBuilder#jmxName(java.lang.String)}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.jmx_domain</b></td> * <td>String</td> * <td>Default value {@link org.infinispan.client.hotrod.configuration.StatisticsConfiguration#JMX_DOMAIN}</td> * <td>Relates to {@link org.infinispan.client.hotrod.configuration.StatisticsConfigurationBuilder#jmxDomain(java.lang.String)}</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.tracing.propagation_enabled</b></td> * <td>Boolean</td> * <td>Enabled implicitly by the presence of the OpenTelemetry API cn the client classpath.</td> * <td>Relates to {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#disableTracingPropagation()}} ()}</td> * </tr> * <tr> * <th colspan="4">Per-cache properties</th> * </tr> * <tr> * <th colspan="4">In per-cache configuration properties, you can use wildcards with <i>cachename</i>, for example: <code>cache-*</code>.</th> * </tr> * <tr> * <th colspan="4">If cache names include the <code>'.'</code> character you must enclose the cache name in square brackets, for example: <code>[example.MyConfig]</code>.</th> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cache.<i>cachename</i>.configuration</b></td> * <td>XML</td> * <td>N/A</td> * <td>Provides a cache configuration, in XML format, to use when clients request caches that do not exist.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cache.<i>cachename</i>.configuration_uri</b></td> * <td>XML</td> * <td>N/A</td> * <td>Provides a URI to a cache configuration, in XML format, to use when clients request caches that do not exist.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cache.<i>cachename</i>.template_name</b></td> * <td>String</td> * <td>N/A</td> * <td>Names a cache template to use when clients request caches that do not exist. The cache template must be available on the server.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cache.<i>cachename</i>.near_cache.mode</b></td> * <td>String ({@link org.infinispan.client.hotrod.configuration.NearCacheMode} enum name)</td> * <td>{@link org.infinispan.client.hotrod.configuration.NearCacheMode#DISABLED DISABLED}</td> * <td>The near-cache {@link org.infinispan.client.hotrod.configuration.RemoteCacheConfigurationBuilder#nearCacheMode(org.infinispan.client.hotrod.configuration.NearCacheMode)} (NearCacheMode) mode} for this cache</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cache.<i>cachename</i>.near_cache.max_entries</b></td> * <td>Integer</td> * <td>-1 (no limit)</td> * <td>The {@link org.infinispan.client.hotrod.configuration.RemoteCacheConfigurationBuilder#nearCacheMaxEntries(int) maximum} number of entries to keep locally for the specified cache.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cache.<i>cachename</i>.force_return_values</b></td> * <td>Boolean</td> * <td>false</td> * <td>Whether to {@link org.infinispan.client.hotrod.configuration.RemoteCacheConfigurationBuilder#forceReturnValues(boolean) return&nbsp;values} for puts/removes for the specified cache.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cache.<i>cachename</i>.transaction.transaction_mode</b></td> * <td>String ({@link org.infinispan.client.hotrod.configuration.TransactionMode} enum name)</td> * <td>{@link org.infinispan.client.hotrod.configuration.TransactionMode#NONE NONE}</td> * <td>The default {@link org.infinispan.client.hotrod.configuration.RemoteCacheConfigurationBuilder#transactionMode(TransactionMode) transaction&nbsp;mode} for the specified cache.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cache.<i>cachename</i>.transaction.transaction_manager_lookup</b></td> * <td>String (class name)</td> * <td>{@link org.infinispan.client.hotrod.transaction.lookup.GenericTransactionManagerLookup GenericTransactionManagerLookup}</td> * <td>The {@link org.infinispan.commons.tx.lookup.TransactionManagerLookup} for the specified cache.</td> * </tr> * <tr> * <td><b>infinispan.client.hotrod.cache.<i>cachename</i>.marshaller</b></td> * <td>String (class name)</td> * <td>{@link org.infinispan.commons.marshall.ProtoStreamMarshaller} unless another marshaller is used.</td> * <td>The {@link org.infinispan.client.hotrod.configuration.ConfigurationBuilder#marshaller(String) marshaller} that serializes keys and values for the specified cache.</td> * </tr> * </tbody> * </table> * * @api.public */ package org.infinispan.client.hotrod.configuration;
31,080
57.313321
310
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/SecurityConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * SecurityConfigurationBuilder. * * @author Tristan Tarrant * @since 7.0 */ public class SecurityConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<SecurityConfiguration> { private final AuthenticationConfigurationBuilder authentication = new AuthenticationConfigurationBuilder(this); private final SslConfigurationBuilder ssl = new SslConfigurationBuilder(this); SecurityConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } public AuthenticationConfigurationBuilder authentication() { return authentication; } public SslConfigurationBuilder ssl() { return ssl; } @Override public SecurityConfiguration create() { return new SecurityConfiguration(authentication.create(), ssl.create()); } @Override public Builder<?> read(SecurityConfiguration template, Combine combine) { authentication.read(template.authentication(), combine); ssl.read(template.ssl(), combine); return this; } @Override public void validate() { authentication.validate(); ssl.validate(); } ConfigurationBuilder getBuilder() { return super.builder; } }
1,531
24.966102
114
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/SslConfiguration.java
package org.infinispan.client.hotrod.configuration; import java.util.Collection; import javax.net.ssl.SSLContext; /** * SslConfiguration. * * @author Tristan Tarrant * @since 5.3 */ public class SslConfiguration { private final boolean enabled; private final String keyStoreFileName; private final String keyStoreType; private final char[] keyStorePassword; private final char[] keyStoreCertificatePassword; private final String keyAlias; private final SSLContext sslContext; private final String trustStoreFileName; private final String trustStorePath; private final String trustStoreType; private final char[] trustStorePassword; private final String sniHostName; private final String protocol; private final Collection<String> ciphers; private final String provider; SslConfiguration(boolean enabled, String keyStoreFileName, String keyStoreType, char[] keyStorePassword, char[] keyStoreCertificatePassword, String keyAlias, SSLContext sslContext, String trustStoreFileName, String trustStorePath, String trustStoreType, char[] trustStorePassword, String sniHostName, String provider, String protocol, Collection<String> ciphers) { this.enabled = enabled; this.keyStoreFileName = keyStoreFileName; this.keyStoreType = keyStoreType; this.keyStorePassword = keyStorePassword; this.keyStoreCertificatePassword = keyStoreCertificatePassword; this.keyAlias = keyAlias; this.sslContext = sslContext; this.trustStoreFileName = trustStoreFileName; this.trustStorePath = trustStorePath; this.trustStoreType = trustStoreType; this.trustStorePassword = trustStorePassword; this.sniHostName = sniHostName; this.provider = provider; this.protocol = protocol; this.ciphers = ciphers; } public boolean enabled() { return enabled; } public String keyStoreFileName() { return keyStoreFileName; } public String keyStoreType() { return keyStoreType; } public char[] keyStorePassword() { return keyStorePassword; } public char[] keyStoreCertificatePassword() { return keyStoreCertificatePassword; } public String keyAlias() { return keyAlias; } public SSLContext sslContext() { return sslContext; } public String trustStoreFileName() { return trustStoreFileName; } public String trustStorePath() { return trustStorePath; } public String trustStoreType() { return trustStoreType; } public char[] trustStorePassword() { return trustStorePassword; } public String sniHostName() { return sniHostName; } public String protocol() { return protocol; } public Collection<String> ciphers() { return ciphers; } public String provider() { return provider; } @Override public String toString() { return "SslConfiguration{" + "enabled=" + enabled + ", keyStoreFileName='" + keyStoreFileName + '\'' + ", keyStoreType='" + keyStoreType + '\'' + ", keyAlias='" + keyAlias + '\'' + ", sslContext=" + sslContext + ", trustStoreFileName='" + trustStoreFileName + '\'' + ", trustStoreType='" + trustStoreType + '\'' + ", sniHostName='" + sniHostName + '\'' + ", provider='" + provider +'\'' + ", protocol='" + protocol + '\'' + ", ciphers='" + ciphers + '\'' + '}'; } }
3,579
27.188976
203
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/RemoteCacheConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.CONFIGURATION; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.FORCE_RETURN_VALUES; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.MARSHALLER; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.MARSHALLER_CLASS; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.NAME; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.NEAR_CACHE_BLOOM_FILTER; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.NEAR_CACHE_FACTORY; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.NEAR_CACHE_MAX_ENTRIES; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.NEAR_CACHE_MODE; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.TEMPLATE_NAME; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.TRANSACTION_MANAGER; import static org.infinispan.client.hotrod.configuration.RemoteCacheConfiguration.TRANSACTION_MODE; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import static org.infinispan.commons.util.Util.getInstance; import static org.infinispan.commons.util.Util.loadClass; import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Properties; import java.util.Scanner; import java.util.function.Consumer; import jakarta.transaction.TransactionManager; import org.infinispan.client.hotrod.DefaultTemplate; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.near.NearCacheFactory; import org.infinispan.client.hotrod.transaction.lookup.GenericTransactionManagerLookup; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.commons.util.TypedProperties; /** * Per-cache configuration. * * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class RemoteCacheConfigurationBuilder implements Builder<RemoteCacheConfiguration> { private final ConfigurationBuilder builder; private final AttributeSet attributes; RemoteCacheConfigurationBuilder(ConfigurationBuilder builder, String name) { this.builder = builder; this.attributes = RemoteCacheConfiguration.attributeDefinitionSet(); this.attributes.attribute(NAME).set(name); } @Override public AttributeSet attributes() { return attributes; } /** * Whether or not to implicitly FORCE_RETURN_VALUE for all calls to this cache. */ public RemoteCacheConfigurationBuilder forceReturnValues(boolean forceReturnValues) { attributes.attribute(FORCE_RETURN_VALUES).set(forceReturnValues); return this; } /** * Specifies the near caching mode. See {@link NearCacheMode} for details on the available modes. * * @param mode one of {@link NearCacheMode} * @return an instance of the builder */ public RemoteCacheConfigurationBuilder nearCacheMode(NearCacheMode mode) { attributes.attribute(NEAR_CACHE_MODE).set(mode); return this; } /** * Specifies the maximum number of entries that will be held in the near cache. Only works when * {@link #nearCacheMode(NearCacheMode)} is not {@link NearCacheMode#DISABLED}. * * @param maxEntries maximum entries in the near cache. * @return an instance of the builder */ public RemoteCacheConfigurationBuilder nearCacheMaxEntries(int maxEntries) { attributes.attribute(NEAR_CACHE_MAX_ENTRIES).set(maxEntries); return this; } /** * Specifies whether bloom filter should be used for near cache to limit the number of write notifications for * unrelated keys. * * @param enable whether to enable bloom filter * @return an instance of this builder */ public RemoteCacheConfigurationBuilder nearCacheUseBloomFilter(boolean enable) { attributes.attribute(NEAR_CACHE_BLOOM_FILTER).set(enable); return this; } /** * Specifies a {@link NearCacheFactory} which is responsible for creating {@link org.infinispan.client.hotrod.near.NearCache} instances. * * @param factory a {@link NearCacheFactory} * @return an instance of the builder */ public RemoteCacheConfigurationBuilder nearCacheFactory(NearCacheFactory factory) { attributes.attribute(NEAR_CACHE_FACTORY).set(factory); return this; } /** * Specifies the declarative configuration to be used to create the cache if it doesn't already exist on the server. * * @param configuration the XML representation of a cache configuration. * @return an instance of the builder */ public RemoteCacheConfigurationBuilder configuration(String configuration) { attributes.attribute(CONFIGURATION).set(configuration); return this; } /** * Specifies a URI pointing to the declarative configuration to be used to create the cache if it doesn't already * exist on the server. * * @param uri the URI of the configuration. * @return an instance of the builder */ public RemoteCacheConfigurationBuilder configurationURI(URI uri) { try { URL url; if (!uri.isAbsolute()) { url = FileLookupFactory.newInstance().lookupFileLocation(uri.toString(), this.getClass().getClassLoader()); } else { url = uri.toURL(); } try (Scanner scanner = new Scanner(url.openStream(), StandardCharsets.UTF_8.toString()).useDelimiter("\\A")) { return this.configuration(scanner.next()); } } catch (Exception e) { throw new CacheConfigurationException(e); } } /** * Specifies the name of a template to be used to create the cache if it doesn't already exist on the server. * * @param templateName the name of the template. * @return an instance of the builder */ public RemoteCacheConfigurationBuilder templateName(String templateName) { attributes.attribute(TEMPLATE_NAME).set(templateName); return this; } /** * Specifies one of the default templates to be used to create the cache if it doesn't already exist on the server. * * @param template the template to use * @return an instance of the builder */ public RemoteCacheConfigurationBuilder templateName(DefaultTemplate template) { attributes.attribute(TEMPLATE_NAME).set(template.getTemplateName()); return this; } /** * The {@link TransactionMode} in which a {@link RemoteCache} will be enlisted. * * @param mode the transaction mode * @return an instance of the builder */ public RemoteCacheConfigurationBuilder transactionMode(TransactionMode mode) { attributes.attribute(TRANSACTION_MODE).set(mode); return this; } /** * Specifies a custom {@link Marshaller} implementation. See {@link #marshaller(Marshaller)}. * * @param className Fully qualifies class name of the marshaller implementation. */ public RemoteCacheConfigurationBuilder marshaller(String className) { marshaller(loadClass(className, Thread.currentThread().getContextClassLoader())); return this; } /** * Specifies a custom {@link Marshaller} implementation. See {@link #marshaller(Marshaller)}. * * @param marshallerClass the marshaller class. */ public RemoteCacheConfigurationBuilder marshaller(Class<? extends Marshaller> marshallerClass) { attributes.attribute(MARSHALLER_CLASS).set(marshallerClass); return this; } /** * Specifies a custom {@link Marshaller} implementation to serialize and deserialize user objects. Has precedence over * {@link #marshaller(Class)} and {@link #marshaller(String)}. If not configured, the marshaller from the * {@link org.infinispan.client.hotrod.RemoteCacheManager} will be used for the cache operations. * * @param marshaller the marshaller instance */ public RemoteCacheConfigurationBuilder marshaller(Marshaller marshaller) { attributes.attribute(MARSHALLER).set(marshaller); return this; } /** * The {@link javax.transaction.TransactionManager} to use for the cache * * @param manager an instance of a TransactionManager * @return an instance of the builder * @deprecated since 12.0. To be removed in Infinispan 14. Use {@link #transactionManagerLookup(TransactionManagerLookup)} * instead. */ @Deprecated public RemoteCacheConfigurationBuilder transactionManager(TransactionManager manager) { return transactionManagerLookup(() -> manager); } /** * The {@link TransactionManagerLookup} to lookup for the {@link TransactionManager} to interact with. * * @param lookup A {@link TransactionManagerLookup} instance. * @return An instance of the builder. */ public RemoteCacheConfigurationBuilder transactionManagerLookup(TransactionManagerLookup lookup) { attributes.attribute(TRANSACTION_MANAGER).set(lookup); return this; } @Override public void validate() { if (attributes.attribute(CONFIGURATION).isModified() && attributes.attribute(TEMPLATE_NAME).isModified()) { throw Log.HOTROD.remoteCacheTemplateNameXorConfiguration(attributes.attribute(NAME).get()); } if (attributes.attribute(TRANSACTION_MODE).get() == null) { throw HOTROD.invalidTransactionMode(); } if (attributes.attribute(TRANSACTION_MANAGER).get() == null) { throw HOTROD.invalidTransactionManagerLookup(); } } @Override public RemoteCacheConfiguration create() { return new RemoteCacheConfiguration(attributes.protect()); } @Override public Builder<?> read(RemoteCacheConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } public ConfigurationBuilder withProperties(Properties properties) { TypedProperties typed = TypedProperties.toTypedProperties(properties); findCacheProperty(typed, ConfigurationProperties.CACHE_CONFIGURATION_SUFFIX, this::configuration); findCacheProperty(typed, ConfigurationProperties.CACHE_CONFIGURATION_URI_SUFFIX, v -> this.configurationURI(URI.create(v))); findCacheProperty(typed, ConfigurationProperties.CACHE_TEMPLATE_NAME_SUFFIX, this::templateName); findCacheProperty(typed, ConfigurationProperties.CACHE_FORCE_RETURN_VALUES_SUFFIX, v -> this.forceReturnValues(Boolean.parseBoolean(v))); findCacheProperty(typed, ConfigurationProperties.CACHE_NEAR_CACHE_MODE_SUFFIX, v -> this.nearCacheMode(NearCacheMode.valueOf(v))); findCacheProperty(typed, ConfigurationProperties.CACHE_NEAR_CACHE_MAX_ENTRIES_SUFFIX, v -> this.nearCacheMaxEntries(Integer.parseInt(v))); findCacheProperty(typed, ConfigurationProperties.CACHE_NEAR_CACHE_BLOOM_FILTER_SUFFIX, v -> this.nearCacheUseBloomFilter(Boolean.parseBoolean(v))); findCacheProperty(typed, ConfigurationProperties.CACHE_NEAR_CACHE_FACTORY_SUFFIX, v -> this.nearCacheFactory(getInstance(loadClass(v, builder.classLoader())))); findCacheProperty(typed, ConfigurationProperties.CACHE_TRANSACTION_MODE_SUFFIX, v -> this.transactionMode(TransactionMode.valueOf(v))); findCacheProperty(typed, ConfigurationProperties.CACHE_TRANSACTION_MANAGER_LOOKUP_SUFFIX, this::transactionManagerLookupClass); findCacheProperty(typed, ConfigurationProperties.CACHE_MARSHALLER, this::marshaller); return builder; } private void transactionManagerLookupClass(String lookupClass) { TransactionManagerLookup lookup = lookupClass == null || GenericTransactionManagerLookup.class.getName().equals(lookupClass) ? GenericTransactionManagerLookup.getInstance() : getInstance(loadClass(lookupClass, builder.classLoader())); transactionManagerLookup(lookup); } private void findCacheProperty(TypedProperties properties, String name, Consumer<String> consumer) { String cacheName = attributes.attribute(NAME).get(); String value = null; if (properties.containsKey(ConfigurationProperties.CACHE_PREFIX + cacheName + name)) { value = properties.getProperty(ConfigurationProperties.CACHE_PREFIX + cacheName + name, true); } else if (properties.containsKey(ConfigurationProperties.CACHE_PREFIX + '[' + cacheName + ']' + name)) { value = properties.getProperty(ConfigurationProperties.CACHE_PREFIX + '[' + cacheName + ']' + name, true); } if (value != null) { consumer.accept(value); } } }
13,247
42.86755
166
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/SslConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Properties; import javax.net.ssl.SSLContext; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.TypedProperties; /** * * SSLConfigurationBuilder. * * @author Tristan Tarrant * @since 5.3 */ public class SslConfigurationBuilder extends AbstractSecurityConfigurationChildBuilder implements Builder<SslConfiguration> { private boolean enabled = false; private String keyStoreFileName; private String keyStoreType; private char[] keyStorePassword; private char[] keyStoreCertificatePassword; private String keyAlias; private String trustStorePath; private String trustStoreFileName; private String trustStoreType; private char[] trustStorePassword; private SSLContext sslContext; private String sniHostName; private String protocol; private Collection<String> ciphers; private String provider; protected SslConfigurationBuilder(SecurityConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } /** * Disables the SSL support */ public SslConfigurationBuilder disable() { this.enabled = false; return this; } /** * Enables the SSL support */ public SslConfigurationBuilder enable() { this.enabled = true; return this; } /** * Enables or disables the SSL support */ public SslConfigurationBuilder enabled(boolean enabled) { this.enabled = enabled; return this; } /** * Specifies the filename of a keystore to use to create the {@link SSLContext} You also need to * specify a {@link #keyStorePassword(char[])}. Alternatively specify an initialized {@link #sslContext(SSLContext)}. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} */ public SslConfigurationBuilder keyStoreFileName(String keyStoreFileName) { this.keyStoreFileName = keyStoreFileName; return enable(); } /** * Specifies the type of the keystore, such as JKS or JCEKS. Defaults to JKS. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} */ public SslConfigurationBuilder keyStoreType(String keyStoreType) { this.keyStoreType = keyStoreType; return enable(); } /** * Specifies the password needed to open the keystore You also need to specify a * {@link #keyStoreFileName(String)}. Alternatively specify an initialized {@link #sslContext(SSLContext)}. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} */ public SslConfigurationBuilder keyStorePassword(char[] keyStorePassword) { this.keyStorePassword = keyStorePassword; return enable(); } /** * Specifies the password needed to access private key associated with certificate stored in specified * {@link #keyStoreFileName(String)}. If password is not specified, password provided in * {@link #keyStorePassword(char[])} will be used. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()}<br> * <b>Note:</b> this only works with some keystore types * * @deprecated since 9.3 */ @Deprecated public SslConfigurationBuilder keyStoreCertificatePassword(char[] keyStoreCertificatePassword) { this.keyStoreCertificatePassword = keyStoreCertificatePassword; return enable(); } /** * Sets the alias of the key to use, in case the keyStore contains multiple certificates. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} */ public SslConfigurationBuilder keyAlias(String keyAlias) { this.keyAlias = keyAlias; return enable(); } /** * Specifies a pre-built {@link SSLContext} */ public SslConfigurationBuilder sslContext(SSLContext sslContext) { this.sslContext = sslContext; return enable(); } /** * Specifies the filename of a truststore to use to create the {@link SSLContext} You also need * to specify a {@link #trustStorePassword(char[])}. Alternatively specify an initialized {@link #sslContext(SSLContext)}. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} */ public SslConfigurationBuilder trustStoreFileName(String trustStoreFileName) { this.trustStoreFileName = trustStoreFileName; return enable(); } /** * Specifies a path containing certificates in PEM format. An in-memory {@link java.security.KeyStore} will be built * with all the certificates found undert that path. This is mutually exclusive with {@link #trustStoreFileName} * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} * * @deprecated since 12.0 to be removed in 15.0. Use {@link #trustStoreFileName(String)} and pass <tt>pem</tt> to {@link #trustStoreType(String)}. */ @Deprecated public SslConfigurationBuilder trustStorePath(String trustStorePath) { HOTROD.deprecatedConfigurationProperty(ConfigurationProperties.TRUST_STORE_PATH); this.trustStorePath = trustStorePath; return enable(); } /** * Specifies the type of the truststore, such as JKS or JCEKS. Defaults to JKS. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} */ public SslConfigurationBuilder trustStoreType(String trustStoreType) { this.trustStoreType = trustStoreType; return enable(); } /** * Specifies the password needed to open the truststore You also need to specify a * {@link #trustStoreFileName(String)}. Alternatively specify an initialized {@link #sslContext(SSLContext)}. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} */ public SslConfigurationBuilder trustStorePassword(char[] trustStorePassword) { this.trustStorePassword = trustStorePassword; return enable(); } /** * Specifies the TLS SNI hostname for the connection * @see javax.net.ssl.SSLParameters#setServerNames(List). * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} */ public SslConfigurationBuilder sniHostName(String sniHostName) { this.sniHostName = sniHostName; return enable(); } /** * Configures the SSL provider. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} * * @see javax.net.ssl.SSLContext#getInstance(String) * @param provider The name of the provider to use when obtaining an SSLContext. */ public SslConfigurationBuilder provider(String provider) { this.provider = provider; return enable(); } /** * Configures the secure socket protocol. * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} * * @see javax.net.ssl.SSLContext#getInstance(String) * @param protocol The standard name of the requested protocol, e.g TLSv1.2 */ public SslConfigurationBuilder protocol(String protocol) { this.protocol = protocol; return enable(); } /** * Configures the ciphers * Setting this property also implicitly enables SSL/TLS (see {@link #enable()} * * @see javax.net.ssl.SSLContext#getInstance(String) * @param ciphers one or more cipher names */ public SslConfigurationBuilder ciphers(String... ciphers) { this.ciphers = Arrays.asList(ciphers); return enable(); } @Override public void validate() { if (enabled) { if (sslContext == null) { if (keyStoreFileName != null && keyStorePassword == null) { throw HOTROD.missingKeyStorePassword(keyStoreFileName); } if (trustStoreFileName == null && trustStorePath == null) { throw HOTROD.noSSLTrustManagerConfiguration(); } if (trustStoreFileName != null && trustStorePath != null) { throw HOTROD.trustStoreFileAndPathExclusive(); } if (trustStoreFileName != null && trustStorePassword == null && !"pem".equalsIgnoreCase(trustStoreType)) { throw HOTROD.missingTrustStorePassword(trustStoreFileName); } } else { if (keyStoreFileName != null || trustStoreFileName != null) { throw HOTROD.xorSSLContext(); } } } } @Override public SslConfiguration create() { return new SslConfiguration(enabled, keyStoreFileName, keyStoreType, keyStorePassword, keyStoreCertificatePassword, keyAlias, sslContext, trustStoreFileName, trustStorePath, trustStoreType, trustStorePassword, sniHostName, provider, protocol, ciphers); } @Override public SslConfigurationBuilder read(SslConfiguration template, Combine combine) { this.enabled = template.enabled(); this.keyStoreFileName = template.keyStoreFileName(); this.keyStoreType = template.keyStoreType(); this.keyStorePassword = template.keyStorePassword(); this.keyStoreCertificatePassword = template.keyStoreCertificatePassword(); this.keyAlias = template.keyAlias(); this.sslContext = template.sslContext(); this.trustStoreFileName = template.trustStoreFileName(); this.trustStorePath = template.trustStorePath(); this.trustStoreType = template.trustStoreType(); this.trustStorePassword = template.trustStorePassword(); this.sniHostName = template.sniHostName(); this.provider = template.provider(); this.protocol = template.protocol(); this.ciphers = template.ciphers() != null ? new ArrayList<>(template.ciphers()) : null; return this; } @Override public ConfigurationBuilder withProperties(Properties properties) { TypedProperties typed = TypedProperties.toTypedProperties(properties); if (typed.containsKey(ConfigurationProperties.KEY_STORE_FILE_NAME)) this.keyStoreFileName(typed.getProperty(ConfigurationProperties.KEY_STORE_FILE_NAME, keyStoreFileName, true)); if (typed.containsKey(ConfigurationProperties.KEY_STORE_TYPE)) this.keyStoreType(typed.getProperty(ConfigurationProperties.KEY_STORE_TYPE, null, true)); if (typed.containsKey(ConfigurationProperties.KEY_STORE_PASSWORD)) this.keyStorePassword(typed.getProperty(ConfigurationProperties.KEY_STORE_PASSWORD, null, true).toCharArray()); if (typed.containsKey(ConfigurationProperties.KEY_STORE_CERTIFICATE_PASSWORD)) this.keyStoreCertificatePassword(typed.getProperty(ConfigurationProperties.KEY_STORE_CERTIFICATE_PASSWORD, null, true).toCharArray()); if (typed.containsKey(ConfigurationProperties.KEY_ALIAS)) this.keyAlias(typed.getProperty(ConfigurationProperties.KEY_ALIAS, null, true)); if (typed.containsKey(ConfigurationProperties.TRUST_STORE_FILE_NAME)) this.trustStoreFileName(typed.getProperty(ConfigurationProperties.TRUST_STORE_FILE_NAME, trustStoreFileName, true)); if (typed.containsKey(ConfigurationProperties.TRUST_STORE_PATH)) { this.trustStorePath(typed.getProperty(ConfigurationProperties.TRUST_STORE_PATH, trustStorePath, true)); } if (typed.containsKey(ConfigurationProperties.TRUST_STORE_TYPE)) this.trustStoreType(typed.getProperty(ConfigurationProperties.TRUST_STORE_TYPE, null, true)); if (typed.containsKey(ConfigurationProperties.TRUST_STORE_PASSWORD)) this.trustStorePassword(typed.getProperty(ConfigurationProperties.TRUST_STORE_PASSWORD, null, true).toCharArray()); if(typed.containsKey(ConfigurationProperties.SSL_PROTOCOL)) this.protocol(typed.getProperty(ConfigurationProperties.SSL_PROTOCOL, null, true)); if(typed.containsKey(ConfigurationProperties.SSL_PROVIDER)) this.provider(typed.getProperty(ConfigurationProperties.SSL_PROVIDER, null, true)); if(typed.containsKey(ConfigurationProperties.SSL_CIPHERS)) this.ciphers(typed.getProperty(ConfigurationProperties.SSL_CIPHERS, null, true).split(" ")); if (typed.containsKey(ConfigurationProperties.SNI_HOST_NAME)) this.sniHostName(typed.getProperty(ConfigurationProperties.SNI_HOST_NAME, null, true)); if (typed.containsKey(ConfigurationProperties.SSL_CONTEXT)) this.sslContext((SSLContext) typed.get(ConfigurationProperties.SSL_CONTEXT)); if (typed.containsKey(ConfigurationProperties.USE_SSL)) this.enabled(typed.getBooleanProperty(ConfigurationProperties.USE_SSL, enabled, true)); return builder.getBuilder(); } }
13,063
38.349398
149
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ConfigurationChildBuilder.java
package org.infinispan.client.hotrod.configuration; import java.net.URI; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import jakarta.transaction.Synchronization; import javax.transaction.xa.XAResource; import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.TransportFactory; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashV2; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.protostream.SerializationContextInitializer; /** * ConfigurationChildBuilder. * * @author Tristan Tarrant * @since 5.3 */ public interface ConfigurationChildBuilder { /** * Adds a new remote server */ ServerConfigurationBuilder addServer(); /** * Adds a new remote server cluster */ ClusterConfigurationBuilder addCluster(String clusterName); /** * Adds a list of remote servers in the form: host1[:port][;host2[:port]]... */ ConfigurationBuilder addServers(String servers); /** * Configuration for the executor service used for asynchronous work on the Transport, including * asynchronous marshalling and Cache 'async operations' such as Cache.putAsync(). */ ExecutorFactoryConfigurationBuilder asyncExecutorFactory(); /** * For replicated (vs distributed) Hot Rod server clusters, the client balances requests to the * servers according to this strategy. */ ConfigurationBuilder balancingStrategy(String balancingStrategy); /** * For replicated (vs distributed) Hot Rod server clusters, the client balances requests to the * servers according to this strategy. */ ConfigurationBuilder balancingStrategy(Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory); /** * For replicated (vs distributed) Hot Rod server clusters, the client balances requests to the * servers according to this strategy. */ ConfigurationBuilder balancingStrategy(Class<? extends FailoverRequestBalancingStrategy> balancingStrategy); /** * Specifies the {@link ClassLoader} used to find certain resources used by configuration when specified by name * (e.g. certificate stores). Infinispan will search through the classloader which loaded this class, the system * classloader and the TCCL classloader. * @deprecated since 9.0. To be removed in 12.0. If you need to load configuration resources from other locations, you will need to do so * yourself and use the appropriate configuration methods (e.g. {@link SslConfigurationBuilder#sslContext(javax.net.ssl.SSLContext)}) */ @Deprecated ConfigurationBuilder classLoader(ClassLoader classLoader); /** * Specifies the level of "intelligence" the client should have */ ConfigurationBuilder clientIntelligence(ClientIntelligence clientIntelligence); /** * Configures the connection pool */ ConnectionPoolConfigurationBuilder connectionPool(); /** * This property defines the maximum socket connect timeout in milliseconds before giving up connecting to the * server. Defaults to {@link org.infinispan.client.hotrod.impl.ConfigurationProperties#DEFAULT_CONNECT_TIMEOUT} */ ConfigurationBuilder connectionTimeout(int connectionTimeout); /** * Defines the {@link ConsistentHash} implementation to use for the specified version. By default, * {@link ConsistentHashV2} is used for version 1 and {@link ConsistentHashV2} is used for version 2. */ ConfigurationBuilder consistentHashImpl(int version, Class<? extends ConsistentHash> consistentHashClass); /** * Defines the {@link ConsistentHash} implementation to use for the specified version. By default, * {@link ConsistentHashV2} is used for version 1 and {@link ConsistentHashV2} is used for version 2. */ ConfigurationBuilder consistentHashImpl(int version, String consistentHashClass); ConfigurationBuilder dnsResolverMinTTL(int minTTL); ConfigurationBuilder dnsResolverMaxTTL(int maxTTL); ConfigurationBuilder dnsResolverNegativeTTL(int negativeTTL); /** * Whether or not to implicitly FORCE_RETURN_VALUE for all calls. */ ConfigurationBuilder forceReturnValues(boolean forceReturnValues); /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated ConfigurationBuilder keySizeEstimate(int keySizeEstimate); /** * Allows you to specify a custom {@link Marshaller} implementation to * serialize and deserialize user objects. This method is mutually exclusive with {@link #marshaller(Marshaller)}. */ ConfigurationBuilder marshaller(String marshaller); /** * Allows you to specify a custom {@link Marshaller} implementation to * serialize and deserialize user objects. This method is mutually exclusive with {@link #marshaller(Marshaller)}. */ ConfigurationBuilder marshaller(Class<? extends Marshaller> marshaller); /** * Allows you to specify an instance of {@link Marshaller} to serialize * and deserialize user objects. This method is mutually exclusive with {@link #marshaller(Class)}. */ ConfigurationBuilder marshaller(Marshaller marshaller); /** * Supply a {@link SerializationContextInitializer} implementation to register classes with the {@link * org.infinispan.commons.marshall.ProtoStreamMarshaller}'s {@link org.infinispan.protostream.SerializationContext}. */ ConfigurationBuilder addContextInitializer(String contextInitializer); /** * Supply a {@link SerializationContextInitializer} implementation to register classes with the {@link * org.infinispan.commons.marshall.ProtoStreamMarshaller}'s {@link org.infinispan.protostream.SerializationContext}. */ ConfigurationBuilder addContextInitializer(SerializationContextInitializer contextInitializer); /** * Convenience method to supply multiple {@link SerializationContextInitializer} implementations. * * @see #addContextInitializer(SerializationContextInitializer). */ ConfigurationBuilder addContextInitializers(SerializationContextInitializer... contextInitializers); /** * This property defines the protocol version that this client should use. Defaults to the latest protocol version * supported by this client. * * @deprecated since 9.0. To be removed in 12.0. Use {@link ConfigurationChildBuilder#version(ProtocolVersion)} instead. */ @Deprecated ConfigurationBuilder protocolVersion(String protocolVersion); /** * This property defines the protocol version that this client should use. Defaults to the latest protocol version * supported by this client. */ ConfigurationBuilder version(ProtocolVersion protocolVersion); /** * This property defines the maximum socket read timeout in milliseconds before giving up waiting * for bytes from the server. Defaults to {@link org.infinispan.client.hotrod.impl.ConfigurationProperties#DEFAULT_SO_TIMEOUT} */ ConfigurationBuilder socketTimeout(int socketTimeout); /** * Security Configuration */ SecurityConfigurationBuilder security(); /** * Affects TCP NODELAY on the TCP stack. Defaults to enabled */ ConfigurationBuilder tcpNoDelay(boolean tcpNoDelay); /** * Affects TCP KEEPALIVE on the TCP stack. Defaults to disable */ ConfigurationBuilder tcpKeepAlive(boolean keepAlive); /** * Configures this builder using the specified URI. */ ConfigurationBuilder uri(URI uri); /** * Configures this builder using the specified URI. */ ConfigurationBuilder uri(String uri); /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated ConfigurationBuilder valueSizeEstimate(int valueSizeEstimate); /** * It sets the maximum number of retries for each request. A valid value should be greater or equals than 0 (zero). * Zero means no retry will made in case of a network failure. It defaults to 10. */ ConfigurationBuilder maxRetries(int maxRetries); /** * List of regular expressions for classes that can be deserialized using standard Java deserialization * when reading data that might have been stored with a different endpoint, e.g. REST. */ ConfigurationBuilder addJavaSerialAllowList(String... regEx); /** * @deprecated Use {@link #addJavaSerialAllowList(String...)} instead. To be removed in 14.0. */ @Deprecated ConfigurationBuilder addJavaSerialWhiteList(String... regEx); /** * Sets the batch size of internal iterators (ie. <code>keySet().iterator()</code>. Defaults to 10_000 * @param batchSize the batch size to set * @return this configuration builder with the batch size set */ ConfigurationBuilder batchSize(int batchSize); /** * Configures client-side statistics. */ StatisticsConfigurationBuilder statistics(); /** * Transaction configuration */ TransactionConfigurationBuilder transaction(); /** * Per-cache configuration * @param name the name of the cache to which specific configuration should be applied. You may use wildcard globbing (e.g. <code>cache-*</code>) which will apply to any cache that matches. * @return the {@link RemoteCacheConfigurationBuilder} for the cache */ RemoteCacheConfigurationBuilder remoteCache(String name); /** * Sets the transaction's timeout. * <p> * This timeout is used by the server to rollback unrecoverable transaction when they are idle for this amount of * time. * <p> * An unrecoverable transaction are transaction enlisted as {@link Synchronization} ({@link TransactionMode#NON_XA}) * or {@link XAResource} without recovery enabled ({@link TransactionMode#NON_DURABLE_XA}). * <p> * For {@link XAResource}, this value is overwritten by {@link XAResource#setTransactionTimeout(int)}. * <p> * It defaults to 1 minute. */ ConfigurationBuilder transactionTimeout(long timeout, TimeUnit timeUnit); /** * Set the TransportFactory. It defaults to {@link org.infinispan.client.hotrod.impl.transport.netty.DefaultTransportFactory} * @param transportFactory an instance of {@link TransportFactory} */ ConfigurationBuilder transportFactory(TransportFactory transportFactory); /** * Configures this builder using the specified properties. See {@link ConfigurationBuilder} for a list. */ ConfigurationBuilder withProperties(Properties properties); /** * Builds a configuration object */ Configuration build(); }
10,777
36.950704
192
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/AbstractSecurityConfigurationChildBuilder.java
package org.infinispan.client.hotrod.configuration; /** * AbstractSecurityConfigurationChildBuilder. * * @author Tristan Tarrant * @since 7.0 */ public class AbstractSecurityConfigurationChildBuilder extends AbstractConfigurationChildBuilder { final SecurityConfigurationBuilder builder; AbstractSecurityConfigurationChildBuilder(SecurityConfigurationBuilder builder) { super(builder.getBuilder()); this.builder = builder; } public AuthenticationConfigurationBuilder authentication() { return builder.authentication(); } public SslConfigurationBuilder ssl() { return builder.ssl(); } }
640
24.64
98
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/AuthenticationConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.security.BasicCallbackHandler; import org.infinispan.client.hotrod.security.TokenCallbackHandler; import org.infinispan.client.hotrod.security.VoidCallbackHandler; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.StringPropertyReplacer; import org.infinispan.commons.util.TypedProperties; import org.infinispan.commons.util.Util; /** * AuthenticationConfigurationBuilder. * * @author Tristan Tarrant * @since 7.0 */ public class AuthenticationConfigurationBuilder extends AbstractSecurityConfigurationChildBuilder implements Builder<AuthenticationConfiguration> { public static final String DEFAULT_REALM = "default"; public static final String DEFAULT_SERVER_NAME = "infinispan"; public static final String DEFAULT_MECHANISM = "SCRAM-SHA-512"; private static final String EXTERNAL_MECH = "EXTERNAL"; private static final String OAUTHBEARER_MECH = "OAUTHBEARER"; private static final String GSSAPI_MECH = "GSSAPI"; private static final String GS2_KRB5_MECH = "GS2-KRB5"; private CallbackHandler callbackHandler; private boolean enabled = false; private String serverName; private Map<String, String> saslProperties = new HashMap<>(); private String saslMechanism; private Subject clientSubject; private String username; private char[] password; private String realm; private String token; public AuthenticationConfigurationBuilder(SecurityConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } /** * Specifies a {@link CallbackHandler} to be used during the authentication handshake. The {@link Callback}s that * need to be handled are specific to the chosen SASL mechanism. */ public AuthenticationConfigurationBuilder callbackHandler(CallbackHandler callbackHandler) { this.callbackHandler = callbackHandler; return this; } /** * Configures whether authentication should be enabled or not */ public AuthenticationConfigurationBuilder enabled(boolean enabled) { this.enabled = enabled; return this; } /** * Enables authentication */ public AuthenticationConfigurationBuilder enable() { this.enabled = true; return this; } /** * Disables authentication */ public AuthenticationConfigurationBuilder disable() { this.enabled = false; return this; } /** * Selects the SASL mechanism to use for the connection to the server. Setting this property also implicitly enables * authentication (see {@link #enable()} */ public AuthenticationConfigurationBuilder saslMechanism(String saslMechanism) { this.saslMechanism = saslMechanism; return enable(); } /** * Sets the SASL properties. Setting this property also implicitly enables authentication (see {@link #enable()} */ public AuthenticationConfigurationBuilder saslProperties(Map<String, String> saslProperties) { this.saslProperties = saslProperties; return enable(); } /** * Sets the SASL QOP property. If multiple values are specified they will determine preference order. Setting this * property also implicitly enables authentication (see {@link #enable()} */ public AuthenticationConfigurationBuilder saslQop(SaslQop... qop) { StringBuilder s = new StringBuilder(); for (int i = 0; i < qop.length; i++) { if (i > 0) { s.append(","); } s.append(qop[i].toString()); } this.saslProperties.put(Sasl.QOP, s.toString()); return enable(); } /** * Sets the SASL strength property. If multiple values are specified they will determine preference order. Setting * this property also implicitly enables authentication (see {@link #enable()} */ public AuthenticationConfigurationBuilder saslStrength(SaslStrength... strength) { StringBuilder s = new StringBuilder(); for (int i = 0; i < strength.length; i++) { if (i > 0) { s.append(","); } s.append(strength[i].toString()); } this.saslProperties.put(Sasl.STRENGTH, s.toString()); return enable(); } /** * Sets the name of the server as expected by the SASL protocol Setting this property also implicitly enables * authentication (see {@link #enable()} This defaults to {@link #DEFAULT_SERVER_NAME}. */ public AuthenticationConfigurationBuilder serverName(String serverName) { this.serverName = serverName; return enable(); } /** * Sets the client subject, necessary for those SASL mechanisms which require it to access client credentials (i.e. * GSSAPI). Setting this property also implicitly enables authentication (see {@link #enable()} */ public AuthenticationConfigurationBuilder clientSubject(Subject clientSubject) { this.clientSubject = clientSubject; return enable(); } /** * Specifies the username to be used for authentication. This will use a simple CallbackHandler. This is mutually * exclusive with explicitly providing the CallbackHandler. Setting this property also implicitly enables * authentication (see {@link #enable()} */ public AuthenticationConfigurationBuilder username(String username) { this.username = username; return enable(); } /** * Specifies the password to be used for authentication. A username is also required. Setting this property also * implicitly enables authentication (see {@link #enable()} */ public AuthenticationConfigurationBuilder password(String password) { this.password = password != null ? password.toCharArray() : null; return enable(); } /** * Specifies the password to be used for authentication. A username is also required. Setting this property also * implicitly enables authentication (see {@link #enable()} */ public AuthenticationConfigurationBuilder password(char[] password) { this.password = password; return enable(); } /** * Specifies the realm to be used for authentication. Username and password also need to be supplied. If none is * specified, this defaults to {@link #DEFAULT_REALM}. Setting this property also implicitly enables authentication * (see {@link #enable()} */ public AuthenticationConfigurationBuilder realm(String realm) { this.realm = realm; return enable(); } public AuthenticationConfigurationBuilder token(String token) { this.token = token; return enable(); } @Override public AuthenticationConfiguration create() { String mech = saslMechanism == null ? DEFAULT_MECHANISM : saslMechanism; CallbackHandler cbh = callbackHandler; if (cbh == null) { if (OAUTHBEARER_MECH.equals(mech)) { cbh = new TokenCallbackHandler(token); } else if (username != null) { cbh = new BasicCallbackHandler(username, realm != null ? realm : DEFAULT_REALM, password); } else if (EXTERNAL_MECH.equals(mech) || GSSAPI_MECH.equals(mech) || GS2_KRB5_MECH.equals(mech)) { cbh = new VoidCallbackHandler(); } } return new AuthenticationConfiguration(cbh, clientSubject, enabled, mech, saslProperties, serverName != null ? serverName : DEFAULT_SERVER_NAME); } @Override public Builder<?> read(AuthenticationConfiguration template, Combine combine) { this.callbackHandler = template.callbackHandler(); this.clientSubject = template.clientSubject(); this.enabled = template.enabled(); this.saslMechanism = template.saslMechanism(); this.saslProperties = template.saslProperties(); this.serverName = template.serverName(); return this; } @Override public void validate() { if (enabled) { if (callbackHandler == null && clientSubject == null && username == null && token == null && !EXTERNAL_MECH.equals(saslMechanism)) { throw HOTROD.invalidAuthenticationConfiguration(); } if (OAUTHBEARER_MECH.equals(saslMechanism) && callbackHandler == null && token == null) { throw HOTROD.oauthBearerWithoutToken(); } if (callbackHandler != null && (username != null || token != null)) { throw HOTROD.callbackHandlerAndUsernameMutuallyExclusive(); } } } @Override public ConfigurationBuilder withProperties(Properties properties) { TypedProperties typed = TypedProperties.toTypedProperties(properties); if (typed.containsKey(ConfigurationProperties.SASL_MECHANISM)) saslMechanism(typed.getProperty(ConfigurationProperties.SASL_MECHANISM, saslMechanism, true)); Object prop = typed.get(ConfigurationProperties.AUTH_CALLBACK_HANDLER); if (prop instanceof String) { String cbhClassName = StringPropertyReplacer.replaceProperties((String) prop); CallbackHandler handler = Util.getInstance(cbhClassName, builder.getBuilder().classLoader()); this.callbackHandler(handler); } else if (prop instanceof CallbackHandler) { this.callbackHandler((CallbackHandler) prop); } if (typed.containsKey(ConfigurationProperties.AUTH_USERNAME)) username(typed.getProperty(ConfigurationProperties.AUTH_USERNAME, username, true)); if (typed.containsKey(ConfigurationProperties.AUTH_PASSWORD)) password(typed.getProperty(ConfigurationProperties.AUTH_PASSWORD, null, true)); if (typed.containsKey(ConfigurationProperties.AUTH_TOKEN)) token(typed.getProperty(ConfigurationProperties.AUTH_TOKEN, token, true)); if (typed.containsKey(ConfigurationProperties.AUTH_REALM)) realm(typed.getProperty(ConfigurationProperties.AUTH_REALM, realm, true)); if (typed.containsKey(ConfigurationProperties.AUTH_SERVER_NAME)) serverName(typed.getProperty(ConfigurationProperties.AUTH_SERVER_NAME, serverName, true)); if (typed.containsKey(ConfigurationProperties.AUTH_CLIENT_SUBJECT)) this.clientSubject((Subject) typed.get(ConfigurationProperties.AUTH_CLIENT_SUBJECT)); Map<String, String> saslProperties = typed.entrySet().stream() .filter(e -> ((String) e.getKey()).startsWith(ConfigurationProperties.SASL_PROPERTIES_PREFIX)) .collect(Collectors.toMap( e -> ConfigurationProperties.SASL_PROPERTIES_PREFIX_REGEX .matcher((String) e.getKey()).replaceFirst(""), e -> StringPropertyReplacer.replaceProperties((String) e.getValue()))); if (!saslProperties.isEmpty()) this.saslProperties(saslProperties); if (typed.containsKey(ConfigurationProperties.USE_AUTH)) this.enabled(typed.getBooleanProperty(ConfigurationProperties.USE_AUTH, enabled, true)); return builder.getBuilder(); } }
11,584
38.271186
151
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/TransactionConfiguration.java
package org.infinispan.client.hotrod.configuration; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; /** * Configures a transactional {@link RemoteCache}. * * @author Pedro Ruivo * @since 9.3 * @deprecated since 12.0. To be removed in Infinispan 14 */ @Deprecated public class TransactionConfiguration { private final TransactionMode transactionMode; private final TransactionManagerLookup transactionManagerLookup; private final long timeout; TransactionConfiguration(TransactionMode transactionMode, TransactionManagerLookup transactionManagerLookup, long timeout) { this.transactionMode = transactionMode; this.transactionManagerLookup = transactionManagerLookup; this.timeout = timeout; } @Deprecated public TransactionMode transactionMode() { return transactionMode; } @Deprecated public TransactionManagerLookup transactionManagerLookup() { return transactionManagerLookup; } /** * @see TransactionConfigurationBuilder#timeout(long, TimeUnit) */ @Deprecated public long timeout() { return timeout; } @Override public String toString() { return "TransactionConfiguration{" + "transactionMode=" + transactionMode + ", transactionManagerLookup=" + transactionManagerLookup + ", timeout=" + timeout + '}'; } void toProperties(Properties properties) { properties.setProperty(ConfigurationProperties.TRANSACTION_MODE, transactionMode.name()); properties.setProperty(ConfigurationProperties.TRANSACTION_MANAGER_LOOKUP, transactionManagerLookup.getClass().getName()); properties.setProperty(ConfigurationProperties.TRANSACTION_TIMEOUT, String.valueOf(timeout)); } }
1,968
29.765625
128
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.lang.ref.WeakReference; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.TransportFactory; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.impl.HotRodURI; import org.infinispan.client.hotrod.impl.consistenthash.CRC16ConsistentHashV2; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashV2; import org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.util.Features; import org.infinispan.commons.util.StringPropertyReplacer; import org.infinispan.commons.util.TypedProperties; import org.infinispan.commons.util.Util; import org.infinispan.protostream.SerializationContextInitializer; /** * <p>ConfigurationBuilder used to generate immutable {@link Configuration} objects to pass to the * {@link RemoteCacheManager#RemoteCacheManager(Configuration)} constructor.</p> * * <p>If you prefer to configure the client declaratively, see {@link org.infinispan.client.hotrod.configuration}</p> * * @author Tristan Tarrant * @since 5.3 */ public class ConfigurationBuilder implements ConfigurationChildBuilder, Builder<Configuration> { private static final Log log = LogFactory.getLog(ConfigurationBuilder.class, Log.class); // Match IPv4 (host:port) or IPv6 ([host]:port) addresses private static final Pattern ADDRESS_PATTERN = Pattern .compile("(\\[([0-9A-Fa-f:]+)\\]|([^:/?#]*))(?::(\\d*))?"); private static final int CACHE_PREFIX_LENGTH = ConfigurationProperties.CACHE_PREFIX.length(); private WeakReference<ClassLoader> classLoader; private final ExecutorFactoryConfigurationBuilder asyncExecutorFactory; private Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory = RoundRobinBalancingStrategy::new; private ClientIntelligence clientIntelligence = ClientIntelligence.getDefault(); private final ConnectionPoolConfigurationBuilder connectionPool; private int connectionTimeout = ConfigurationProperties.DEFAULT_CONNECT_TIMEOUT; @SuppressWarnings("unchecked") private final Class<? extends ConsistentHash>[] consistentHashImpl = new Class[]{ null, ConsistentHashV2.class, SegmentConsistentHash.class, CRC16ConsistentHashV2.class }; private boolean forceReturnValues; private int keySizeEstimate = ConfigurationProperties.DEFAULT_KEY_SIZE; private Class<? extends Marshaller> marshallerClass; private Marshaller marshaller; private ProtocolVersion protocolVersion = ProtocolVersion.DEFAULT_PROTOCOL_VERSION; private final List<ServerConfigurationBuilder> servers = new ArrayList<>(); private int socketTimeout = ConfigurationProperties.DEFAULT_SO_TIMEOUT; private final SecurityConfigurationBuilder security; private boolean tcpNoDelay = true; private boolean tcpKeepAlive = false; private int valueSizeEstimate = ConfigurationProperties.DEFAULT_VALUE_SIZE; private int maxRetries = ConfigurationProperties.DEFAULT_MAX_RETRIES; private final NearCacheConfigurationBuilder nearCache; private final List<String> allowListRegExs = new ArrayList<>(); private int batchSize = ConfigurationProperties.DEFAULT_BATCH_SIZE; private final TransactionConfigurationBuilder transaction; private final StatisticsConfigurationBuilder statistics; private final List<ClusterConfigurationBuilder> clusters = new ArrayList<>(); private Features features; private final List<SerializationContextInitializer> contextInitializers = new ArrayList<>(); private final Map<String, RemoteCacheConfigurationBuilder> remoteCacheBuilders; private TransportFactory transportFactory = TransportFactory.DEFAULT; private boolean tracingPropagationEnabled = ConfigurationProperties.DEFAULT_TRACING_PROPAGATION_ENABLED; private int dnsResolverMinTTL = 0; private int dnsResolverMaxTTL = Integer.MAX_VALUE; private int dnsResolverNegativeTTL = 0; public ConfigurationBuilder() { this.classLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader()); this.connectionPool = new ConnectionPoolConfigurationBuilder(this); this.asyncExecutorFactory = new ExecutorFactoryConfigurationBuilder(this); this.security = new SecurityConfigurationBuilder(this); this.nearCache = new NearCacheConfigurationBuilder(this); this.transaction = new TransactionConfigurationBuilder(this); this.statistics = new StatisticsConfigurationBuilder(this); this.remoteCacheBuilders = new HashMap<>(); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } @Override public ServerConfigurationBuilder addServer() { ServerConfigurationBuilder builder = new ServerConfigurationBuilder(this); this.servers.add(builder); return builder; } @Override public ClusterConfigurationBuilder addCluster(String clusterName) { ClusterConfigurationBuilder builder = new ClusterConfigurationBuilder(this, clusterName); this.clusters.add(builder); return builder; } @Override public ConfigurationBuilder addServers(String servers) { parseServers(servers, (host, port) -> addServer().host(host).port(port)); return this; } public List<ServerConfigurationBuilder> servers() { return servers; } public static void parseServers(String servers, BiConsumer<String, Integer> c) { for (String server : servers.split(";")) { Matcher matcher = ADDRESS_PATTERN.matcher(server.trim()); if (matcher.matches()) { String v6host = matcher.group(2); String v4host = matcher.group(3); String host = v6host != null ? v6host : v4host; String portString = matcher.group(4); int port = portString == null ? ConfigurationProperties.DEFAULT_HOTROD_PORT : Integer.parseInt(portString); c.accept(host, port); } else { throw HOTROD.parseErrorServerAddress(server); } } } @Override public ExecutorFactoryConfigurationBuilder asyncExecutorFactory() { return this.asyncExecutorFactory; } @Override public ConfigurationBuilder balancingStrategy(String balancingStrategy) { this.balancingStrategyFactory = () -> Util.getInstance(balancingStrategy, this.classLoader()); return this; } @Override public ConfigurationBuilder balancingStrategy(Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory) { this.balancingStrategyFactory = balancingStrategyFactory; return this; } @Override public ConfigurationBuilder balancingStrategy(Class<? extends FailoverRequestBalancingStrategy> balancingStrategy) { this.balancingStrategyFactory = () -> Util.getInstance(balancingStrategy); return this; } @Override public ConfigurationBuilder classLoader(ClassLoader cl) { this.classLoader = new WeakReference<>(cl); return this; } ClassLoader classLoader() { return classLoader != null ? classLoader.get() : null; } @Override public ConfigurationBuilder clientIntelligence(ClientIntelligence clientIntelligence) { this.clientIntelligence = clientIntelligence; return this; } @Override public ConnectionPoolConfigurationBuilder connectionPool() { return connectionPool; } @Override public ConfigurationBuilder connectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } @Override public ConfigurationBuilder consistentHashImpl(int version, Class<? extends ConsistentHash> consistentHashClass) { if (version == 1) { log.warn("Hash function version 1 is no longer supported."); } else { this.consistentHashImpl[version - 1] = consistentHashClass; } return this; } @Override public ConfigurationBuilder consistentHashImpl(int version, String consistentHashClass) { if (version == 1) { log.warn("Hash function version 1 is no longer supported."); } else { this.consistentHashImpl[version - 1] = Util.loadClass(consistentHashClass, classLoader()); } return this; } @Override public ConfigurationBuilder dnsResolverMinTTL(int minTTL) { this.dnsResolverMinTTL = minTTL; return this; } @Override public ConfigurationBuilder dnsResolverMaxTTL(int maxTTL) { this.dnsResolverMaxTTL = maxTTL; return this; } @Override public ConfigurationBuilder dnsResolverNegativeTTL(int negativeTTL) { this.dnsResolverNegativeTTL = negativeTTL; return this; } @Override public ConfigurationBuilder forceReturnValues(boolean forceReturnValues) { this.forceReturnValues = forceReturnValues; return this; } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated @Override public ConfigurationBuilder keySizeEstimate(int keySizeEstimate) { this.keySizeEstimate = keySizeEstimate; return this; } @Override public ConfigurationBuilder marshaller(String marshallerClassName) { return marshaller(marshallerClassName == null ? null : Util.loadClass(marshallerClassName, classLoader())); } @Override public ConfigurationBuilder marshaller(Class<? extends Marshaller> marshallerClass) { this.marshallerClass = marshallerClass; this.marshaller = marshallerClass == null ? null : Util.getInstance(marshallerClass); return this; } @Override public ConfigurationBuilder marshaller(Marshaller marshaller) { this.marshaller = marshaller; this.marshallerClass = marshaller == null ? null : marshaller.getClass(); return this; } @Override public ConfigurationBuilder addContextInitializer(String contextInitializer) { SerializationContextInitializer sci = Util.getInstance(contextInitializer, this.classLoader()); return addContextInitializers(sci); } @Override public ConfigurationBuilder addContextInitializer(SerializationContextInitializer contextInitializer) { if (contextInitializer != null) this.contextInitializers.add(contextInitializer); return this; } @Override public ConfigurationBuilder addContextInitializers(SerializationContextInitializer... contextInitializers) { this.contextInitializers.addAll(Arrays.asList(contextInitializers)); return this; } /** * @deprecated since 11.0. To be removed in 14.0. Use * {@link RemoteCacheConfigurationBuilder#nearCacheMode(NearCacheMode)} and * {@link RemoteCacheConfigurationBuilder#nearCacheMaxEntries(int)} instead. */ @Deprecated public NearCacheConfigurationBuilder nearCache() { return nearCache; } /** * @deprecated Use {@link ConfigurationBuilder#version(ProtocolVersion)} instead. */ @Deprecated @Override public ConfigurationBuilder protocolVersion(String protocolVersion) { this.protocolVersion = ProtocolVersion.parseVersion(protocolVersion); return this; } @Override public ConfigurationBuilder version(ProtocolVersion protocolVersion) { this.protocolVersion = protocolVersion; return this; } @Override public SecurityConfigurationBuilder security() { return security; } @Override public ConfigurationBuilder socketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; return this; } @Override public ConfigurationBuilder tcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; return this; } @Override public ConfigurationBuilder tcpKeepAlive(boolean keepAlive) { this.tcpKeepAlive = keepAlive; return this; } @Override public ConfigurationBuilder uri(URI uri) { // it returns this return HotRodURI.create(uri).toConfigurationBuilder(this); } @Override public ConfigurationBuilder uri(String uri) { return uri(URI.create(uri)); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated @Override public ConfigurationBuilder valueSizeEstimate(int valueSizeEstimate) { this.valueSizeEstimate = valueSizeEstimate; return this; } @Override public ConfigurationBuilder maxRetries(int maxRetries) { this.maxRetries = maxRetries; return this; } @Override public ConfigurationBuilder addJavaSerialAllowList(String... regEx) { this.allowListRegExs.addAll(Arrays.asList(regEx)); return this; } @Override @Deprecated public ConfigurationBuilder addJavaSerialWhiteList(String... regEx) { return addJavaSerialAllowList(regEx); } @Override public ConfigurationBuilder batchSize(int batchSize) { if (batchSize <= 0) { throw new IllegalArgumentException("batchSize must be greater than 0"); } this.batchSize = batchSize; return this; } @Override public StatisticsConfigurationBuilder statistics() { return statistics; } @Override public TransactionConfigurationBuilder transaction() { return transaction; } @Override public RemoteCacheConfigurationBuilder remoteCache(String name) { return remoteCacheBuilders.computeIfAbsent(name, (n) -> new RemoteCacheConfigurationBuilder(this, n)); } @Override public ConfigurationBuilder transactionTimeout(long timeout, TimeUnit timeUnit) { //TODO replace this invocation with a long field in this class when TransactionConfigurationBuilder is removed. transaction.timeout(timeout, timeUnit); return this; } @Override public ConfigurationBuilder transportFactory(TransportFactory transportFactory) { this.transportFactory = transportFactory; return this; } public ConfigurationBuilder disableTracingPropagation() { this.tracingPropagationEnabled = false; return this; } @Override public ConfigurationBuilder withProperties(Properties properties) { TypedProperties typed = TypedProperties.toTypedProperties(properties); if (typed.containsKey(ConfigurationProperties.URI)) { HotRodURI uri = HotRodURI.create(typed.getProperty(ConfigurationProperties.URI)); this.read(uri.toConfigurationBuilder().build()); } if (typed.containsKey(ConfigurationProperties.ASYNC_EXECUTOR_FACTORY)) { this.asyncExecutorFactory().factoryClass(typed.getProperty(ConfigurationProperties.ASYNC_EXECUTOR_FACTORY, null, true)); } this.asyncExecutorFactory().withExecutorProperties(typed); String balancingStrategyClass = typed.getProperty(ConfigurationProperties.REQUEST_BALANCING_STRATEGY, null, true); if (balancingStrategyClass != null) { this.balancingStrategy(balancingStrategyClass); } if (typed.containsKey(ConfigurationProperties.CLIENT_INTELLIGENCE)) { this.clientIntelligence(typed.getEnumProperty(ConfigurationProperties.CLIENT_INTELLIGENCE, ClientIntelligence.class, ClientIntelligence.getDefault(), true)); } this.connectionPool.withPoolProperties(typed); if (typed.containsKey(ConfigurationProperties.CONNECT_TIMEOUT)) { this.connectionTimeout(typed.getIntProperty(ConfigurationProperties.CONNECT_TIMEOUT, connectionTimeout, true)); } if (typed.containsKey(ConfigurationProperties.HASH_FUNCTION_PREFIX + ".1")) { log.warn("Hash function version 1 is no longer supported"); } for (int i = 0; i < consistentHashImpl.length; i++) { if (consistentHashImpl[i] != null) { int version = i + 1; String hashClassName = typed.getProperty(ConfigurationProperties.HASH_FUNCTION_PREFIX + "." + version, null, true); if (hashClassName != null) { this.consistentHashImpl(version, hashClassName); } } } if (typed.containsKey(ConfigurationProperties.FORCE_RETURN_VALUES)) { this.forceReturnValues(typed.getBooleanProperty(ConfigurationProperties.FORCE_RETURN_VALUES, forceReturnValues, true)); } if (typed.containsKey(ConfigurationProperties.KEY_SIZE_ESTIMATE)) { this.keySizeEstimate(typed.getIntProperty(ConfigurationProperties.KEY_SIZE_ESTIMATE, keySizeEstimate, true)); } if (typed.containsKey(ConfigurationProperties.MARSHALLER)) { this.marshaller(typed.getProperty(ConfigurationProperties.MARSHALLER, null, true)); } if (typed.containsKey(ConfigurationProperties.CONTEXT_INITIALIZERS)) { String initializers = typed.getProperty(ConfigurationProperties.CONTEXT_INITIALIZERS); for (String sci : initializers.split(",")) this.addContextInitializer(sci); } if (typed.containsKey(ConfigurationProperties.PROTOCOL_VERSION)) { this.version(ProtocolVersion.parseVersion(typed.getProperty(ConfigurationProperties.PROTOCOL_VERSION, protocolVersion.toString(), true))); } String serverList = typed.getProperty(ConfigurationProperties.SERVER_LIST, null, true); if (serverList != null) { this.servers.clear(); this.addServers(serverList); } if (typed.containsKey(ConfigurationProperties.SO_TIMEOUT)) { this.socketTimeout(typed.getIntProperty(ConfigurationProperties.SO_TIMEOUT, socketTimeout, true)); } if (typed.containsKey(ConfigurationProperties.TCP_NO_DELAY)) { this.tcpNoDelay(typed.getBooleanProperty(ConfigurationProperties.TCP_NO_DELAY, tcpNoDelay, true)); } if (typed.containsKey(ConfigurationProperties.TCP_KEEP_ALIVE)) { this.tcpKeepAlive(typed.getBooleanProperty(ConfigurationProperties.TCP_KEEP_ALIVE, tcpKeepAlive, true)); } if (typed.containsKey(ConfigurationProperties.VALUE_SIZE_ESTIMATE)) { this.valueSizeEstimate(typed.getIntProperty(ConfigurationProperties.VALUE_SIZE_ESTIMATE, valueSizeEstimate, true)); } if (typed.containsKey(ConfigurationProperties.MAX_RETRIES)) { this.maxRetries(typed.getIntProperty(ConfigurationProperties.MAX_RETRIES, maxRetries, true)); } if (typed.containsKey(ConfigurationProperties.DNS_RESOLVER_MIN_TTL)) { this.dnsResolverMinTTL(typed.getIntProperty(ConfigurationProperties.DNS_RESOLVER_MIN_TTL, dnsResolverMinTTL, true)); } if (typed.containsKey(ConfigurationProperties.DNS_RESOLVER_MAX_TTL)) { this.dnsResolverMaxTTL(typed.getIntProperty(ConfigurationProperties.DNS_RESOLVER_MAX_TTL, dnsResolverMaxTTL, true)); } if (typed.containsKey(ConfigurationProperties.DNS_RESOLVER_NEGATIVE_TTL)) { this.dnsResolverNegativeTTL(typed.getIntProperty(ConfigurationProperties.DNS_RESOLVER_NEGATIVE_TTL, dnsResolverNegativeTTL, true)); } this.security.ssl().withProperties(properties); this.security.authentication().withProperties(properties); String serialAllowList = typed.getProperty(ConfigurationProperties.JAVA_SERIAL_WHITELIST); if (serialAllowList != null && !serialAllowList.isEmpty()) { org.infinispan.commons.logging.Log.CONFIG.deprecatedProperty(ConfigurationProperties.JAVA_SERIAL_WHITELIST, ConfigurationProperties.JAVA_SERIAL_ALLOWLIST); String[] classes = serialAllowList.split(","); Collections.addAll(this.allowListRegExs, classes); } serialAllowList = typed.getProperty(ConfigurationProperties.JAVA_SERIAL_ALLOWLIST); if (serialAllowList != null && !serialAllowList.isEmpty()) { String[] classes = serialAllowList.split(","); Collections.addAll(this.allowListRegExs, classes); } if (typed.containsKey(ConfigurationProperties.BATCH_SIZE)) { this.batchSize(typed.getIntProperty(ConfigurationProperties.BATCH_SIZE, batchSize, true)); } //TODO read TRANSACTION_TIMEOUT property after TransactionConfigurationBuilder is removed. transaction.withTransactionProperties(typed); nearCache.withProperties(properties); parseClusterProperties(typed); Set<String> cachesNames = typed.keySet().stream() .map(k -> (String) k) .filter(k -> k.startsWith(ConfigurationProperties.CACHE_PREFIX)) .map(k -> k.charAt(CACHE_PREFIX_LENGTH) == '[' ? k.substring(CACHE_PREFIX_LENGTH + 1, k.indexOf(']', CACHE_PREFIX_LENGTH)) : k.substring(CACHE_PREFIX_LENGTH, k.indexOf('.', CACHE_PREFIX_LENGTH + 1)) ).collect(Collectors.toSet()); for (String cacheName : cachesNames) { this.remoteCache(cacheName).withProperties(typed); } statistics.withProperties(properties); if (typed.containsKey(ConfigurationProperties.TRANSPORT_FACTORY)) { this.transportFactory = Util.getInstance(typed.getProperty(ConfigurationProperties.TRANSPORT_FACTORY), classLoader.get()); } if (typed.containsKey(ConfigurationProperties.TRACING_PROPAGATION_ENABLED)) { this.tracingPropagationEnabled = typed.getBooleanProperty(ConfigurationProperties.TRACING_PROPAGATION_ENABLED, ConfigurationProperties.DEFAULT_TRACING_PROPAGATION_ENABLED); } return this; } private void parseClusterProperties(TypedProperties properties) { Map<String, ClusterConfigurationBuilder> builders = new HashMap<>(); properties.forEach((k, v) -> { assert k instanceof String; String key = (String) k; if (!key.startsWith(ConfigurationProperties.CLUSTER_PROPERTIES_PREFIX)) { // not a cluster property return; } assert v instanceof String; String value = (String) v; Matcher intelligenceMatcher = ConfigurationProperties.CLUSTER_PROPERTIES_PREFIX_INTELLIGENCE_REGEX.matcher(key); if (intelligenceMatcher.matches()) { String clusterName = intelligenceMatcher.replaceFirst(""); builders.computeIfAbsent(clusterName, this::addCluster).clusterClientIntelligence(ClientIntelligence.valueOf(value.toUpperCase())); return; } String clusterName = ConfigurationProperties.CLUSTER_PROPERTIES_PREFIX_REGEX.matcher(key).replaceFirst(""); ClusterConfigurationBuilder builder = builders.computeIfAbsent(clusterName, this::addCluster); parseServers(StringPropertyReplacer.replaceProperties(value), builder::addClusterNode); }); } @Override public void validate() { connectionPool.validate(); asyncExecutorFactory.validate(); security.validate(); nearCache.validate(); transaction.validate(); statistics.validate(); if (maxRetries < 0) { throw HOTROD.invalidMaxRetries(maxRetries); } Set<String> clusterNameSet = new HashSet<>(clusters.size()); for (ClusterConfigurationBuilder clusterConfigBuilder : clusters) { if (!clusterNameSet.add(clusterConfigBuilder.getClusterName())) { throw HOTROD.duplicateClusterDefinition(clusterConfigBuilder.getClusterName()); } clusterConfigBuilder.validate(); } } @Override public Configuration create() { List<ServerConfiguration> servers = new ArrayList<>(); if (this.servers.size() > 0) for (ServerConfigurationBuilder server : this.servers) { servers.add(server.create()); } else { servers.add(new ServerConfiguration("127.0.0.1", ConfigurationProperties.DEFAULT_HOTROD_PORT)); } List<ClusterConfiguration> serverClusterConfigs = clusters.stream() .map(ClusterConfigurationBuilder::create).collect(Collectors.toList()); Marshaller buildMarshaller = this.marshaller; if (buildMarshaller == null && marshallerClass == null) { buildMarshaller = handleNullMarshaller(); } Class<? extends Marshaller> buildMarshallerClass = this.marshallerClass; if (buildMarshallerClass == null) { // Populate the marshaller class as well, so it can be exported to properties buildMarshallerClass = buildMarshaller.getClass(); } else { if (buildMarshaller != null && !buildMarshallerClass.isInstance(buildMarshaller)) throw new IllegalArgumentException("Both marshaller and marshallerClass attributes are present, but marshaller is not an instance of marshallerClass"); } Map<String, RemoteCacheConfiguration> remoteCaches = remoteCacheBuilders.entrySet().stream().collect(Collectors.toMap( Map.Entry::getKey, e -> e.getValue().create())); return new Configuration(asyncExecutorFactory.create(), balancingStrategyFactory, classLoader == null ? null : classLoader.get(), clientIntelligence, connectionPool.create(), connectionTimeout, consistentHashImpl, dnsResolverMinTTL, dnsResolverMaxTTL, dnsResolverNegativeTTL, forceReturnValues, keySizeEstimate, buildMarshaller, buildMarshallerClass, protocolVersion, servers, socketTimeout, security.create(), tcpNoDelay, tcpKeepAlive, valueSizeEstimate, maxRetries, nearCache.create(), serverClusterConfigs, allowListRegExs, batchSize, transaction.create(), statistics.create(), features, contextInitializers, remoteCaches, transportFactory, tracingPropagationEnabled); } // Method that handles default marshaller - needed as a placeholder private Marshaller handleNullMarshaller() { return new ProtoStreamMarshaller(); } @Override public Configuration build() { features = new Features(classLoader.get()); return build(true); } public Configuration build(boolean validate) { if (validate) { validate(); } return create(); } @Override public ConfigurationBuilder read(Configuration template, Combine combine) { this.classLoader = new WeakReference<>(template.classLoader()); this.asyncExecutorFactory.read(template.asyncExecutorFactory(), combine); this.balancingStrategyFactory = template.balancingStrategyFactory(); this.connectionPool.read(template.connectionPool(), combine); this.connectionTimeout = template.connectionTimeout(); for (int i = 0; i < consistentHashImpl.length; i++) { this.consistentHashImpl[i] = template.consistentHashImpl(i + 1); } this.dnsResolverMinTTL = template.dnsResolverMinTTL(); this.dnsResolverMaxTTL = template.dnsResolverMaxTTL(); this.dnsResolverNegativeTTL = template.dnsResolverNegativeTTL(); this.forceReturnValues = template.forceReturnValues(); this.keySizeEstimate = template.keySizeEstimate(); this.marshaller = template.marshaller(); this.marshallerClass = template.marshallerClass(); this.protocolVersion = template.version(); this.servers.clear(); for (ServerConfiguration server : template.servers()) { this.addServer().host(server.host()).port(server.port()); } this.clusters.clear(); template.clusters().forEach(cluster -> this.addCluster(cluster.getClusterName()).read(cluster, combine)); this.socketTimeout = template.socketTimeout(); this.security.read(template.security(), combine); this.tcpNoDelay = template.tcpNoDelay(); this.tcpKeepAlive = template.tcpKeepAlive(); this.transportFactory = template.transportFactory(); this.valueSizeEstimate = template.valueSizeEstimate(); this.maxRetries = template.maxRetries(); this.nearCache.read(template.nearCache(), combine); this.allowListRegExs.addAll(template.serialWhitelist()); this.transaction.read(template.transaction(), combine); this.statistics.read(template.statistics(), combine); this.contextInitializers.clear(); this.contextInitializers.addAll(template.getContextInitializers()); this.clientIntelligence = template.clientIntelligence(); return this; } }
29,359
40.293952
166
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/RemoteCacheConfiguration.java
package org.infinispan.client.hotrod.configuration; import org.infinispan.client.hotrod.near.DefaultNearCacheFactory; import org.infinispan.client.hotrod.near.NearCacheFactory; import org.infinispan.client.hotrod.transaction.lookup.GenericTransactionManagerLookup; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @BuiltBy(RemoteCacheConfigurationBuilder.class) public class RemoteCacheConfiguration { public static final AttributeDefinition<String> CONFIGURATION = AttributeDefinition.builder("configuration", null, String.class).build(); public static final AttributeDefinition<Boolean> FORCE_RETURN_VALUES = AttributeDefinition.builder("force-return-values", false, Boolean.class).build(); public static final AttributeDefinition<String> NAME = AttributeDefinition.builder("name", null, String.class).build(); public static final AttributeDefinition<NearCacheMode> NEAR_CACHE_MODE = AttributeDefinition.builder("near-cache-mode", NearCacheMode.DISABLED).build(); public static final AttributeDefinition<Integer> NEAR_CACHE_MAX_ENTRIES = AttributeDefinition.builder("near-cache-max-entries", -1).build(); public static final AttributeDefinition<Boolean> NEAR_CACHE_BLOOM_FILTER = AttributeDefinition.builder("near-cache-bloom-filter", false).build(); public static final AttributeDefinition<NearCacheFactory> NEAR_CACHE_FACTORY = AttributeDefinition.builder("near-cache-factory", DefaultNearCacheFactory.INSTANCE, NearCacheFactory.class).build(); public static final AttributeDefinition<String> TEMPLATE_NAME = AttributeDefinition.builder("template-name", null, String.class).build(); public static final AttributeDefinition<TransactionMode> TRANSACTION_MODE = AttributeDefinition.builder("transaction-mode", TransactionMode.NONE).build(); public static final AttributeDefinition<TransactionManagerLookup> TRANSACTION_MANAGER = AttributeDefinition.builder("transaction-manager", GenericTransactionManagerLookup.getInstance(), TransactionManagerLookup.class).build(); public static final AttributeDefinition<Marshaller> MARSHALLER = AttributeDefinition.builder("marshaller", null, Marshaller.class).build(); public static final AttributeDefinition<Class> MARSHALLER_CLASS = AttributeDefinition.builder("marshallerClass", null, Class.class).build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(RemoteCacheConfiguration.class, CONFIGURATION, FORCE_RETURN_VALUES, NAME, MARSHALLER, MARSHALLER_CLASS, NEAR_CACHE_MODE, NEAR_CACHE_MAX_ENTRIES, NEAR_CACHE_BLOOM_FILTER, NEAR_CACHE_FACTORY, TEMPLATE_NAME, TRANSACTION_MODE, TRANSACTION_MANAGER); } private final Attribute<String> configuration; private final Attribute<Boolean> forceReturnValues; private final Attribute<Marshaller> marshaller; private final Attribute<Class> marshallerClass; private final Attribute<String> name; private final Attribute<NearCacheMode> nearCacheMode; private final Attribute<Integer> nearCacheMaxEntries; private final Attribute<Boolean> nearCacheBloomFilter; private final Attribute<String> templateName; private final Attribute<TransactionMode> transactionMode; private final Attribute<TransactionManagerLookup> transactionManager; private final AttributeSet attributes; RemoteCacheConfiguration(AttributeSet attributes) { this.attributes = attributes.checkProtection(); configuration = attributes.attribute(CONFIGURATION); forceReturnValues = attributes.attribute(FORCE_RETURN_VALUES); name = attributes.attribute(NAME); marshaller = attributes.attribute(MARSHALLER); marshallerClass = attributes.attribute(MARSHALLER_CLASS); nearCacheMode = attributes.attribute(NEAR_CACHE_MODE); nearCacheMaxEntries = attributes.attribute(NEAR_CACHE_MAX_ENTRIES); nearCacheBloomFilter = attributes.attribute(NEAR_CACHE_BLOOM_FILTER); templateName = attributes.attribute(TEMPLATE_NAME); transactionMode = attributes.attribute(TRANSACTION_MODE); transactionManager = attributes.attribute(TRANSACTION_MANAGER); } public String configuration() { return configuration.get(); } public boolean forceReturnValues() { return forceReturnValues.get(); } public String name() { return name.get(); } public Marshaller marshaller() { return marshaller.get(); } public Class<? extends Marshaller> marshallerClass() { return marshallerClass.get(); } public NearCacheMode nearCacheMode() { return nearCacheMode.get(); } public int nearCacheMaxEntries() { return nearCacheMaxEntries.get(); } public boolean nearCacheBloomFilter() { return nearCacheBloomFilter.get(); } public NearCacheFactory nearCacheFactory() { return attributes.attribute(NEAR_CACHE_FACTORY).get(); } public String templateName() { return templateName.get(); } public TransactionMode transactionMode() { return transactionMode.get(); } public TransactionManagerLookup transactionManagerLookup() { return transactionManager.get(); } AttributeSet attributes() { return attributes; } @Override public String toString() { return "RemoteCacheConfiguration [attributes=" + attributes + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RemoteCacheConfiguration other = (RemoteCacheConfiguration) obj; if (attributes == null) { if (other.attributes != null) return false; } else if (!attributes.equals(other.attributes)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((attributes == null) ? 0 : attributes.hashCode()); return result; } }
6,377
42.684932
274
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/SecurityConfiguration.java
package org.infinispan.client.hotrod.configuration; /** * SecurityConfiguration. * * @author Tristan Tarrant * @since 7.0 */ public class SecurityConfiguration { private final AuthenticationConfiguration authentication; private final SslConfiguration ssl; SecurityConfiguration(AuthenticationConfiguration authentication, SslConfiguration ssl) { this.authentication = authentication; this.ssl = ssl; } public AuthenticationConfiguration authentication() { return authentication; } public SslConfiguration ssl() { return ssl; } }
588
20.035714
92
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/TransactionMode.java
package org.infinispan.client.hotrod.configuration; import jakarta.transaction.Synchronization; import jakarta.transaction.Transaction; import javax.transaction.xa.XAResource; import org.infinispan.client.hotrod.RemoteCache; /** * Specifies how the {@link RemoteCache} is enlisted in the {@link Transaction}. * * If {@link #NONE} is used, the {@link RemoteCache} won't be transactional. * * @author Pedro Ruivo * @since 9.3 */ public enum TransactionMode { /** * The cache is not transactional */ NONE, /** * The cache is enlisted as {@link Synchronization}. */ NON_XA, /** * The cache is enlisted as {@link XAResource} but it doesn't keep any recovery information. */ NON_DURABLE_XA, /** * The cache is enlisted as{@link XAResource} with recovery support. * * This mode isn't available yet. */ FULL_XA }
879
22.783784
95
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/AbstractConfigurationChildBuilder.java
package org.infinispan.client.hotrod.configuration; import java.net.URI; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.TransportFactory; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.protostream.SerializationContextInitializer; /** * AbstractConfigurationChildBuilder. * * @author Tristan Tarrant * @since 5.3 */ public abstract class AbstractConfigurationChildBuilder implements ConfigurationChildBuilder { final ConfigurationBuilder builder; protected AbstractConfigurationChildBuilder(ConfigurationBuilder builder) { this.builder = builder; } @Override public ServerConfigurationBuilder addServer() { return builder.addServer(); } @Override public ClusterConfigurationBuilder addCluster(String clusterName) { return builder.addCluster(clusterName); } @Override public ConfigurationBuilder addServers(String servers) { return builder.addServers(servers); } @Override public ExecutorFactoryConfigurationBuilder asyncExecutorFactory() { return builder.asyncExecutorFactory(); } @Override public ConfigurationBuilder balancingStrategy(String balancingStrategy) { return builder.balancingStrategy(balancingStrategy); } @Override public ConfigurationBuilder balancingStrategy(Class<? extends FailoverRequestBalancingStrategy> balancingStrategy) { return builder.balancingStrategy(balancingStrategy); } @Override public ConfigurationBuilder balancingStrategy(Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory) { return builder.balancingStrategy(balancingStrategyFactory); } @Override public ConfigurationBuilder classLoader(ClassLoader classLoader) { return builder.classLoader(classLoader); } @Override public ConfigurationBuilder clientIntelligence(ClientIntelligence clientIntelligence) { return builder.clientIntelligence(clientIntelligence); } @Override public ConnectionPoolConfigurationBuilder connectionPool() { return builder.connectionPool(); } @Override public ConfigurationBuilder connectionTimeout(int connectionTimeout) { return builder.connectionTimeout(connectionTimeout); } @Override public ConfigurationBuilder consistentHashImpl(int version, Class<? extends ConsistentHash> consistentHashClass) { return builder.consistentHashImpl(version, consistentHashClass); } @Override public ConfigurationBuilder consistentHashImpl(int version, String consistentHashClass) { return builder.consistentHashImpl(version, consistentHashClass); } @Override public ConfigurationBuilder dnsResolverMinTTL(int minTTL) { return builder.dnsResolverMinTTL(minTTL); } @Override public ConfigurationBuilder dnsResolverMaxTTL(int maxTTL) { return builder.dnsResolverMaxTTL(maxTTL); } @Override public ConfigurationBuilder dnsResolverNegativeTTL(int negativeTTL) { return builder.dnsResolverNegativeTTL(negativeTTL); } @Override public ConfigurationBuilder forceReturnValues(boolean forceReturnValues) { return builder.forceReturnValues(forceReturnValues); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated @Override public ConfigurationBuilder keySizeEstimate(int keySizeEstimate) { return builder.keySizeEstimate(keySizeEstimate); } @Override public ConfigurationBuilder marshaller(String marshaller) { return builder.marshaller(marshaller); } @Override public ConfigurationBuilder marshaller(Class<? extends Marshaller> marshaller) { return builder.marshaller(marshaller); } @Override public ConfigurationBuilder marshaller(Marshaller marshaller) { return builder.marshaller(marshaller); } @Override public ConfigurationBuilder addContextInitializer(String contextInitializer) { return builder.addContextInitializer(contextInitializer); } @Override public ConfigurationBuilder addContextInitializer(SerializationContextInitializer contextInitializer) { return builder.addContextInitializer(contextInitializer); } @Override public ConfigurationBuilder addContextInitializers(SerializationContextInitializer... contextInitializers) { return builder.addContextInitializers(contextInitializers); } /** * @deprecated Use {@link #version(ProtocolVersion)} instead. */ @Deprecated @Override public ConfigurationBuilder protocolVersion(String protocolVersion) { return builder.version(ProtocolVersion.parseVersion(protocolVersion)); } @Override public ConfigurationBuilder version(ProtocolVersion protocolVersion) { return builder.version(protocolVersion); } @Override public ConfigurationBuilder socketTimeout(int socketTimeout) { return builder.socketTimeout(socketTimeout); } @Override public SecurityConfigurationBuilder security() { return builder.security(); } @Override public ConfigurationBuilder tcpNoDelay(boolean tcpNoDelay) { return builder.tcpNoDelay(tcpNoDelay); } @Override public ConfigurationBuilder tcpKeepAlive(boolean tcpKeepAlive) { return builder.tcpKeepAlive(tcpKeepAlive); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated @Override public ConfigurationBuilder valueSizeEstimate(int valueSizeEstimate) { return builder.valueSizeEstimate(valueSizeEstimate); } @Override public ConfigurationBuilder maxRetries(int retriesPerServer) { return builder.maxRetries(retriesPerServer); } @Override public ConfigurationBuilder addJavaSerialAllowList(String... regExs) { return builder.addJavaSerialAllowList(regExs); } @Override @Deprecated public ConfigurationBuilder addJavaSerialWhiteList(String... regExs) { return builder.addJavaSerialAllowList(regExs); } @Override public ConfigurationBuilder batchSize(int batchSize) { return builder.batchSize(batchSize); } @Override public StatisticsConfigurationBuilder statistics() { return builder.statistics(); } @Override public TransactionConfigurationBuilder transaction() { return builder.transaction(); } @Override public RemoteCacheConfigurationBuilder remoteCache(String name) { return builder.remoteCache(name); } @Override public ConfigurationBuilder transactionTimeout(long timeout, TimeUnit timeUnit) { return builder.transactionTimeout(timeout, timeUnit); } @Override public ConfigurationBuilder transportFactory(TransportFactory transportFactory) { return builder.transportFactory(transportFactory); } @Override public ConfigurationBuilder uri(URI uri) { return builder.uri(uri); } @Override public ConfigurationBuilder uri(String uri) { return builder.uri(uri); } @Override public ConfigurationBuilder withProperties(Properties properties) { return builder.withProperties(properties); } @Override public Configuration build() { return builder.build(); } }
7,497
27.618321
119
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/AuthenticationConfiguration.java
package org.infinispan.client.hotrod.configuration; import java.util.Map; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; /** * AuthenticationConfiguration. * * @author Tristan Tarrant * @since 7.0 */ public class AuthenticationConfiguration { private final boolean enabled; private final CallbackHandler callbackHandler; private final Subject clientSubject; private final String saslMechanism; private final Map<String, String> saslProperties; private final String serverName; public AuthenticationConfiguration(CallbackHandler callbackHandler, Subject clientSubject, boolean enabled, String saslMechanism, Map<String, String> saslProperties, String serverName) { this.enabled = enabled; this.callbackHandler = callbackHandler; this.clientSubject = clientSubject; this.saslMechanism = saslMechanism; this.saslProperties = saslProperties; this.serverName = serverName; } public CallbackHandler callbackHandler() { return callbackHandler; } public boolean enabled() { return enabled; } public String saslMechanism() { return saslMechanism; } public Map<String, String> saslProperties() { return saslProperties; } public String serverName() { return serverName; } public Subject clientSubject() { return clientSubject; } }
1,410
24.196429
189
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ConnectionPoolConfiguration.java
package org.infinispan.client.hotrod.configuration; /** * ConnectionPoolConfiguration. * * @author Tristan Tarrant * @since 5.3 */ public class ConnectionPoolConfiguration { private final ExhaustedAction exhaustedAction; private final int maxActive; private final long maxWait; private final int minIdle; private final long minEvictableIdleTime; private final int maxPendingRequests; ConnectionPoolConfiguration(ExhaustedAction exhaustedAction, int maxActive, long maxWait, int minIdle, long minEvictableIdleTime, int maxPendingRequests) { this.exhaustedAction = exhaustedAction; this.maxActive = maxActive; this.maxWait = maxWait; this.minIdle = minIdle; this.minEvictableIdleTime = minEvictableIdleTime; this.maxPendingRequests = maxPendingRequests; } public ExhaustedAction exhaustedAction() { return exhaustedAction; } public int maxActive() { return maxActive; } public long maxWait() { return maxWait; } public int minIdle() { return minIdle; } public long minEvictableIdleTime() { return minEvictableIdleTime; } public int maxPendingRequests() { return maxPendingRequests; } @Override public String toString() { return "ConnectionPoolConfiguration{" + "exhaustedAction=" + exhaustedAction + ", maxActive=" + maxActive + ", maxWait=" + maxWait + ", minIdle=" + minIdle + ", minEvictableIdleTime=" + minEvictableIdleTime + ", maxPendingRequests=" + maxPendingRequests + '}'; } }
1,629
25.290323
158
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/NearCacheConfiguration.java
package org.infinispan.client.hotrod.configuration; import java.util.regex.Pattern; import org.infinispan.client.hotrod.near.DefaultNearCacheFactory; import org.infinispan.client.hotrod.near.NearCacheFactory; public class NearCacheConfiguration { // TODO: Consider an option to configure key equivalence function for near cache (e.g. for byte arrays) private final NearCacheMode mode; private final int maxEntries; private final boolean bloomFilter; private final Pattern cacheNamePattern; private final NearCacheFactory nearCacheFactory; public NearCacheConfiguration(NearCacheMode mode, int maxEntries, boolean bloomFilterOptimization) { this(mode, maxEntries, bloomFilterOptimization, null, DefaultNearCacheFactory.INSTANCE); } public NearCacheConfiguration(NearCacheMode mode, int maxEntries, boolean bloomFilter, Pattern cacheNamePattern, NearCacheFactory nearCacheFactory) { this.mode = mode; this.maxEntries = maxEntries; this.bloomFilter = bloomFilter; this.cacheNamePattern = cacheNamePattern; this.nearCacheFactory = nearCacheFactory; } public int maxEntries() { return maxEntries; } public NearCacheMode mode() { return mode; } public boolean bloomFilter() { return bloomFilter; } @Deprecated public Pattern cacheNamePattern() { return cacheNamePattern; } public NearCacheFactory nearCacheFactory() { return nearCacheFactory; } @Override public String toString() { return "NearCacheConfiguration{" + "mode=" + mode + ", maxEntries=" + maxEntries + ", bloomFilter=" + bloomFilter + ", cacheNamePattern=" + cacheNamePattern + ", nearCacheFactory=" + nearCacheFactory + '}'; } }
1,814
29.25
152
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/Configuration.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.ASYNC_EXECUTOR_FACTORY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.AUTH_CALLBACK_HANDLER; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.AUTH_CLIENT_SUBJECT; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.AUTH_SERVER_NAME; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.BATCH_SIZE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CACHE_CONFIGURATION_SUFFIX; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CACHE_MARSHALLER; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CACHE_NEAR_CACHE_MODE_SUFFIX; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CACHE_PREFIX; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CACHE_TEMPLATE_NAME_SUFFIX; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CLIENT_INTELLIGENCE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_EXHAUSTED_ACTION; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MAX_ACTIVE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MAX_PENDING_REQUESTS; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MAX_WAIT; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MIN_IDLE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECT_TIMEOUT; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONTEXT_INITIALIZERS; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.DEFAULT_EXECUTOR_FACTORY_POOL_SIZE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.DNS_RESOLVER_MAX_TTL; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.DNS_RESOLVER_MIN_TTL; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.DNS_RESOLVER_NEGATIVE_TTL; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.FORCE_RETURN_VALUES; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.HASH_FUNCTION_PREFIX; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.JAVA_SERIAL_ALLOWLIST; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_SIZE_ESTIMATE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_STORE_CERTIFICATE_PASSWORD; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_STORE_FILE_NAME; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_STORE_PASSWORD; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.MARSHALLER; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.MAX_RETRIES; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_MAX_ENTRIES; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_MODE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_NAME_PATTERN; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.PROTOCOL_VERSION; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.REQUEST_BALANCING_STRATEGY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SASL_MECHANISM; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SASL_PROPERTIES_PREFIX; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SERVER_LIST; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SNI_HOST_NAME; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SO_TIMEOUT; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SSL_CONTEXT; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SSL_PROTOCOL; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.STATISTICS; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_KEEP_ALIVE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_NO_DELAY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TRUST_STORE_FILE_NAME; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TRUST_STORE_PASSWORD; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.USE_AUTH; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.USE_SSL; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.VALUE_SIZE_ESTIMATE; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.TransportFactory; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.util.Features; import org.infinispan.commons.util.TypedProperties; import org.infinispan.protostream.SerializationContextInitializer; /** * Configuration. * * @author Tristan Tarrant * @since 5.3 */ @BuiltBy(ConfigurationBuilder.class) public class Configuration { private final ExecutorFactoryConfiguration asyncExecutorFactory; private final Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory; private final WeakReference<ClassLoader> classLoader; private final ClientIntelligence clientIntelligence; private final ConnectionPoolConfiguration connectionPool; private final int connectionTimeout; private final Class<? extends ConsistentHash>[] consistentHashImpl; private final boolean forceReturnValues; private final int keySizeEstimate; private final Class<? extends Marshaller> marshallerClass; private final Marshaller marshaller; private final ProtocolVersion protocolVersion; private final List<ServerConfiguration> servers; private final int socketTimeout; private final SecurityConfiguration security; private final boolean tcpNoDelay; private final boolean tcpKeepAlive; private final int valueSizeEstimate; private final int maxRetries; private final NearCacheConfiguration nearCache; private final List<ClusterConfiguration> clusters; private final List<String> serialAllowList; private final int batchSize; private final ClassAllowList classAllowList; private final StatisticsConfiguration statistics; @Deprecated private final TransactionConfiguration transaction; private final Features features; private final List<SerializationContextInitializer> contextInitializers; private final Map<String, RemoteCacheConfiguration> remoteCaches; private final TransportFactory transportFactory; private final boolean tracingPropagationEnabled; private final int dnsResolverMinTTL; private final int dnsResolverMaxTTL; private final int dnsResolverNegativeTTL; public Configuration(ExecutorFactoryConfiguration asyncExecutorFactory, Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory, ClassLoader classLoader, ClientIntelligence clientIntelligence, ConnectionPoolConfiguration connectionPool, int connectionTimeout, Class<? extends ConsistentHash>[] consistentHashImpl, int dnsResolverMinTTL, int dnsResolverMaxTTL, int dnsResolverNegativeTTL, boolean forceReturnValues, int keySizeEstimate, Marshaller marshaller, Class<? extends Marshaller> marshallerClass, ProtocolVersion protocolVersion, List<ServerConfiguration> servers, int socketTimeout, SecurityConfiguration security, boolean tcpNoDelay, boolean tcpKeepAlive, int valueSizeEstimate, int maxRetries, NearCacheConfiguration nearCache, List<ClusterConfiguration> clusters, List<String> serialAllowList, int batchSize, TransactionConfiguration transaction, StatisticsConfiguration statistics, Features features, List<SerializationContextInitializer> contextInitializers, Map<String, RemoteCacheConfiguration> remoteCaches, TransportFactory transportFactory, boolean tracingPropagationEnabled) { this.asyncExecutorFactory = asyncExecutorFactory; this.balancingStrategyFactory = balancingStrategyFactory; this.maxRetries = maxRetries; this.classLoader = new WeakReference<>(classLoader); this.clientIntelligence = clientIntelligence; this.connectionPool = connectionPool; this.connectionTimeout = connectionTimeout; this.consistentHashImpl = consistentHashImpl; this.dnsResolverMinTTL = dnsResolverMinTTL; this.dnsResolverMaxTTL = dnsResolverMaxTTL; this.dnsResolverNegativeTTL = dnsResolverNegativeTTL; this.forceReturnValues = forceReturnValues; this.keySizeEstimate = keySizeEstimate; this.marshallerClass = marshallerClass; this.marshaller = marshaller; this.protocolVersion = protocolVersion; this.servers = Collections.unmodifiableList(servers); this.socketTimeout = socketTimeout; this.security = security; this.tcpNoDelay = tcpNoDelay; this.tcpKeepAlive = tcpKeepAlive; this.valueSizeEstimate = valueSizeEstimate; this.nearCache = nearCache; this.clusters = clusters; this.serialAllowList = serialAllowList; this.classAllowList = new ClassAllowList(serialAllowList); this.batchSize = batchSize; this.transaction = transaction; this.statistics = statistics; this.features = features; this.contextInitializers = contextInitializers; this.remoteCaches = remoteCaches; this.transportFactory = transportFactory; this.tracingPropagationEnabled = tracingPropagationEnabled; } public ExecutorFactoryConfiguration asyncExecutorFactory() { return asyncExecutorFactory; } public Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory() { return balancingStrategyFactory; } @Deprecated public ClassLoader classLoader() { return classLoader.get(); } public ClientIntelligence clientIntelligence() { return clientIntelligence; } public ConnectionPoolConfiguration connectionPool() { return connectionPool; } public int connectionTimeout() { return connectionTimeout; } public Class<? extends ConsistentHash>[] consistentHashImpl() { return Arrays.copyOf(consistentHashImpl, consistentHashImpl.length); } public Class<? extends ConsistentHash> consistentHashImpl(int version) { return consistentHashImpl[version - 1]; } public int dnsResolverMinTTL() { return dnsResolverMinTTL; } public int dnsResolverMaxTTL() { return dnsResolverMaxTTL; } public int dnsResolverNegativeTTL() { return dnsResolverNegativeTTL; } public boolean forceReturnValues() { return forceReturnValues; } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public int keySizeEstimate() { return keySizeEstimate; } public Marshaller marshaller() { return marshaller; } public Class<? extends Marshaller> marshallerClass() { return marshallerClass; } @Deprecated public NearCacheConfiguration nearCache() { return nearCache; } public ProtocolVersion version() { return protocolVersion; } public List<ServerConfiguration> servers() { return servers; } public List<ClusterConfiguration> clusters() { return clusters; } public int socketTimeout() { return socketTimeout; } public SecurityConfiguration security() { return security; } public boolean tcpNoDelay() { return tcpNoDelay; } public boolean tcpKeepAlive() { return tcpKeepAlive; } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public int valueSizeEstimate() { return valueSizeEstimate; } public int maxRetries() { return maxRetries; } /** * @deprecated Use {@link #serialAllowList()} instead. To be removed in 14.0. */ @Deprecated public List<String> serialWhitelist() { return serialAllowList(); } public List<String> serialAllowList() { return serialAllowList; } /** * @deprecated Use {@link #getClassAllowList()} instead. To be removed in 14.0. */ @Deprecated public ClassAllowList getClassWhiteList() { return getClassAllowList(); } public ClassAllowList getClassAllowList() { return classAllowList; } public int batchSize() { return batchSize; } public Map<String, RemoteCacheConfiguration> remoteCaches() { return Collections.unmodifiableMap(remoteCaches); } /** * Create a new {@link RemoteCacheConfiguration}. This can be used to create additional configurations after a {@link org.infinispan.client.hotrod.RemoteCacheManager} has been initialized. * * @param name the name of the cache configuration to create * @param builderConsumer a {@link Consumer} which receives a {@link RemoteCacheConfigurationBuilder} and can apply the necessary configurations on it. * @return the {@link RemoteCacheConfiguration} * @throws IllegalArgumentException if a cache configuration with the same name already exists */ public RemoteCacheConfiguration addRemoteCache(String name, Consumer<RemoteCacheConfigurationBuilder> builderConsumer) { synchronized (remoteCaches) { if (remoteCaches.containsKey(name)) { throw Log.HOTROD.duplicateCacheConfiguration(name); } else { RemoteCacheConfigurationBuilder builder = new RemoteCacheConfigurationBuilder(null, name); builderConsumer.accept(builder); builder.validate(); RemoteCacheConfiguration configuration = builder.create(); remoteCaches.put(name, configuration); return configuration; } } } /** * Remove a {@link RemoteCacheConfiguration} from this {@link Configuration}. If the cache configuration doesn't exist, this method has no effect. * @param name the name of the {@link RemoteCacheConfiguration} to remove. */ public void removeRemoteCache(String name) { remoteCaches.remove(name); } public StatisticsConfiguration statistics() { return statistics; } /** * @deprecated since 12.0. To be removed in Infinispan 14. */ @Deprecated public TransactionConfiguration transaction() { return transaction; } /** * see {@link ConfigurationBuilder#transactionTimeout(long, TimeUnit)}, */ public long transactionTimeout() { //TODO replace with field in this class then TransactionConfiguration is removed. return transaction.timeout(); } public Features features() { return features; } public List<SerializationContextInitializer> getContextInitializers() { return contextInitializers; } public TransportFactory transportFactory() { return transportFactory; } /** * OpenTelemetry tracing propagation will be activated if this property is true * and if the OpenTelemetry API jar is detected on the classpath. * By default, the property is true. * * @return if the tracing propagation is enabled */ public boolean tracingPropagationEnabled() { return tracingPropagationEnabled; } @Override public String toString() { return "Configuration [asyncExecutorFactory=" + asyncExecutorFactory + ", balancingStrategyFactory=()->" + balancingStrategyFactory.get() + ",classLoader=" + classLoader + ", clientIntelligence=" + clientIntelligence + ", connectionPool=" + connectionPool + ", connectionTimeout=" + connectionTimeout + ", consistentHashImpl=" + Arrays.toString(consistentHashImpl) + ", forceReturnValues=" + forceReturnValues + ", keySizeEstimate=" + keySizeEstimate + ", marshallerClass=" + marshallerClass + ", marshaller=" + marshaller + ", protocolVersion=" + protocolVersion + ", servers=" + servers + ", socketTimeout=" + socketTimeout + ", security=" + security + ", tcpNoDelay=" + tcpNoDelay + ", tcpKeepAlive=" + tcpKeepAlive + ", valueSizeEstimate=" + valueSizeEstimate + ", maxRetries=" + maxRetries + ", serialAllowList=" + serialAllowList + ", batchSize=" + batchSize + ", nearCache=" + nearCache + ", remoteCaches= " + remoteCaches + ", transaction=" + transaction + ", statistics=" + statistics + "]"; } public Properties properties() { TypedProperties properties = new TypedProperties(); if (asyncExecutorFactory().factoryClass() != null) { properties.setProperty(ASYNC_EXECUTOR_FACTORY, asyncExecutorFactory().factoryClass().getName()); TypedProperties aefProps = asyncExecutorFactory().properties(); for (String key : Arrays.asList(DEFAULT_EXECUTOR_FACTORY_POOL_SIZE)) { if (aefProps.containsKey(key)) { properties.setProperty(key, aefProps.getProperty(key)); } } } properties.setProperty(REQUEST_BALANCING_STRATEGY, balancingStrategyFactory().get().getClass().getName()); properties.setProperty(CLIENT_INTELLIGENCE, clientIntelligence().name()); properties.setProperty(CONNECT_TIMEOUT, Integer.toString(connectionTimeout())); for (int i = 0; i < consistentHashImpl().length; i++) { int version = i + 1; if (consistentHashImpl(version) != null) { properties.setProperty(HASH_FUNCTION_PREFIX + "." + version, consistentHashImpl(version).getName()); } } properties.setProperty(FORCE_RETURN_VALUES, forceReturnValues()); properties.setProperty(KEY_SIZE_ESTIMATE, keySizeEstimate()); properties.setProperty(MARSHALLER, marshallerClass().getName()); properties.setProperty(PROTOCOL_VERSION, version().toString()); properties.setProperty(SO_TIMEOUT, socketTimeout()); properties.setProperty(TCP_NO_DELAY, tcpNoDelay()); properties.setProperty(TCP_KEEP_ALIVE, tcpKeepAlive()); properties.setProperty(VALUE_SIZE_ESTIMATE, valueSizeEstimate()); properties.setProperty(MAX_RETRIES, maxRetries()); properties.setProperty(STATISTICS, statistics().enabled()); properties.setProperty(DNS_RESOLVER_MIN_TTL, dnsResolverMinTTL); properties.setProperty(DNS_RESOLVER_MAX_TTL, dnsResolverMaxTTL); properties.setProperty(DNS_RESOLVER_NEGATIVE_TTL, dnsResolverNegativeTTL); properties.setProperty(CONNECTION_POOL_EXHAUSTED_ACTION, connectionPool().exhaustedAction().name()); properties.setProperty("exhaustedAction", connectionPool().exhaustedAction().ordinal()); properties.setProperty(CONNECTION_POOL_MAX_ACTIVE, connectionPool().maxActive()); properties.setProperty("maxActive", connectionPool().maxActive()); properties.setProperty(CONNECTION_POOL_MAX_WAIT, connectionPool().maxWait()); properties.setProperty("maxWait", connectionPool().maxWait()); properties.setProperty(CONNECTION_POOL_MIN_IDLE, connectionPool().minIdle()); properties.setProperty("minIdle", connectionPool().minIdle()); properties.setProperty(CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME, connectionPool().minEvictableIdleTime()); properties.setProperty("minEvictableIdleTimeMillis", connectionPool().minEvictableIdleTime()); properties.setProperty(CONNECTION_POOL_MAX_PENDING_REQUESTS, connectionPool().maxPendingRequests()); StringBuilder servers = new StringBuilder(); for (ServerConfiguration server : servers()) { if (servers.length() > 0) { servers.append(";"); } servers.append(server.host()).append(":").append(server.port()); } properties.setProperty(SERVER_LIST, servers.toString()); properties.setProperty(USE_SSL, Boolean.toString(security.ssl().enabled())); if (security.ssl().keyStoreFileName() != null) properties.setProperty(KEY_STORE_FILE_NAME, security.ssl().keyStoreFileName()); if (security.ssl().keyStorePassword() != null) properties.setProperty(KEY_STORE_PASSWORD, new String(security.ssl().keyStorePassword())); if (security.ssl().keyStoreCertificatePassword() != null) properties.setProperty(KEY_STORE_CERTIFICATE_PASSWORD, new String(security.ssl().keyStoreCertificatePassword())); if (security.ssl().trustStoreFileName() != null) properties.setProperty(TRUST_STORE_FILE_NAME, security.ssl().trustStoreFileName()); if (security.ssl().trustStorePassword() != null) properties.setProperty(TRUST_STORE_PASSWORD, new String(security.ssl().trustStorePassword())); if (security.ssl().sniHostName() != null) properties.setProperty(SNI_HOST_NAME, security.ssl().sniHostName()); if (security.ssl().protocol() != null) properties.setProperty(SSL_PROTOCOL, security.ssl().protocol()); if (security.ssl().sslContext() != null) properties.put(SSL_CONTEXT, security.ssl().sslContext()); properties.setProperty(USE_AUTH, Boolean.toString(security.authentication().enabled())); if (security.authentication().saslMechanism() != null) properties.setProperty(SASL_MECHANISM, security.authentication().saslMechanism()); if (security.authentication().callbackHandler() != null) properties.put(AUTH_CALLBACK_HANDLER, security.authentication().callbackHandler()); if (security.authentication().serverName() != null) properties.setProperty(AUTH_SERVER_NAME, security.authentication().serverName()); if (security.authentication().clientSubject() != null) properties.put(AUTH_CLIENT_SUBJECT, security.authentication().clientSubject()); for (Map.Entry<String, String> entry : security.authentication().saslProperties().entrySet()) properties.setProperty(SASL_PROPERTIES_PREFIX + '.' + entry.getKey(), entry.getValue()); properties.setProperty(JAVA_SERIAL_ALLOWLIST, String.join(",", serialAllowList)); properties.setProperty(BATCH_SIZE, Integer.toString(batchSize)); transaction.toProperties(properties); properties.setProperty(NEAR_CACHE_MODE, nearCache.mode().name()); properties.setProperty(NEAR_CACHE_MAX_ENTRIES, Integer.toString(nearCache.maxEntries())); if (nearCache.cacheNamePattern() != null) properties.setProperty(NEAR_CACHE_NAME_PATTERN, nearCache.cacheNamePattern().pattern()); if (contextInitializers != null && !contextInitializers.isEmpty()) properties.setProperty(CONTEXT_INITIALIZERS, contextInitializers.stream().map(sci -> sci.getClass().getName()).collect(Collectors.joining(","))); for (RemoteCacheConfiguration remoteCache : remoteCaches.values()) { String prefix = CACHE_PREFIX + remoteCache.name(); if (remoteCache.templateName() != null) { properties.setProperty(prefix + CACHE_TEMPLATE_NAME_SUFFIX, remoteCache.templateName()); } if (remoteCache.configuration() != null) { properties.setProperty(prefix + CACHE_CONFIGURATION_SUFFIX, remoteCache.configuration()); } properties.setProperty(prefix + CACHE_NEAR_CACHE_MODE_SUFFIX, remoteCache.nearCacheMode().name()); properties.setProperty(prefix + CACHE_NEAR_CACHE_MODE_SUFFIX, remoteCache.nearCacheMaxEntries()); Marshaller marshaller = remoteCache.marshaller(); if (marshaller != null) { properties.setProperty(prefix + CACHE_MARSHALLER, remoteCache.marshaller().getClass().getName()); } else { Class<? extends Marshaller> marshallerClass = remoteCache.marshallerClass(); if(marshallerClass != null) { properties.setProperty(prefix + CACHE_MARSHALLER, marshallerClass.getName()); } } } return properties; } }
25,038
45.112339
191
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/TransactionConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TRANSACTION_MANAGER_LOOKUP; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TRANSACTION_MODE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TRANSACTION_TIMEOUT; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import static org.infinispan.commons.util.Util.getInstance; import static org.infinispan.commons.util.Util.loadClass; import java.util.Properties; import java.util.concurrent.TimeUnit; import jakarta.transaction.Synchronization; import jakarta.transaction.TransactionManager; import javax.transaction.xa.XAResource; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.transaction.lookup.GenericTransactionManagerLookup; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import org.infinispan.commons.util.TypedProperties; /** * Configures a transactional {@link RemoteCache}. * * @author Pedro Ruivo * @since 9.3 * @deprecated since 12.0. To be removed in Infinispan 14. */ @Deprecated public class TransactionConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<TransactionConfiguration> { public static final long DEFAULT_TIMEOUT = 60000; private TransactionMode transactionMode = TransactionMode.NONE; private TransactionManagerLookup transactionManagerLookup = defaultTransactionManagerLookup(); private long timeout = DEFAULT_TIMEOUT; TransactionConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } public static TransactionManagerLookup defaultTransactionManagerLookup() { return GenericTransactionManagerLookup.getInstance(); } /** * The {@link TransactionManagerLookup} to lookup for the {@link TransactionManager} to interact with. * @deprecated since 12.0. To be removed in Infinispan 14. Use {@link RemoteCacheConfigurationBuilder#transactionManagerLookup(TransactionManagerLookup)} */ @Deprecated public TransactionConfigurationBuilder transactionManagerLookup(TransactionManagerLookup transactionManagerLookup) { this.transactionManagerLookup = transactionManagerLookup; return this; } /** * The {@link TransactionMode} in which a {@link RemoteCache} will be enlisted. * @deprecated since 12.0. To be removed in Infinispan 14. Use {@link RemoteCacheConfigurationBuilder#transactionMode(TransactionMode)} */ @Deprecated public TransactionConfigurationBuilder transactionMode(TransactionMode transactionMode) { this.transactionMode = transactionMode; return this; } /** * Sets the transaction's timeout. * <p> * This timeout is used by the server to rollback unrecoverable transaction when they are idle for this amount of * time. * <p> * An unrecoverable transaction are transaction enlisted as {@link Synchronization} ({@link TransactionMode#NON_XA}) * or {@link XAResource} without recovery enabled ({@link TransactionMode#NON_DURABLE_XA}). * <p> * For {@link XAResource}, this value is overwritten by {@link XAResource#setTransactionTimeout(int)}. * <p> * It defaults to 1 minute. * @deprecated since 12.0. To be removed in Infinispan 14. Use {@link ConfigurationBuilder#transactionTimeout(long, TimeUnit)} */ @Deprecated public TransactionConfigurationBuilder timeout(long timeout, TimeUnit timeUnit) { setTimeoutMillis(timeUnit.toMillis(timeout)); return this; } @Override public void validate() { if (transactionMode == null) { throw HOTROD.invalidTransactionMode(); } if (transactionManagerLookup == null) { throw HOTROD.invalidTransactionManagerLookup(); } if (timeout <= 0) { throw HOTROD.invalidTransactionTimeout(); } } @Override public TransactionConfiguration create() { return new TransactionConfiguration(transactionMode, transactionManagerLookup, timeout); } @Override public Builder<?> read(TransactionConfiguration template, Combine combine) { this.transactionManagerLookup = template.transactionManagerLookup(); this.transactionMode = template.transactionMode(); this.timeout = template.timeout(); return this; } void withTransactionProperties(Properties properties) { TypedProperties typed = TypedProperties.toTypedProperties(properties); transactionMode(typed.getEnumProperty(TRANSACTION_MODE, TransactionMode.class, transactionMode, true)); transactionManagerLookup(tlmFromString(typed.getProperty(TRANSACTION_MANAGER_LOOKUP, tlmClass(), true))); setTimeoutMillis(typed.getLongProperty(TRANSACTION_TIMEOUT, timeout, true)); } private TransactionManagerLookup tlmFromString(String lookupClass) { return lookupClass == null || tlmClass().equals(lookupClass) ? transactionManagerLookup : getInstance(loadClass(lookupClass, builder.classLoader())); } private String tlmClass() { return transactionManagerLookup.getClass().getName(); } private void setTimeoutMillis(long timeout) { this.timeout = timeout; } }
5,523
37.901408
156
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/StatisticsConfiguration.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.commons.configuration.attributes.IdentityAttributeCopier.identityCopier; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.PlatformMBeanServerLookup; import org.infinispan.commons.util.Util; /** * @author Tristan Tarrant * @since 9.4 */ public class StatisticsConfiguration { public static final AttributeDefinition<Boolean> ENABLED = AttributeDefinition.builder("enabled", false).immutable().build(); public static final AttributeDefinition<Boolean> JMX_ENABLED = AttributeDefinition.builder("jmx_enabled", false).immutable().build(); public static final AttributeDefinition<String> JMX_DOMAIN = AttributeDefinition.builder("jmx_domain", "org.infinispan").immutable().build(); public static final AttributeDefinition<MBeanServerLookup> MBEAN_SERVER_LOOKUP = AttributeDefinition.builder("mbeanserverlookup", (MBeanServerLookup) Util.getInstance(PlatformMBeanServerLookup.class)) .copier(identityCopier()).immutable().build(); public static final AttributeDefinition<String> JMX_NAME = AttributeDefinition.builder("jmx_name", "Default").immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(StatisticsConfiguration.class, ENABLED, JMX_ENABLED, JMX_DOMAIN, MBEAN_SERVER_LOOKUP, JMX_NAME); } private final Attribute<Boolean> enabled; private final Attribute<Boolean> jmxEnabled; private final Attribute<String> jmxDomain; private final Attribute<String> jmxName; private final Attribute<MBeanServerLookup> mBeanServerLookup; private final AttributeSet attributes; StatisticsConfiguration(AttributeSet attributes) { this.attributes = attributes.checkProtection(); this.enabled = attributes.attribute(ENABLED); this.jmxEnabled = attributes.attribute(JMX_ENABLED); this.jmxDomain = attributes.attribute(JMX_DOMAIN); this.jmxName = attributes.attribute(JMX_NAME); this.mBeanServerLookup = attributes.attribute(MBEAN_SERVER_LOOKUP); } public AttributeSet attributes() { return attributes; } public boolean enabled() { return enabled.get(); } public boolean jmxEnabled() { return jmxEnabled.get(); } public String jmxDomain() { return jmxDomain.get(); } public MBeanServerLookup mbeanServerLookup() { return mBeanServerLookup.get(); } public String jmxName() { return jmxName.get(); } @Override public String toString() { return attributes.toString(StatisticsConfiguration.class.getSimpleName()); } }
2,858
38.164384
203
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/NearCacheConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.Properties; import java.util.regex.Pattern; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.near.DefaultNearCacheFactory; import org.infinispan.client.hotrod.near.NearCacheFactory; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.TypedProperties; public class NearCacheConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<NearCacheConfiguration> { private NearCacheMode mode = NearCacheMode.DISABLED; private Integer maxEntries = null; // undefined private Pattern cacheNamePattern = null; // matches all private boolean bloomFilter = false; private NearCacheFactory nearCacheFactory = DefaultNearCacheFactory.INSTANCE; protected NearCacheConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } /** * Specifies the maximum number of entries that will be held in the near cache. * * @param maxEntries maximum entries in the near cache. * @return an instance of the builder */ public NearCacheConfigurationBuilder maxEntries(int maxEntries) { this.maxEntries = maxEntries; return this; } /** * Specifies whether bloom filter should be used for near cache to limit the number of write * notifications for unrelated keys. * @param enable whether to enable bloom filter * @return an instance of this builder */ public NearCacheConfigurationBuilder bloomFilter(boolean enable) { this.bloomFilter = enable; return this; } /** * Specifies the near caching mode. See {@link NearCacheMode} for details on the available modes. * * @param mode one of {@link NearCacheMode} * @return an instance of the builder */ public NearCacheConfigurationBuilder mode(NearCacheMode mode) { this.mode = mode; return this; } /** * Specifies a cache name pattern (in the form of a regular expression) that matches all cache names for which * near caching should be enabled. See the {@link Pattern} syntax for details on the format. * * @param pattern a regular expression. * @return an instance of the builder * @deprecated use {@link RemoteCacheConfigurationBuilder#nearCacheMode(NearCacheMode)} to enable near-caching per-cache */ @Deprecated public NearCacheConfigurationBuilder cacheNamePattern(String pattern) { this.cacheNamePattern = Pattern.compile(pattern); return this; } /** * Specifies a cache name pattern that matches all cache names for which near caching should be enabled. * * @param pattern a {@link Pattern} * @return an instance of the builder * @deprecated use {@link RemoteCacheConfigurationBuilder#nearCacheMode(NearCacheMode)} to enable near-caching per-cache */ @Deprecated public NearCacheConfigurationBuilder cacheNamePattern(Pattern pattern) { this.cacheNamePattern = pattern; return this; } /** * Specifies a {@link NearCacheFactory} which is responsible for creating {@link org.infinispan.client.hotrod.near.NearCache} instances. * * @param factory a {@link NearCacheFactory} * @return an instance of the builder */ public NearCacheConfigurationBuilder nearCacheFactory(NearCacheFactory factory) { this.nearCacheFactory = factory; return this; } @Override public void validate() { if (mode.enabled()) { if (maxEntries == null) { throw HOTROD.nearCacheMaxEntriesUndefined(); } else if (maxEntries < 0 && bloomFilter) { throw HOTROD.nearCacheMaxEntriesPositiveWithBloom(maxEntries); } if (bloomFilter) { int maxActive = connectionPool().maxActive(); ExhaustedAction exhaustedAction = connectionPool().exhaustedAction(); if (maxActive != 1 || exhaustedAction != ExhaustedAction.WAIT) { throw HOTROD.bloomFilterRequiresMaxActiveOneAndWait(maxEntries, exhaustedAction); } } } } @Override public NearCacheConfiguration create() { return new NearCacheConfiguration(mode, maxEntries == null ? -1 : maxEntries, bloomFilter, cacheNamePattern, nearCacheFactory); } @Override public Builder<?> read(NearCacheConfiguration template, Combine combine) { mode = template.mode(); maxEntries = template.maxEntries(); bloomFilter = template.bloomFilter(); cacheNamePattern = template.cacheNamePattern(); nearCacheFactory = template.nearCacheFactory(); return this; } @Override public ConfigurationBuilder withProperties(Properties properties) { TypedProperties typed = TypedProperties.toTypedProperties(properties); if (typed.containsKey(ConfigurationProperties.NEAR_CACHE_MAX_ENTRIES)) { this.maxEntries(typed.getIntProperty(ConfigurationProperties.NEAR_CACHE_MAX_ENTRIES, -1)); } if (typed.containsKey(ConfigurationProperties.NEAR_CACHE_MODE)) { this.mode(NearCacheMode.valueOf(typed.getProperty(ConfigurationProperties.NEAR_CACHE_MODE))); } if (typed.containsKey(ConfigurationProperties.NEAR_CACHE_BLOOM_FILTER)) { this.bloomFilter(typed.getBooleanProperty(ConfigurationProperties.NEAR_CACHE_BLOOM_FILTER, false)); } if (typed.containsKey(ConfigurationProperties.NEAR_CACHE_NAME_PATTERN)) { this.cacheNamePattern(typed.getProperty(ConfigurationProperties.NEAR_CACHE_NAME_PATTERN)); } return builder; } }
5,903
36.605096
139
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ExhaustedAction.java
package org.infinispan.client.hotrod.configuration; /** * Enumeration for whenExhaustedAction. Order is important, as the underlying commons-pool uses a byte to represent values * ExhaustedAction. * * @author Tristan Tarrant * @since 5.3 */ public enum ExhaustedAction { EXCEPTION, // GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL WAIT, // GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK CREATE_NEW // GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW }
456
29.466667
122
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/SaslQop.java
package org.infinispan.client.hotrod.configuration; /** * SaslQop. Possible values for the SASL QOP property * * @author Tristan Tarrant * @since 7.0 */ public enum SaslQop { AUTH("auth"), AUTH_INT("auth-int"), AUTH_CONF("auth-conf"); private String v; SaslQop(String v) { this.v = v; } @Override public String toString() { return v; } }
381
14.916667
62
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ConnectionPoolConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import java.util.Properties; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.TypedProperties; /** * ConnectionPoolConfigurationBuilder. Specifies connection pooling properties for the HotRod client. * * @author Tristan Tarrant * @since 5.3 */ public class ConnectionPoolConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<ConnectionPoolConfiguration> { private ExhaustedAction exhaustedAction = ExhaustedAction.WAIT; private int maxActive = ConfigurationProperties.DEFAULT_MAX_ACTIVE; private long maxWait = ConfigurationProperties.DEFAULT_MAX_WAIT; private int minIdle = ConfigurationProperties.DEFAULT_MIN_IDLE; private long minEvictableIdleTime = ConfigurationProperties.DEFAULT_MIN_EVICTABLE_IDLE_TIME; private int maxPendingRequests = ConfigurationProperties.DEFAULT_MAX_PENDING_REQUESTS; ConnectionPoolConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } /** * Specifies what happens when asking for a connection from a server's pool, and that pool is * exhausted. */ public ConnectionPoolConfigurationBuilder exhaustedAction(ExhaustedAction exhaustedAction) { this.exhaustedAction = exhaustedAction; return this; } /** * Returns the configured action when the pool has become exhausted. * @return the action to perform */ public ExhaustedAction exhaustedAction() { return exhaustedAction; } /** * Controls the maximum number of connections per server that are allocated (checked out to * client threads, or idle in the pool) at one time. When non-positive, there is no limit to the * number of connections per server. When maxActive is reached, the connection pool for that * server is said to be exhausted. The default setting for this parameter is -1, i.e. there is no * limit. */ public ConnectionPoolConfigurationBuilder maxActive(int maxActive) { this.maxActive = maxActive; return this; } /** * Returns the number of configured maximum connections per server that can be allocated. When this is non-positive * there is no limit to the number of connections. * @return maximum number of open connections to a server */ public int maxActive() { return maxActive; } /** * The amount of time in milliseconds to wait for a connection to become available when the * exhausted action is {@link ExhaustedAction#WAIT}, after which a {@link java.util.NoSuchElementException} * will be thrown. If a negative value is supplied, the pool will block indefinitely. */ public ConnectionPoolConfigurationBuilder maxWait(long maxWait) { this.maxWait = maxWait; return this; } /** * Sets a target value for the minimum number of idle connections (per server) that should always * be available. If this parameter is set to a positive number and timeBetweenEvictionRunsMillis * &gt; 0, each time the idle connection eviction thread runs, it will try to create enough idle * instances so that there will be minIdle idle instances available for each server. The default * setting for this parameter is 1. */ public ConnectionPoolConfigurationBuilder minIdle(int minIdle) { this.minIdle = minIdle; return this; } /** * Specifies the minimum amount of time that an connection may sit idle in the pool before it is * eligible for eviction due to idle time. When non-positive, no connection will be dropped from * the pool due to idle time alone. This setting has no effect unless * timeBetweenEvictionRunsMillis &gt; 0. Defaults to {@link ConfigurationProperties#DEFAULT_MIN_EVICTABLE_IDLE_TIME} */ public ConnectionPoolConfigurationBuilder minEvictableIdleTime(long minEvictableIdleTime) { this.minEvictableIdleTime = minEvictableIdleTime; return this; } /** * Specifies maximum number of requests sent over single connection at one instant. * Connections with more concurrent requests will be ignored in the pool when choosing available connection * and the pool will try to create a new connection if all connections are utilized. Only if the new connection * cannot be created and the {@link #exhaustedAction(ExhaustedAction) exhausted action} * is set to {@link ExhaustedAction#WAIT} the pool will allow sending the request over one of the over-utilized * connections. * The rule of thumb is that this should be set to higher values if the values are small (&lt; 1kB) and to lower values * if the entries are big (&gt; 10kB). * Default setting for this parameter is 5. */ public ConnectionPoolConfigurationBuilder maxPendingRequests(int maxPendingRequests) { this.maxPendingRequests = maxPendingRequests; return this; } /** * Configures the connection pool parameter according to properties */ public ConnectionPoolConfigurationBuilder withPoolProperties(Properties properties) { TypedProperties typed = TypedProperties.toTypedProperties(properties); exhaustedAction(typed.getEnumProperty(ConfigurationProperties.CONNECTION_POOL_EXHAUSTED_ACTION, ExhaustedAction.class, ExhaustedAction.values()[typed.getIntProperty("whenExhaustedAction", exhaustedAction.ordinal(), true)], true)); maxActive(typed.getIntProperty(ConfigurationProperties.CONNECTION_POOL_MAX_ACTIVE, typed.getIntProperty("maxActive", maxActive, true), true)); maxWait(typed.getLongProperty(ConfigurationProperties.CONNECTION_POOL_MAX_WAIT, typed.getLongProperty("maxWait", maxWait, true), true)); minIdle(typed.getIntProperty(ConfigurationProperties.CONNECTION_POOL_MIN_IDLE, typed.getIntProperty("minIdle", minIdle, true), true)); minEvictableIdleTime(typed.getLongProperty(ConfigurationProperties.CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME, typed.getLongProperty("minEvictableIdleTimeMillis", minEvictableIdleTime, true), true)); maxPendingRequests(typed.getIntProperty(ConfigurationProperties.CONNECTION_POOL_MAX_PENDING_REQUESTS, typed.getIntProperty("maxPendingRequests", maxPendingRequests, true), true)); return this; } @Override public ConnectionPoolConfiguration create() { return new ConnectionPoolConfiguration(exhaustedAction, maxActive, maxWait, minIdle, minEvictableIdleTime, maxPendingRequests); } @Override public ConnectionPoolConfigurationBuilder read(ConnectionPoolConfiguration template, Combine combine) { exhaustedAction = template.exhaustedAction(); maxActive = template.maxActive(); maxWait = template.maxWait(); minIdle = template.minIdle(); minEvictableIdleTime = template.minEvictableIdleTime(); maxPendingRequests = template.maxPendingRequests(); return this; } }
7,320
43.369697
139
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ServerConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * ServerConfigurationBuilder. * * @author Tristan Tarrant * @since 5.3 */ public class ServerConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<ServerConfiguration> { private String host; private int port = 11222; ServerConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } public ServerConfigurationBuilder host(String host) { this.host = host; return this; } public ServerConfigurationBuilder port(int port) { this.port = port; return this; } @Override public void validate() { if (host == null || host.isEmpty()) { throw HOTROD.missingHostDefinition(); } } @Override public ServerConfiguration create() { return new ServerConfiguration(host, port); } @Override public ServerConfigurationBuilder read(ServerConfiguration template, Combine combine) { this.host = template.host(); this.port = template.port(); return this; } }
1,402
22.383333
123
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ClusterConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * @since 8.1 */ public class ClusterConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<ClusterConfiguration> { private final List<ServerConfigurationBuilder> servers = new ArrayList<>(); private final String clusterName; private ClientIntelligence intelligence; protected ClusterConfigurationBuilder(ConfigurationBuilder builder, String clusterName) { super(builder); this.clusterName = clusterName; } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } public String getClusterName() { return clusterName; } public ClusterConfigurationBuilder addClusterNode(String host, int port) { ServerConfigurationBuilder serverBuilder = new ServerConfigurationBuilder(builder); servers.add(serverBuilder.host(host).port(port)); return this; } public ClusterConfigurationBuilder addClusterNodes(String serverList) { ConfigurationBuilder.parseServers(serverList, (host, port) -> { ServerConfigurationBuilder serverBuilder = new ServerConfigurationBuilder(builder); servers.add(serverBuilder.host(host).port(port)); }); return this; } public ClusterConfigurationBuilder clusterClientIntelligence(ClientIntelligence intelligence) { // null is valid, means using the global intelligence (for backwards compatibility) this.intelligence = intelligence; return this; } @Override public void validate() { if (clusterName == null || clusterName.isEmpty()) { throw HOTROD.missingClusterNameDefinition(); } if (servers.isEmpty()) { throw HOTROD.missingClusterServersDefinition(clusterName); } for (ServerConfigurationBuilder serverConfigBuilder : servers) { serverConfigBuilder.validate(); } } @Override public ClusterConfiguration create() { List<ServerConfiguration> serverCluster = servers.stream() .map(ServerConfigurationBuilder::create).collect(Collectors.toList()); return new ClusterConfiguration(serverCluster, clusterName, intelligence); } @Override public Builder<?> read(ClusterConfiguration template, Combine combine) { template.getCluster().forEach(server -> this.addClusterNode(server.host(), server.port())); clusterClientIntelligence(template.getClientIntelligence()); return this; } }
2,804
32.795181
125
java