+ *
* Protobuf type {@code wso2.discovery.config.enforcer.ThrottleAgent}
*/
public final class ThrottleAgent extends
@@ -740,6 +744,10 @@ protected Builder newBuilderForType(
return builder;
}
/**
+ *
+ * Throttle Agent configuration model
+ *
+ *
* Protobuf type {@code wso2.discovery.config.enforcer.ThrottleAgent}
*/
public static final class Builder extends
diff --git a/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlePublisher.java b/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlePublisher.java
index 7aa75bfb7a..aa9d880e02 100644
--- a/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlePublisher.java
+++ b/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlePublisher.java
@@ -4,6 +4,10 @@
package org.wso2.gateway.discovery.config.enforcer;
/**
+ *
+ * Throttle Publisher configuration model
+ *
+ *
* Protobuf type {@code wso2.discovery.config.enforcer.ThrottlePublisher}
*/
public final class ThrottlePublisher extends
@@ -360,6 +364,10 @@ protected Builder newBuilderForType(
return builder;
}
/**
+ *
+ * Throttle Publisher configuration model
+ *
+ *
* Protobuf type {@code wso2.discovery.config.enforcer.ThrottlePublisher}
*/
public static final class Builder extends
diff --git a/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/Throttling.java b/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/Throttling.java
index 9bb4ef40c0..8bb7c1b95b 100644
--- a/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/Throttling.java
+++ b/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/Throttling.java
@@ -20,6 +20,8 @@ private Throttling(com.google.protobuf.GeneratedMessageV3.Builder> builder) {
super(builder);
}
private Throttling() {
+ jmsConnectionInitialContextFactory_ = "";
+ jmsConnectionProviderUrl_ = "";
}
@java.lang.Override
@@ -52,15 +54,47 @@ private Throttling(
case 0:
done = true;
break;
- case 10: {
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.Builder subBuilder = null;
- if (binary_ != null) {
- subBuilder = binary_.toBuilder();
+ case 8: {
+
+ enableGlobalEventPublishing_ = input.readBool();
+ break;
+ }
+ case 16: {
+
+ enableHeaderConditions_ = input.readBool();
+ break;
+ }
+ case 24: {
+
+ enableQueryParamConditions_ = input.readBool();
+ break;
+ }
+ case 32: {
+
+ enableJwtClaimConditions_ = input.readBool();
+ break;
+ }
+ case 42: {
+ java.lang.String s = input.readStringRequireUtf8();
+
+ jmsConnectionInitialContextFactory_ = s;
+ break;
+ }
+ case 50: {
+ java.lang.String s = input.readStringRequireUtf8();
+
+ jmsConnectionProviderUrl_ = s;
+ break;
+ }
+ case 58: {
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.Builder subBuilder = null;
+ if (publisher_ != null) {
+ subBuilder = publisher_.toBuilder();
}
- binary_ = input.readMessage(org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.parser(), extensionRegistry);
+ publisher_ = input.readMessage(org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.parser(), extensionRegistry);
if (subBuilder != null) {
- subBuilder.mergeFrom(binary_);
- binary_ = subBuilder.buildPartial();
+ subBuilder.mergeFrom(publisher_);
+ publisher_ = subBuilder.buildPartial();
}
break;
@@ -97,30 +131,150 @@ private Throttling(
org.wso2.gateway.discovery.config.enforcer.Throttling.class, org.wso2.gateway.discovery.config.enforcer.Throttling.Builder.class);
}
- public static final int BINARY_FIELD_NUMBER = 1;
- private org.wso2.gateway.discovery.config.enforcer.BinaryThrottling binary_;
+ public static final int ENABLE_GLOBAL_EVENT_PUBLISHING_FIELD_NUMBER = 1;
+ private boolean enableGlobalEventPublishing_;
+ /**
+ * bool enable_global_event_publishing = 1;
+ * @return The enableGlobalEventPublishing.
+ */
+ @java.lang.Override
+ public boolean getEnableGlobalEventPublishing() {
+ return enableGlobalEventPublishing_;
+ }
+
+ public static final int ENABLE_HEADER_CONDITIONS_FIELD_NUMBER = 2;
+ private boolean enableHeaderConditions_;
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
- * @return Whether the binary field is set.
+ * bool enable_header_conditions = 2;
+ * @return The enableHeaderConditions.
*/
@java.lang.Override
- public boolean hasBinary() {
- return binary_ != null;
+ public boolean getEnableHeaderConditions() {
+ return enableHeaderConditions_;
}
+
+ public static final int ENABLE_QUERY_PARAM_CONDITIONS_FIELD_NUMBER = 3;
+ private boolean enableQueryParamConditions_;
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
- * @return The binary.
+ * bool enable_query_param_conditions = 3;
+ * @return The enableQueryParamConditions.
*/
@java.lang.Override
- public org.wso2.gateway.discovery.config.enforcer.BinaryThrottling getBinary() {
- return binary_ == null ? org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.getDefaultInstance() : binary_;
+ public boolean getEnableQueryParamConditions() {
+ return enableQueryParamConditions_;
}
+
+ public static final int ENABLE_JWT_CLAIM_CONDITIONS_FIELD_NUMBER = 4;
+ private boolean enableJwtClaimConditions_;
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
+ * bool enable_jwt_claim_conditions = 4;
+ * @return The enableJwtClaimConditions.
*/
@java.lang.Override
- public org.wso2.gateway.discovery.config.enforcer.BinaryThrottlingOrBuilder getBinaryOrBuilder() {
- return getBinary();
+ public boolean getEnableJwtClaimConditions() {
+ return enableJwtClaimConditions_;
+ }
+
+ public static final int JMS_CONNECTION_INITIAL_CONTEXT_FACTORY_FIELD_NUMBER = 5;
+ private volatile java.lang.Object jmsConnectionInitialContextFactory_;
+ /**
+ * string jms_connection_initial_context_factory = 5;
+ * @return The jmsConnectionInitialContextFactory.
+ */
+ @java.lang.Override
+ public java.lang.String getJmsConnectionInitialContextFactory() {
+ java.lang.Object ref = jmsConnectionInitialContextFactory_;
+ if (ref instanceof java.lang.String) {
+ return (java.lang.String) ref;
+ } else {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ jmsConnectionInitialContextFactory_ = s;
+ return s;
+ }
+ }
+ /**
+ * string jms_connection_initial_context_factory = 5;
+ * @return The bytes for jmsConnectionInitialContextFactory.
+ */
+ @java.lang.Override
+ public com.google.protobuf.ByteString
+ getJmsConnectionInitialContextFactoryBytes() {
+ java.lang.Object ref = jmsConnectionInitialContextFactory_;
+ if (ref instanceof java.lang.String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ jmsConnectionInitialContextFactory_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+
+ public static final int JMS_CONNECTION_PROVIDER_URL_FIELD_NUMBER = 6;
+ private volatile java.lang.Object jmsConnectionProviderUrl_;
+ /**
+ * string jms_connection_provider_url = 6;
+ * @return The jmsConnectionProviderUrl.
+ */
+ @java.lang.Override
+ public java.lang.String getJmsConnectionProviderUrl() {
+ java.lang.Object ref = jmsConnectionProviderUrl_;
+ if (ref instanceof java.lang.String) {
+ return (java.lang.String) ref;
+ } else {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ jmsConnectionProviderUrl_ = s;
+ return s;
+ }
+ }
+ /**
+ * string jms_connection_provider_url = 6;
+ * @return The bytes for jmsConnectionProviderUrl.
+ */
+ @java.lang.Override
+ public com.google.protobuf.ByteString
+ getJmsConnectionProviderUrlBytes() {
+ java.lang.Object ref = jmsConnectionProviderUrl_;
+ if (ref instanceof java.lang.String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ jmsConnectionProviderUrl_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+
+ public static final int PUBLISHER_FIELD_NUMBER = 7;
+ private org.wso2.gateway.discovery.config.enforcer.BinaryPublisher publisher_;
+ /**
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
+ * @return Whether the publisher field is set.
+ */
+ @java.lang.Override
+ public boolean hasPublisher() {
+ return publisher_ != null;
+ }
+ /**
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
+ * @return The publisher.
+ */
+ @java.lang.Override
+ public org.wso2.gateway.discovery.config.enforcer.BinaryPublisher getPublisher() {
+ return publisher_ == null ? org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.getDefaultInstance() : publisher_;
+ }
+ /**
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
+ */
+ @java.lang.Override
+ public org.wso2.gateway.discovery.config.enforcer.BinaryPublisherOrBuilder getPublisherOrBuilder() {
+ return getPublisher();
}
private byte memoizedIsInitialized = -1;
@@ -137,8 +291,26 @@ public final boolean isInitialized() {
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
- if (binary_ != null) {
- output.writeMessage(1, getBinary());
+ if (enableGlobalEventPublishing_ != false) {
+ output.writeBool(1, enableGlobalEventPublishing_);
+ }
+ if (enableHeaderConditions_ != false) {
+ output.writeBool(2, enableHeaderConditions_);
+ }
+ if (enableQueryParamConditions_ != false) {
+ output.writeBool(3, enableQueryParamConditions_);
+ }
+ if (enableJwtClaimConditions_ != false) {
+ output.writeBool(4, enableJwtClaimConditions_);
+ }
+ if (!getJmsConnectionInitialContextFactoryBytes().isEmpty()) {
+ com.google.protobuf.GeneratedMessageV3.writeString(output, 5, jmsConnectionInitialContextFactory_);
+ }
+ if (!getJmsConnectionProviderUrlBytes().isEmpty()) {
+ com.google.protobuf.GeneratedMessageV3.writeString(output, 6, jmsConnectionProviderUrl_);
+ }
+ if (publisher_ != null) {
+ output.writeMessage(7, getPublisher());
}
unknownFields.writeTo(output);
}
@@ -149,9 +321,31 @@ public int getSerializedSize() {
if (size != -1) return size;
size = 0;
- if (binary_ != null) {
+ if (enableGlobalEventPublishing_ != false) {
size += com.google.protobuf.CodedOutputStream
- .computeMessageSize(1, getBinary());
+ .computeBoolSize(1, enableGlobalEventPublishing_);
+ }
+ if (enableHeaderConditions_ != false) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBoolSize(2, enableHeaderConditions_);
+ }
+ if (enableQueryParamConditions_ != false) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBoolSize(3, enableQueryParamConditions_);
+ }
+ if (enableJwtClaimConditions_ != false) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBoolSize(4, enableJwtClaimConditions_);
+ }
+ if (!getJmsConnectionInitialContextFactoryBytes().isEmpty()) {
+ size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, jmsConnectionInitialContextFactory_);
+ }
+ if (!getJmsConnectionProviderUrlBytes().isEmpty()) {
+ size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, jmsConnectionProviderUrl_);
+ }
+ if (publisher_ != null) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(7, getPublisher());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
@@ -168,10 +362,22 @@ public boolean equals(final java.lang.Object obj) {
}
org.wso2.gateway.discovery.config.enforcer.Throttling other = (org.wso2.gateway.discovery.config.enforcer.Throttling) obj;
- if (hasBinary() != other.hasBinary()) return false;
- if (hasBinary()) {
- if (!getBinary()
- .equals(other.getBinary())) return false;
+ if (getEnableGlobalEventPublishing()
+ != other.getEnableGlobalEventPublishing()) return false;
+ if (getEnableHeaderConditions()
+ != other.getEnableHeaderConditions()) return false;
+ if (getEnableQueryParamConditions()
+ != other.getEnableQueryParamConditions()) return false;
+ if (getEnableJwtClaimConditions()
+ != other.getEnableJwtClaimConditions()) return false;
+ if (!getJmsConnectionInitialContextFactory()
+ .equals(other.getJmsConnectionInitialContextFactory())) return false;
+ if (!getJmsConnectionProviderUrl()
+ .equals(other.getJmsConnectionProviderUrl())) return false;
+ if (hasPublisher() != other.hasPublisher()) return false;
+ if (hasPublisher()) {
+ if (!getPublisher()
+ .equals(other.getPublisher())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
@@ -184,9 +390,25 @@ public int hashCode() {
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
- if (hasBinary()) {
- hash = (37 * hash) + BINARY_FIELD_NUMBER;
- hash = (53 * hash) + getBinary().hashCode();
+ hash = (37 * hash) + ENABLE_GLOBAL_EVENT_PUBLISHING_FIELD_NUMBER;
+ hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
+ getEnableGlobalEventPublishing());
+ hash = (37 * hash) + ENABLE_HEADER_CONDITIONS_FIELD_NUMBER;
+ hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
+ getEnableHeaderConditions());
+ hash = (37 * hash) + ENABLE_QUERY_PARAM_CONDITIONS_FIELD_NUMBER;
+ hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
+ getEnableQueryParamConditions());
+ hash = (37 * hash) + ENABLE_JWT_CLAIM_CONDITIONS_FIELD_NUMBER;
+ hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
+ getEnableJwtClaimConditions());
+ hash = (37 * hash) + JMS_CONNECTION_INITIAL_CONTEXT_FACTORY_FIELD_NUMBER;
+ hash = (53 * hash) + getJmsConnectionInitialContextFactory().hashCode();
+ hash = (37 * hash) + JMS_CONNECTION_PROVIDER_URL_FIELD_NUMBER;
+ hash = (53 * hash) + getJmsConnectionProviderUrl().hashCode();
+ if (hasPublisher()) {
+ hash = (37 * hash) + PUBLISHER_FIELD_NUMBER;
+ hash = (53 * hash) + getPublisher().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
@@ -325,11 +547,23 @@ private void maybeForceBuilderInitialization() {
@java.lang.Override
public Builder clear() {
super.clear();
- if (binaryBuilder_ == null) {
- binary_ = null;
+ enableGlobalEventPublishing_ = false;
+
+ enableHeaderConditions_ = false;
+
+ enableQueryParamConditions_ = false;
+
+ enableJwtClaimConditions_ = false;
+
+ jmsConnectionInitialContextFactory_ = "";
+
+ jmsConnectionProviderUrl_ = "";
+
+ if (publisherBuilder_ == null) {
+ publisher_ = null;
} else {
- binary_ = null;
- binaryBuilder_ = null;
+ publisher_ = null;
+ publisherBuilder_ = null;
}
return this;
}
@@ -357,10 +591,16 @@ public org.wso2.gateway.discovery.config.enforcer.Throttling build() {
@java.lang.Override
public org.wso2.gateway.discovery.config.enforcer.Throttling buildPartial() {
org.wso2.gateway.discovery.config.enforcer.Throttling result = new org.wso2.gateway.discovery.config.enforcer.Throttling(this);
- if (binaryBuilder_ == null) {
- result.binary_ = binary_;
+ result.enableGlobalEventPublishing_ = enableGlobalEventPublishing_;
+ result.enableHeaderConditions_ = enableHeaderConditions_;
+ result.enableQueryParamConditions_ = enableQueryParamConditions_;
+ result.enableJwtClaimConditions_ = enableJwtClaimConditions_;
+ result.jmsConnectionInitialContextFactory_ = jmsConnectionInitialContextFactory_;
+ result.jmsConnectionProviderUrl_ = jmsConnectionProviderUrl_;
+ if (publisherBuilder_ == null) {
+ result.publisher_ = publisher_;
} else {
- result.binary_ = binaryBuilder_.build();
+ result.publisher_ = publisherBuilder_.build();
}
onBuilt();
return result;
@@ -410,8 +650,28 @@ public Builder mergeFrom(com.google.protobuf.Message other) {
public Builder mergeFrom(org.wso2.gateway.discovery.config.enforcer.Throttling other) {
if (other == org.wso2.gateway.discovery.config.enforcer.Throttling.getDefaultInstance()) return this;
- if (other.hasBinary()) {
- mergeBinary(other.getBinary());
+ if (other.getEnableGlobalEventPublishing() != false) {
+ setEnableGlobalEventPublishing(other.getEnableGlobalEventPublishing());
+ }
+ if (other.getEnableHeaderConditions() != false) {
+ setEnableHeaderConditions(other.getEnableHeaderConditions());
+ }
+ if (other.getEnableQueryParamConditions() != false) {
+ setEnableQueryParamConditions(other.getEnableQueryParamConditions());
+ }
+ if (other.getEnableJwtClaimConditions() != false) {
+ setEnableJwtClaimConditions(other.getEnableJwtClaimConditions());
+ }
+ if (!other.getJmsConnectionInitialContextFactory().isEmpty()) {
+ jmsConnectionInitialContextFactory_ = other.jmsConnectionInitialContextFactory_;
+ onChanged();
+ }
+ if (!other.getJmsConnectionProviderUrl().isEmpty()) {
+ jmsConnectionProviderUrl_ = other.jmsConnectionProviderUrl_;
+ onChanged();
+ }
+ if (other.hasPublisher()) {
+ mergePublisher(other.getPublisher());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
@@ -442,123 +702,399 @@ public Builder mergeFrom(
return this;
}
- private org.wso2.gateway.discovery.config.enforcer.BinaryThrottling binary_;
+ private boolean enableGlobalEventPublishing_ ;
+ /**
+ * bool enable_global_event_publishing = 1;
+ * @return The enableGlobalEventPublishing.
+ */
+ @java.lang.Override
+ public boolean getEnableGlobalEventPublishing() {
+ return enableGlobalEventPublishing_;
+ }
+ /**
+ * bool enable_global_event_publishing = 1;
+ * @param value The enableGlobalEventPublishing to set.
+ * @return This builder for chaining.
+ */
+ public Builder setEnableGlobalEventPublishing(boolean value) {
+
+ enableGlobalEventPublishing_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * bool enable_global_event_publishing = 1;
+ * @return This builder for chaining.
+ */
+ public Builder clearEnableGlobalEventPublishing() {
+
+ enableGlobalEventPublishing_ = false;
+ onChanged();
+ return this;
+ }
+
+ private boolean enableHeaderConditions_ ;
+ /**
+ * bool enable_header_conditions = 2;
+ * @return The enableHeaderConditions.
+ */
+ @java.lang.Override
+ public boolean getEnableHeaderConditions() {
+ return enableHeaderConditions_;
+ }
+ /**
+ * bool enable_header_conditions = 2;
+ * @param value The enableHeaderConditions to set.
+ * @return This builder for chaining.
+ */
+ public Builder setEnableHeaderConditions(boolean value) {
+
+ enableHeaderConditions_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * bool enable_header_conditions = 2;
+ * @return This builder for chaining.
+ */
+ public Builder clearEnableHeaderConditions() {
+
+ enableHeaderConditions_ = false;
+ onChanged();
+ return this;
+ }
+
+ private boolean enableQueryParamConditions_ ;
+ /**
+ * bool enable_query_param_conditions = 3;
+ * @return The enableQueryParamConditions.
+ */
+ @java.lang.Override
+ public boolean getEnableQueryParamConditions() {
+ return enableQueryParamConditions_;
+ }
+ /**
+ * bool enable_query_param_conditions = 3;
+ * @param value The enableQueryParamConditions to set.
+ * @return This builder for chaining.
+ */
+ public Builder setEnableQueryParamConditions(boolean value) {
+
+ enableQueryParamConditions_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * bool enable_query_param_conditions = 3;
+ * @return This builder for chaining.
+ */
+ public Builder clearEnableQueryParamConditions() {
+
+ enableQueryParamConditions_ = false;
+ onChanged();
+ return this;
+ }
+
+ private boolean enableJwtClaimConditions_ ;
+ /**
+ * bool enable_jwt_claim_conditions = 4;
+ * @return The enableJwtClaimConditions.
+ */
+ @java.lang.Override
+ public boolean getEnableJwtClaimConditions() {
+ return enableJwtClaimConditions_;
+ }
+ /**
+ * bool enable_jwt_claim_conditions = 4;
+ * @param value The enableJwtClaimConditions to set.
+ * @return This builder for chaining.
+ */
+ public Builder setEnableJwtClaimConditions(boolean value) {
+
+ enableJwtClaimConditions_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * bool enable_jwt_claim_conditions = 4;
+ * @return This builder for chaining.
+ */
+ public Builder clearEnableJwtClaimConditions() {
+
+ enableJwtClaimConditions_ = false;
+ onChanged();
+ return this;
+ }
+
+ private java.lang.Object jmsConnectionInitialContextFactory_ = "";
+ /**
+ * string jms_connection_initial_context_factory = 5;
+ * @return The jmsConnectionInitialContextFactory.
+ */
+ public java.lang.String getJmsConnectionInitialContextFactory() {
+ java.lang.Object ref = jmsConnectionInitialContextFactory_;
+ if (!(ref instanceof java.lang.String)) {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ jmsConnectionInitialContextFactory_ = s;
+ return s;
+ } else {
+ return (java.lang.String) ref;
+ }
+ }
+ /**
+ * string jms_connection_initial_context_factory = 5;
+ * @return The bytes for jmsConnectionInitialContextFactory.
+ */
+ public com.google.protobuf.ByteString
+ getJmsConnectionInitialContextFactoryBytes() {
+ java.lang.Object ref = jmsConnectionInitialContextFactory_;
+ if (ref instanceof String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ jmsConnectionInitialContextFactory_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+ /**
+ * string jms_connection_initial_context_factory = 5;
+ * @param value The jmsConnectionInitialContextFactory to set.
+ * @return This builder for chaining.
+ */
+ public Builder setJmsConnectionInitialContextFactory(
+ java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+
+ jmsConnectionInitialContextFactory_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * string jms_connection_initial_context_factory = 5;
+ * @return This builder for chaining.
+ */
+ public Builder clearJmsConnectionInitialContextFactory() {
+
+ jmsConnectionInitialContextFactory_ = getDefaultInstance().getJmsConnectionInitialContextFactory();
+ onChanged();
+ return this;
+ }
+ /**
+ * string jms_connection_initial_context_factory = 5;
+ * @param value The bytes for jmsConnectionInitialContextFactory to set.
+ * @return This builder for chaining.
+ */
+ public Builder setJmsConnectionInitialContextFactoryBytes(
+ com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ checkByteStringIsUtf8(value);
+
+ jmsConnectionInitialContextFactory_ = value;
+ onChanged();
+ return this;
+ }
+
+ private java.lang.Object jmsConnectionProviderUrl_ = "";
+ /**
+ * string jms_connection_provider_url = 6;
+ * @return The jmsConnectionProviderUrl.
+ */
+ public java.lang.String getJmsConnectionProviderUrl() {
+ java.lang.Object ref = jmsConnectionProviderUrl_;
+ if (!(ref instanceof java.lang.String)) {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ jmsConnectionProviderUrl_ = s;
+ return s;
+ } else {
+ return (java.lang.String) ref;
+ }
+ }
+ /**
+ * string jms_connection_provider_url = 6;
+ * @return The bytes for jmsConnectionProviderUrl.
+ */
+ public com.google.protobuf.ByteString
+ getJmsConnectionProviderUrlBytes() {
+ java.lang.Object ref = jmsConnectionProviderUrl_;
+ if (ref instanceof String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ jmsConnectionProviderUrl_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+ /**
+ * string jms_connection_provider_url = 6;
+ * @param value The jmsConnectionProviderUrl to set.
+ * @return This builder for chaining.
+ */
+ public Builder setJmsConnectionProviderUrl(
+ java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+
+ jmsConnectionProviderUrl_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * string jms_connection_provider_url = 6;
+ * @return This builder for chaining.
+ */
+ public Builder clearJmsConnectionProviderUrl() {
+
+ jmsConnectionProviderUrl_ = getDefaultInstance().getJmsConnectionProviderUrl();
+ onChanged();
+ return this;
+ }
+ /**
+ * string jms_connection_provider_url = 6;
+ * @param value The bytes for jmsConnectionProviderUrl to set.
+ * @return This builder for chaining.
+ */
+ public Builder setJmsConnectionProviderUrlBytes(
+ com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ checkByteStringIsUtf8(value);
+
+ jmsConnectionProviderUrl_ = value;
+ onChanged();
+ return this;
+ }
+
+ private org.wso2.gateway.discovery.config.enforcer.BinaryPublisher publisher_;
private com.google.protobuf.SingleFieldBuilderV3<
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottling, org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.Builder, org.wso2.gateway.discovery.config.enforcer.BinaryThrottlingOrBuilder> binaryBuilder_;
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisher, org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.Builder, org.wso2.gateway.discovery.config.enforcer.BinaryPublisherOrBuilder> publisherBuilder_;
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
- * @return Whether the binary field is set.
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
+ * @return Whether the publisher field is set.
*/
- public boolean hasBinary() {
- return binaryBuilder_ != null || binary_ != null;
+ public boolean hasPublisher() {
+ return publisherBuilder_ != null || publisher_ != null;
}
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
- * @return The binary.
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
+ * @return The publisher.
*/
- public org.wso2.gateway.discovery.config.enforcer.BinaryThrottling getBinary() {
- if (binaryBuilder_ == null) {
- return binary_ == null ? org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.getDefaultInstance() : binary_;
+ public org.wso2.gateway.discovery.config.enforcer.BinaryPublisher getPublisher() {
+ if (publisherBuilder_ == null) {
+ return publisher_ == null ? org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.getDefaultInstance() : publisher_;
} else {
- return binaryBuilder_.getMessage();
+ return publisherBuilder_.getMessage();
}
}
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
*/
- public Builder setBinary(org.wso2.gateway.discovery.config.enforcer.BinaryThrottling value) {
- if (binaryBuilder_ == null) {
+ public Builder setPublisher(org.wso2.gateway.discovery.config.enforcer.BinaryPublisher value) {
+ if (publisherBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
- binary_ = value;
+ publisher_ = value;
onChanged();
} else {
- binaryBuilder_.setMessage(value);
+ publisherBuilder_.setMessage(value);
}
return this;
}
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
*/
- public Builder setBinary(
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.Builder builderForValue) {
- if (binaryBuilder_ == null) {
- binary_ = builderForValue.build();
+ public Builder setPublisher(
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.Builder builderForValue) {
+ if (publisherBuilder_ == null) {
+ publisher_ = builderForValue.build();
onChanged();
} else {
- binaryBuilder_.setMessage(builderForValue.build());
+ publisherBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
*/
- public Builder mergeBinary(org.wso2.gateway.discovery.config.enforcer.BinaryThrottling value) {
- if (binaryBuilder_ == null) {
- if (binary_ != null) {
- binary_ =
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.newBuilder(binary_).mergeFrom(value).buildPartial();
+ public Builder mergePublisher(org.wso2.gateway.discovery.config.enforcer.BinaryPublisher value) {
+ if (publisherBuilder_ == null) {
+ if (publisher_ != null) {
+ publisher_ =
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.newBuilder(publisher_).mergeFrom(value).buildPartial();
} else {
- binary_ = value;
+ publisher_ = value;
}
onChanged();
} else {
- binaryBuilder_.mergeFrom(value);
+ publisherBuilder_.mergeFrom(value);
}
return this;
}
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
*/
- public Builder clearBinary() {
- if (binaryBuilder_ == null) {
- binary_ = null;
+ public Builder clearPublisher() {
+ if (publisherBuilder_ == null) {
+ publisher_ = null;
onChanged();
} else {
- binary_ = null;
- binaryBuilder_ = null;
+ publisher_ = null;
+ publisherBuilder_ = null;
}
return this;
}
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
*/
- public org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.Builder getBinaryBuilder() {
+ public org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.Builder getPublisherBuilder() {
onChanged();
- return getBinaryFieldBuilder().getBuilder();
+ return getPublisherFieldBuilder().getBuilder();
}
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
*/
- public org.wso2.gateway.discovery.config.enforcer.BinaryThrottlingOrBuilder getBinaryOrBuilder() {
- if (binaryBuilder_ != null) {
- return binaryBuilder_.getMessageOrBuilder();
+ public org.wso2.gateway.discovery.config.enforcer.BinaryPublisherOrBuilder getPublisherOrBuilder() {
+ if (publisherBuilder_ != null) {
+ return publisherBuilder_.getMessageOrBuilder();
} else {
- return binary_ == null ?
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.getDefaultInstance() : binary_;
+ return publisher_ == null ?
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.getDefaultInstance() : publisher_;
}
}
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
*/
private com.google.protobuf.SingleFieldBuilderV3<
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottling, org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.Builder, org.wso2.gateway.discovery.config.enforcer.BinaryThrottlingOrBuilder>
- getBinaryFieldBuilder() {
- if (binaryBuilder_ == null) {
- binaryBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottling, org.wso2.gateway.discovery.config.enforcer.BinaryThrottling.Builder, org.wso2.gateway.discovery.config.enforcer.BinaryThrottlingOrBuilder>(
- getBinary(),
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisher, org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.Builder, org.wso2.gateway.discovery.config.enforcer.BinaryPublisherOrBuilder>
+ getPublisherFieldBuilder() {
+ if (publisherBuilder_ == null) {
+ publisherBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisher, org.wso2.gateway.discovery.config.enforcer.BinaryPublisher.Builder, org.wso2.gateway.discovery.config.enforcer.BinaryPublisherOrBuilder>(
+ getPublisher(),
getParentForChildren(),
isClean());
- binary_ = null;
+ publisher_ = null;
}
- return binaryBuilder_;
+ return publisherBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
diff --git a/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlingOrBuilder.java b/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlingOrBuilder.java
index 1ea806dc93..47fefc7606 100644
--- a/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlingOrBuilder.java
+++ b/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlingOrBuilder.java
@@ -8,17 +8,65 @@ public interface ThrottlingOrBuilder extends
com.google.protobuf.MessageOrBuilder {
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
- * @return Whether the binary field is set.
+ * bool enable_global_event_publishing = 1;
+ * @return The enableGlobalEventPublishing.
*/
- boolean hasBinary();
+ boolean getEnableGlobalEventPublishing();
+
+ /**
+ * bool enable_header_conditions = 2;
+ * @return The enableHeaderConditions.
+ */
+ boolean getEnableHeaderConditions();
+
+ /**
+ * bool enable_query_param_conditions = 3;
+ * @return The enableQueryParamConditions.
+ */
+ boolean getEnableQueryParamConditions();
+
+ /**
+ * bool enable_jwt_claim_conditions = 4;
+ * @return The enableJwtClaimConditions.
+ */
+ boolean getEnableJwtClaimConditions();
+
+ /**
+ * string jms_connection_initial_context_factory = 5;
+ * @return The jmsConnectionInitialContextFactory.
+ */
+ java.lang.String getJmsConnectionInitialContextFactory();
+ /**
+ * string jms_connection_initial_context_factory = 5;
+ * @return The bytes for jmsConnectionInitialContextFactory.
+ */
+ com.google.protobuf.ByteString
+ getJmsConnectionInitialContextFactoryBytes();
+
+ /**
+ * string jms_connection_provider_url = 6;
+ * @return The jmsConnectionProviderUrl.
+ */
+ java.lang.String getJmsConnectionProviderUrl();
+ /**
+ * string jms_connection_provider_url = 6;
+ * @return The bytes for jmsConnectionProviderUrl.
+ */
+ com.google.protobuf.ByteString
+ getJmsConnectionProviderUrlBytes();
+
+ /**
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
+ * @return Whether the publisher field is set.
+ */
+ boolean hasPublisher();
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
- * @return The binary.
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
+ * @return The publisher.
*/
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottling getBinary();
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisher getPublisher();
/**
- * .wso2.discovery.config.enforcer.BinaryThrottling binary = 1;
+ * .wso2.discovery.config.enforcer.BinaryPublisher publisher = 7;
*/
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottlingOrBuilder getBinaryOrBuilder();
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisherOrBuilder getPublisherOrBuilder();
}
diff --git a/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlingProto.java b/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlingProto.java
index 5658b5fcd6..7fc683d5fe 100644
--- a/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlingProto.java
+++ b/enforcer/src/main/gen/org/wso2/gateway/discovery/config/enforcer/ThrottlingProto.java
@@ -30,27 +30,33 @@ public static void registerAllExtensions(
java.lang.String[] descriptorData = {
"\n/wso2/discovery/config/enforcer/throttl" +
"ing.proto\022\036wso2.discovery.config.enforce" +
- "r\0326wso2/discovery/config/enforcer/binary" +
- "_throttling.proto\"N\n\nThrottling\022@\n\006binar" +
- "y\030\001 \001(\01320.wso2.discovery.config.enforcer" +
- ".BinaryThrottlingB\217\001\n*org.wso2.gateway.d" +
- "iscovery.config.enforcerB\017ThrottlingProt" +
- "oP\001ZNgithub.com/envoyproxy/go-control-pl" +
- "ane/wso2/discovery/config/enforcer;enfor" +
- "cerb\006proto3"
+ "r\0325wso2/discovery/config/enforcer/binary" +
+ "_publisher.proto\"\273\002\n\nThrottling\022&\n\036enabl" +
+ "e_global_event_publishing\030\001 \001(\010\022 \n\030enabl" +
+ "e_header_conditions\030\002 \001(\010\022%\n\035enable_quer" +
+ "y_param_conditions\030\003 \001(\010\022#\n\033enable_jwt_c" +
+ "laim_conditions\030\004 \001(\010\022.\n&jms_connection_" +
+ "initial_context_factory\030\005 \001(\t\022#\n\033jms_con" +
+ "nection_provider_url\030\006 \001(\t\022B\n\tpublisher\030" +
+ "\007 \001(\0132/.wso2.discovery.config.enforcer.B" +
+ "inaryPublisherB\217\001\n*org.wso2.gateway.disc" +
+ "overy.config.enforcerB\017ThrottlingProtoP\001" +
+ "ZNgithub.com/envoyproxy/go-control-plane" +
+ "/wso2/discovery/config/enforcer;enforcer" +
+ "b\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottlingProto.getDescriptor(),
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisherProto.getDescriptor(),
});
internal_static_wso2_discovery_config_enforcer_Throttling_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_wso2_discovery_config_enforcer_Throttling_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_wso2_discovery_config_enforcer_Throttling_descriptor,
- new java.lang.String[] { "Binary", });
- org.wso2.gateway.discovery.config.enforcer.BinaryThrottlingProto.getDescriptor();
+ new java.lang.String[] { "EnableGlobalEventPublishing", "EnableHeaderConditions", "EnableQueryParamConditions", "EnableJwtClaimConditions", "JmsConnectionInitialContextFactory", "JmsConnectionProviderUrl", "Publisher", });
+ org.wso2.gateway.discovery.config.enforcer.BinaryPublisherProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/RequestContext.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/RequestContext.java
index 566d3b6d74..f549dee513 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/RequestContext.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/RequestContext.java
@@ -19,6 +19,7 @@
import org.apache.commons.lang3.StringUtils;
import org.wso2.micro.gateway.enforcer.api.config.ResourceConfig;
+import org.wso2.micro.gateway.enforcer.security.AuthenticationContext;
import java.util.HashMap;
import java.util.Map;
@@ -36,6 +37,9 @@ public class RequestContext {
private ResourceConfig matchedResourcePath;
private Map headers;
private Map properties = new HashMap();
+ private AuthenticationContext authenticationContext;
+ private String requestID;
+ private String address;
// Denotes the cluster header name for each environment. Both properties can be null if
// the openAPI has production endpoints alone.
private String prodClusterHeader;
@@ -60,6 +64,9 @@ public static class Builder {
private String prodClusterHeader;
private String sandClusterHeader;
private Map properties = new HashMap();
+ private AuthenticationContext authenticationContext = new AuthenticationContext();
+ private String requestID;
+ private String address;
public Builder(String requestPath) {
this.requestPath = requestPath;
@@ -99,6 +106,21 @@ public Builder sandClusterHeader(String cluster) {
return this;
}
+ public Builder authenticationContext(AuthenticationContext authenticationContext) {
+ this.authenticationContext = authenticationContext;
+ return this;
+ }
+
+ public Builder requestID(String requestID) {
+ this.requestID = requestID;
+ return this;
+ }
+
+ public Builder address(String address) {
+ this.address = address;
+ return this;
+ }
+
public RequestContext build() {
RequestContext requestContext = new RequestContext();
requestContext.matchedResourcePath = this.matchedResourceConfig;
@@ -109,6 +131,9 @@ public RequestContext build() {
requestContext.prodClusterHeader = this.prodClusterHeader;
requestContext.sandClusterHeader = this.sandClusterHeader;
requestContext.properties = this.properties;
+ requestContext.authenticationContext = this.authenticationContext;
+ requestContext.requestID = this.requestID;
+ requestContext.address = this.address;
// Adapter assigns header based routing only if both type of endpoints are present.
if (!StringUtils.isEmpty(prodClusterHeader) && !StringUtils.isEmpty(sandClusterHeader)) {
@@ -118,6 +143,18 @@ public RequestContext build() {
}
}
+ public AuthenticationContext getAuthenticationContext() {
+ return authenticationContext;
+ }
+
+ public String getRequestID() {
+ return requestID;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
public API getMathedAPI() {
return mathedAPI;
}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/RestAPI.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/RestAPI.java
index a0593d56e0..1ed1e4078d 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/RestAPI.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/RestAPI.java
@@ -25,8 +25,10 @@
import org.wso2.micro.gateway.enforcer.Filter;
import org.wso2.micro.gateway.enforcer.api.config.APIConfig;
import org.wso2.micro.gateway.enforcer.api.config.ResourceConfig;
+import org.wso2.micro.gateway.enforcer.config.ConfigHolder;
import org.wso2.micro.gateway.enforcer.constants.APIConstants;
import org.wso2.micro.gateway.enforcer.cors.CorsFilter;
+import org.wso2.micro.gateway.enforcer.filters.ThrottleFilter;
import org.wso2.micro.gateway.enforcer.security.AuthFilter;
import java.util.ArrayList;
@@ -125,10 +127,18 @@ private ResourceConfig buildResource(Operation operation, String resPath) {
private void initFilters() {
CorsFilter corsFilter = new CorsFilter();
this.filters.add(corsFilter);
+
if (!APIConstants.PROTOTYPED_LIFE_CYCLE_STATUS.equals(apiLifeCycleState)) {
AuthFilter authFilter = new AuthFilter();
authFilter.init(apiConfig);
this.filters.add(authFilter);
}
+
+ // enable throttle filter
+ if (ConfigHolder.getInstance().getConfig().getThrottleConfig().isGlobalPublishingEnabled()) {
+ ThrottleFilter throttleFilter = new ThrottleFilter();
+ throttleFilter.init(apiConfig);
+ this.filters.add(throttleFilter);
+ }
}
}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/config/APIConfig.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/config/APIConfig.java
index 8595e032a5..12b3620e63 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/config/APIConfig.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/config/APIConfig.java
@@ -17,7 +17,7 @@
*/
package org.wso2.micro.gateway.enforcer.api.config;
-import org.wso2.micro.gateway.enforcer.constants.APIConstants;
+import org.wso2.micro.gateway.enforcer.throttle.ThrottleConstants;
import java.util.ArrayList;
import java.util.List;
@@ -32,7 +32,7 @@ public class APIConfig {
private String apiLifeCycleState;
private List securitySchemas = new ArrayList<>();
- private String tier = APIConstants.UNLIMITED_TIER;
+ private String tier = ThrottleConstants.UNLIMITED_TIER;
private List resources = new ArrayList<>();
/**
@@ -46,7 +46,7 @@ public static class Builder {
private String apiLifeCycleState;
private List securitySchemas = new ArrayList<>();
- private String tier = APIConstants.UNLIMITED_TIER;
+ private String tier = ThrottleConstants.UNLIMITED_TIER;
private List resources = new ArrayList<>();
public Builder(String name) {
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/config/ResourceConfig.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/config/ResourceConfig.java
index 59322ab02a..bf94ed5886 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/config/ResourceConfig.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/api/config/ResourceConfig.java
@@ -17,7 +17,7 @@
*/
package org.wso2.micro.gateway.enforcer.api.config;
-import org.wso2.micro.gateway.enforcer.constants.APIConstants;
+import org.wso2.micro.gateway.enforcer.throttle.ThrottleConstants;
import java.util.HashMap;
import java.util.List;
@@ -32,7 +32,7 @@ public class ResourceConfig {
private String path;
private HttpMethods method;
private Map> securitySchemas = new HashMap();
- private String tier = APIConstants.UNLIMITED_TIER;
+ private String tier = ThrottleConstants.UNLIMITED_TIER;
public String getPath() {
return path;
@@ -67,7 +67,7 @@ public void setTier(String tier) {
}
/**
- * ENUM to hold http operations
+ * ENUM to hold http operations.
*/
public enum HttpMethods {
GET("get"), POST("post"), PUT("put"), DELETE("delete"), HEAD("head"),
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/common/CacheableEntity.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/common/CacheableEntity.java
index f9865478dc..d01e721ed9 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/common/CacheableEntity.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/common/CacheableEntity.java
@@ -19,7 +19,7 @@
package org.wso2.micro.gateway.enforcer.common;
/**
- * An interface to indicate that an entity provides a cacheKey
+ * An interface to indicate that an entity provides a cacheKey.
*
* @param Type of the CacheKey
*/
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/ConfigHolder.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/ConfigHolder.java
index 0ca30afea0..2872e7c653 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/ConfigHolder.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/ConfigHolder.java
@@ -26,6 +26,7 @@
import org.wso2.carbon.apimgt.common.gateway.dto.JWTConfigurationDto;
import org.wso2.gateway.discovery.config.enforcer.AmCredentials;
import org.wso2.gateway.discovery.config.enforcer.AuthService;
+import org.wso2.gateway.discovery.config.enforcer.BinaryPublisher;
import org.wso2.gateway.discovery.config.enforcer.Cache;
import org.wso2.gateway.discovery.config.enforcer.ClaimMapping;
import org.wso2.gateway.discovery.config.enforcer.Config;
@@ -33,17 +34,25 @@
import org.wso2.gateway.discovery.config.enforcer.Issuer;
import org.wso2.gateway.discovery.config.enforcer.JWTGenerator;
import org.wso2.gateway.discovery.config.enforcer.JWTIssuer;
+import org.wso2.gateway.discovery.config.enforcer.PublisherPool;
+import org.wso2.gateway.discovery.config.enforcer.TMURLGroup;
+import org.wso2.gateway.discovery.config.enforcer.ThrottleAgent;
+import org.wso2.gateway.discovery.config.enforcer.Throttling;
import org.wso2.micro.gateway.enforcer.config.dto.AuthServiceConfigurationDto;
import org.wso2.micro.gateway.enforcer.config.dto.CacheDto;
import org.wso2.micro.gateway.enforcer.config.dto.CredentialDto;
import org.wso2.micro.gateway.enforcer.config.dto.EventHubConfigurationDto;
import org.wso2.micro.gateway.enforcer.config.dto.ExtendedTokenIssuerDto;
import org.wso2.micro.gateway.enforcer.config.dto.JWTIssuerConfigurationDto;
+import org.wso2.micro.gateway.enforcer.config.dto.ThrottleAgentConfigDto;
+import org.wso2.micro.gateway.enforcer.config.dto.ThrottleConfigDto;
import org.wso2.micro.gateway.enforcer.constants.Constants;
import org.wso2.micro.gateway.enforcer.discovery.ConfigDiscoveryClient;
import org.wso2.micro.gateway.enforcer.exception.DiscoveryException;
import org.wso2.micro.gateway.enforcer.exception.MGWException;
import org.wso2.micro.gateway.enforcer.security.jwt.JWTUtil;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.conf.AgentConfiguration;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.publisher.PublisherConfiguration;
import org.wso2.micro.gateway.enforcer.util.TLSUtils;
import java.io.IOException;
@@ -119,9 +128,12 @@ private void parseConfigs(Config config) {
// Read jwt token configuration
populateJWTIssuerConfiguration(config.getJwtTokenConfigList());
- //Read credentials used to connect with APIM services
+ // Read credentials used to connect with APIM services
populateAPIMCredentials(config.getApimCredentials());
+ // Read throttle publisher configurations
+ populateThrottlingConfig(config.getThrottling());
+
// Read backend jwt generation configurations
populateJWTGeneratorConfigurations(config.getJwtGenerator());
@@ -188,7 +200,7 @@ private void populateJWTIssuerConfiguration(List cdsIssuers) {
// Load jwt transformers map.
config.setJwtTransformerMap(JWTUtil.loadJWTTransformers());
String certificateAlias = jwtIssuer.getCertificateAlias();
- if (certificateAlias != null) {
+ if (!certificateAlias.isBlank()) {
try {
Certificate cert = TLSUtils.getCertificateFromFile(jwtIssuer.getCertificateFilePath());
getTrustStoreForJWT().setCertificateEntry(certificateAlias, cert);
@@ -210,6 +222,60 @@ private void populateJWTIssuerConfiguration(List cdsIssuers) {
}
}
+ private void populateThrottlingConfig(Throttling throttling) {
+ ThrottleConfigDto throttleConfig = new ThrottleConfigDto();
+ throttleConfig.setGlobalPublishingEnabled(throttling.getEnableGlobalEventPublishing());
+ throttleConfig.setHeaderConditionsEnabled(throttling.getEnableHeaderConditions());
+ throttleConfig.setQueryConditionsEnabled(throttling.getEnableQueryParamConditions());
+ throttleConfig.setJwtClaimConditionsEnabled(throttling.getEnableJwtClaimConditions());
+ throttleConfig.setJmsConnectionInitialContextFactory(throttling.getJmsConnectionInitialContextFactory());
+ throttleConfig.setJmsConnectionProviderUrl(throttling.getJmsConnectionProviderUrl());
+ config.setThrottleConfig(throttleConfig);
+ populateTMBinaryConfig(throttling.getPublisher());
+ }
+
+ private void populateTMBinaryConfig(BinaryPublisher binary) {
+ ThrottleAgent binaryAgent = binary.getAgent();
+ AgentConfiguration agentConf = AgentConfiguration.getInstance();
+ agentConf.setBatchSize(binaryAgent.getBatchSize());
+ agentConf.setCiphers(binaryAgent.getCiphers());
+ agentConf.setCorePoolSize(binaryAgent.getCorePoolSize());
+ agentConf.setEvictionTimePeriod(binaryAgent.getEvictionTimePeriod());
+ agentConf.setKeepAliveTimeInPool(binaryAgent.getKeepAliveTimeInPool());
+ agentConf.setMaxIdleConnections(binaryAgent.getMaxIdleConnections());
+ agentConf.setMaxPoolSize(binaryAgent.getMaxPoolSize());
+ agentConf.setMaxTransportPoolSize(binaryAgent.getMaxTransportPoolSize());
+ agentConf.setMinIdleTimeInPool(binaryAgent.getMinIdleTimeInPool());
+ agentConf.setQueueSize(binaryAgent.getQueueSize());
+ agentConf.setReconnectionInterval(binaryAgent.getReconnectionInterval());
+ agentConf.setSecureEvictionTimePeriod(binaryAgent.getSecureEvictionTimePeriod());
+ agentConf.setSecureMaxIdleConnections(binaryAgent.getSecureMaxIdleConnections());
+ agentConf.setSecureMaxTransportPoolSize(binaryAgent.getSecureMaxTransportPoolSize());
+ agentConf.setSecureMinIdleTimeInPool(binaryAgent.getSecureMinIdleTimeInPool());
+ agentConf.setSslEnabledProtocols(binaryAgent.getSslEnabledProtocols());
+ agentConf.setSocketTimeoutMS(binaryAgent.getSocketTimeoutMS());
+ agentConf.setTrustStore(trustStore);
+
+ PublisherPool pool = binary.getPool();
+ PublisherConfiguration pubConf = PublisherConfiguration.getInstance();
+ pubConf.setUserName(binary.getUsername());
+ pubConf.setPassword(binary.getPassword());
+ pubConf.setInitIdleObjectDataPublishingAgents(pool.getInitIdleObjectDataPublishingAgents());
+ pubConf.setMaxIdleDataPublishingAgents(pool.getMaxIdleDataPublishingAgents());
+ pubConf.setPublisherThreadPoolCoreSize(pool.getPublisherThreadPoolCoreSize());
+ pubConf.setPublisherThreadPoolKeepAliveTime(pool.getPublisherThreadPoolKeepAliveTime());
+ pubConf.setPublisherThreadPoolMaximumSize(pool.getPublisherThreadPoolMaximumSize());
+
+ processTMPublisherURLGroup(binary.getUrlGroupList(), pubConf);
+
+ ThrottleAgentConfigDto throttleAgent = new ThrottleAgentConfigDto();
+ throttleAgent.setAgent(agentConf);
+ throttleAgent.setUsername(binary.getUsername());
+ throttleAgent.setPassword(binary.getPassword());
+ throttleAgent.setPublisher(pubConf);
+ config.getThrottleConfig().setThrottleAgent(throttleAgent);
+ }
+
private void loadTrustStore() {
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
@@ -230,6 +296,60 @@ private void populateAPIMCredentials(AmCredentials cred) {
config.setApimCredentials(credentialDto);
}
+ /**
+ * The receiverURLGroup and the authURLGroup is preprocessed
+ * such that to make them compatible with the binary agent.
+ */
+ private void processTMPublisherURLGroup(List urlGroups,
+ PublisherConfiguration pubConfiguration) {
+ StringBuilder restructuredReceiverURL = new StringBuilder();
+ StringBuilder restructuredAuthURL = new StringBuilder();
+
+ for (TMURLGroup urlGroup : urlGroups) {
+ List receiverUrls = urlGroup.getReceiverURLsList();
+ List authUrls = urlGroup.getAuthURLsList();
+ if (receiverUrls.size() == 1 && authUrls.size() == 1) {
+ restructuredReceiverURL.append("{").append(receiverUrls.get(0)).append("},");
+ restructuredAuthURL.append("{").append(authUrls.get(0)).append("},");
+ continue;
+ }
+ String urlType = urlGroup.getType();
+ if (urlType.isBlank() || !(Constants.LOADBALANCE.equalsIgnoreCase(urlType)
+ || Constants.FAILOVER.equalsIgnoreCase(urlType))) {
+ logger.warn("Type is not "
+ + Constants.LOADBALANCE + " or " + Constants.FAILOVER + ". Hence proceeding as a "
+ + Constants.FAILOVER + " configuration.");
+ urlType = Constants.FAILOVER;
+ }
+ restructuredReceiverURL.append(processSingleURLGroup(receiverUrls, urlType)).append(",");
+ restructuredAuthURL.append(processSingleURLGroup(authUrls, urlType)).append(",");
+ }
+
+ //to remove the final ',' in the URLs and set to publisher config
+ if (!restructuredReceiverURL.toString().isBlank() && !restructuredAuthURL.toString().isBlank()) {
+ pubConfiguration.setReceiverUrlGroup(restructuredReceiverURL.substring(0,
+ restructuredReceiverURL.length() - 1));
+ pubConfiguration.setAuthUrlGroup(restructuredAuthURL.substring(0, restructuredAuthURL.length() - 1));
+ }
+ }
+
+ private String processSingleURLGroup(List urlArray, String urlType) {
+ StringBuilder concatenatedURLString = new StringBuilder("{");
+ for (String url : urlArray) {
+ if (Constants.LOADBALANCE.equalsIgnoreCase(urlType)) {
+ concatenatedURLString.append(url).append(Constants.TM_BINARY_LOADBALANCE_SEPARATOR);
+ } else if (Constants.FAILOVER.equalsIgnoreCase(urlType)) {
+ concatenatedURLString.append(url).append(Constants.TM_BINARY_FAILOVER_SEPARATOR);
+ } else {
+ concatenatedURLString.append(url).append(Constants.TM_BINARY_FAILOVER_SEPARATOR);
+ }
+ }
+ //to remove the trailing '|' or ','
+ concatenatedURLString = new StringBuilder(
+ concatenatedURLString.substring(0, concatenatedURLString.length() - 1) + "}");
+ return concatenatedURLString.toString();
+ }
+
private void populateJWTGeneratorConfigurations(JWTGenerator jwtGenerator) {
JWTConfigurationDto jwtConfigurationDto = new JWTConfigurationDto();
jwtConfigurationDto.setEnabled(jwtGenerator.getEnable());
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/EnforcerConfig.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/EnforcerConfig.java
index 673e0785ac..2928a1dd4a 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/EnforcerConfig.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/EnforcerConfig.java
@@ -26,6 +26,7 @@
import org.wso2.micro.gateway.enforcer.config.dto.EventHubConfigurationDto;
import org.wso2.micro.gateway.enforcer.config.dto.ExtendedTokenIssuerDto;
import org.wso2.micro.gateway.enforcer.config.dto.JWTIssuerConfigurationDto;
+import org.wso2.micro.gateway.enforcer.config.dto.ThrottleConfigDto;
import java.util.HashMap;
import java.util.Map;
@@ -39,6 +40,7 @@ public class EnforcerConfig {
private EventHubConfigurationDto eventHub;
private Map issuersMap = new HashMap<>();
private CredentialDto apimCredentials;
+ private ThrottleConfigDto throttleConfig;
private JWTConfigurationDto jwtConfigurationDto;
private CacheDto cacheDto;
private JWTIssuerConfigurationDto jwtIssuerConfigurationDto;
@@ -79,6 +81,14 @@ public void setApimCredentials(CredentialDto apimCredentials) {
this.apimCredentials = apimCredentials;
}
+ public ThrottleConfigDto getThrottleConfig() {
+ return throttleConfig;
+ }
+
+ public void setThrottleConfig(ThrottleConfigDto throttleConfig) {
+ this.throttleConfig = throttleConfig;
+ }
+
public void setJwtConfigurationDto(JWTConfigurationDto jwtConfigurationDto) {
this.jwtConfigurationDto = jwtConfigurationDto;
}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleAgentConfigDto.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleAgentConfigDto.java
new file mode 100644
index 0000000000..0b54b82441
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleAgentConfigDto.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.config.dto;
+
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.conf.AgentConfiguration;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.publisher.PublisherConfiguration;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This contains throttle configurations.
+ */
+public class ThrottleAgentConfigDto {
+ String username;
+ String password;
+ List urlGroup = new ArrayList<>();
+ PublisherConfiguration publisher;
+ AgentConfiguration agent;
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public List getUrlGroup() {
+ return urlGroup;
+ }
+
+ public void setUrlGroup(List urlGroup) {
+ this.urlGroup = urlGroup;
+ }
+
+ public PublisherConfiguration getPublisher() {
+ return publisher;
+ }
+
+ public void setPublisher(PublisherConfiguration publisher) {
+ this.publisher = publisher;
+ }
+
+ public AgentConfiguration getAgent() {
+ return agent;
+ }
+
+ public void setAgent(AgentConfiguration agent) {
+ this.agent = agent;
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleConfigDto.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleConfigDto.java
new file mode 100644
index 0000000000..cf1b619f0d
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleConfigDto.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.config.dto;
+
+/**
+ * Throttling configuration model.
+ */
+public class ThrottleConfigDto {
+ private boolean isGlobalPublishingEnabled;
+ private boolean isHeaderConditionsEnabled;
+ private boolean isQueryConditionsEnabled;
+ private boolean isJwtClaimConditionsEnabled;
+ private String jmsConnectionInitialContextFactory;
+ private String jmsConnectionProviderUrl;
+ private ThrottleAgentConfigDto throttleAgent;
+
+ public boolean isGlobalPublishingEnabled() {
+ return isGlobalPublishingEnabled;
+ }
+
+ public void setGlobalPublishingEnabled(boolean globalPublishingEnabled) {
+ isGlobalPublishingEnabled = globalPublishingEnabled;
+ }
+
+ public boolean isHeaderConditionsEnabled() {
+ return isHeaderConditionsEnabled;
+ }
+
+ public void setHeaderConditionsEnabled(boolean headerConditionsEnabled) {
+ isHeaderConditionsEnabled = headerConditionsEnabled;
+ }
+
+ public boolean isQueryConditionsEnabled() {
+ return isQueryConditionsEnabled;
+ }
+
+ public void setQueryConditionsEnabled(boolean queryConditionsEnabled) {
+ isQueryConditionsEnabled = queryConditionsEnabled;
+ }
+
+ public boolean isJwtClaimConditionsEnabled() {
+ return isJwtClaimConditionsEnabled;
+ }
+
+ public void setJwtClaimConditionsEnabled(boolean jwtClaimConditionsEnabled) {
+ isJwtClaimConditionsEnabled = jwtClaimConditionsEnabled;
+ }
+
+ public String getJmsConnectionInitialContextFactory() {
+ return jmsConnectionInitialContextFactory;
+ }
+
+ public void setJmsConnectionInitialContextFactory(String jmsConnectionInitialContextFactory) {
+ this.jmsConnectionInitialContextFactory = jmsConnectionInitialContextFactory;
+ }
+
+ public String getJmsConnectionProviderUrl() {
+ return jmsConnectionProviderUrl;
+ }
+
+ public void setJmsConnectionProviderUrl(String jmsConnectionProviderUrl) {
+ this.jmsConnectionProviderUrl = jmsConnectionProviderUrl;
+ }
+
+ public ThrottleAgentConfigDto getThrottleAgent() {
+ return throttleAgent;
+ }
+
+ public void setThrottleAgent(ThrottleAgentConfigDto throttleAgent) {
+ this.throttleAgent = throttleAgent;
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleURLGroupDto.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleURLGroupDto.java
new file mode 100644
index 0000000000..ef33fc715b
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleURLGroupDto.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.config.dto;
+
+/**
+ * Throttle URL groups configurations.
+ */
+public class ThrottleURLGroupDto {
+ String[] receiverURLs;
+ String[] authURLs;
+ String type;
+
+ public String[] getReceiverURLs() {
+ return receiverURLs;
+ }
+
+ public void setReceiverURLs(String[] receiverURLs) {
+ this.receiverURLs = receiverURLs;
+ }
+
+ public String[] getAuthURLs() {
+ return authURLs;
+ }
+
+ public void setAuthURLs(String[] authURLs) {
+ this.authURLs = authURLs;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/APIConstants.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/APIConstants.java
index bbc33970fa..9c075547ec 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/APIConstants.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/APIConstants.java
@@ -22,8 +22,6 @@
*/
public class APIConstants {
- public static final String UNLIMITED_TIER = "Unlimited";
-
//open API extensions
public static final String X_WSO2_BASE_PATH = "x-wso2-basepath";
@@ -34,7 +32,6 @@ public class APIConstants {
public static final String GW_API_NAME_PARAM = "name";
public static final String PROTOTYPED_LIFE_CYCLE_STATUS = "PROTOTYPED";
-
public static final String GATEWAY_SIGNED_JWT_CACHE = "SignedJWTParseCache";
public static final String GATEWAY_PUBLIC_CERTIFICATE_ALIAS = "wso2carbon";
public static final String HTTPS_PROTOCOL = "https";
@@ -88,7 +85,7 @@ private KeyValidationStatus() {
}
/**
- * Holds the common set of constants for output of the subscription validation
+ * Holds the common set of constants for output of the subscription validation.
*/
public static class SubscriptionStatus {
@@ -105,7 +102,7 @@ private SubscriptionStatus() {
}
/**
- * Holds the common set of constants for validating the JWT tokens
+ * Holds the common set of constants for validating the JWT tokens.
*/
public static class JwtTokenConstants {
@@ -294,19 +291,6 @@ public enum PolicyType {
SUBSCRIPTION
}
- /**
- * Topic Names.
- */
- public static class TopicNames {
-
- //APIM default topic names
- public static final String TOPIC_THROTTLE_DATA = "throttleData";
- public static final String TOPIC_TOKEN_REVOCATION = "tokenRevocation";
- public static final String TOPIC_CACHE_INVALIDATION = "cacheInvalidation";
- public static final String TOPIC_KEY_MANAGER = "keyManager";
- public static final String TOPIC_NOTIFICATION = "notification";
- }
-
/**
* Holds the constants related to attributes to be sent in the response in case of an error
* scenario raised within the enforcer.
@@ -325,7 +309,8 @@ public enum StatusCodes {
OK("200", 200),
UNAUTHENTICATED("401", 401),
UNAUTHORIZED("403", 403),
- NOTFOUND("404", 404);
+ NOTFOUND("404", 404),
+ THROTTLED("429", 429);
private String value;
private int code;
@@ -342,4 +327,5 @@ public int getCode() {
return this.code;
}
}
+
}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/APISecurityConstants.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/APISecurityConstants.java
index 5eb4c07e12..635c3121e3 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/APISecurityConstants.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/APISecurityConstants.java
@@ -69,25 +69,12 @@ public class APISecurityConstants {
public static final int API_AUTH_MISSING_OPEN_API_DEF = 900911;
public static final String API_AUTH_MISSING_OPEN_API_DEF_ERROR_MESSAGE = "Internal Server Error";
- public static final int GRAPHQL_QUERY_TOO_DEEP = 900912;
- public static final String GRAPHQL_QUERY_TOO_DEEP_MESSAGE = "QUERY TOO DEEP";
-
- public static final int GRAPHQL_QUERY_TOO_COMPLEX = 900913;
- public static final String GRAPHQL_QUERY_TOO_COMPLEX_MESSAGE = "QUERY TOO COMPLEX";
-
- public static final int GRAPHQL_INVALID_QUERY = 900422;
- public static final String GRAPHQL_API_FAILURE_HANDLER = "_graphql_failure_handler";
- public static final String GRAPHQL_INVALID_QUERY_MESSAGE = "INVALID QUERY";
-
- public static final int OAUTH_TEMPORARY_SERVER_ERROR = 900424;
- public static final String OAUTH_TEMPORARY_SERVER_ERROR_MESSAGE = "Temporary Server Error";
-
// We have added this because we need to add an additional description to the original one and we need to
// separate the 2 messages
public static final String DESCRIPTION_SEPARATOR = ". ";
/**
- * returns an String that corresponds to errorCode passed in
+ * returns an String that corresponds to errorCode passed in.
*
* @param errorCode
* @return String
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/Constants.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/Constants.java
index 7a400a20be..b9ac14f1a7 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/Constants.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/constants/Constants.java
@@ -48,6 +48,12 @@ public class Constants {
public static final String END_OF_PRIVATE_KEY = "-----END PRIVATE KEY-----";
public static final String RSA = "RSA";
+ public static final String LOADBALANCE = "loadbalance";
+ public static final String FAILOVER = "failover";
+ public static final String TM_BINARY_LOADBALANCE_SEPARATOR = ",";
+ public static final String TM_BINARY_FAILOVER_SEPARATOR = "|";
+ public static final String UNKNOWN_VALUE = "__unknown__";
+
public static final String OBJECT_THIS_NOTATION = "this$";
public static final String ENV_PREFIX = "$env{";
public static final String START_BRACKET = "{";
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/filters/ThrottleFilter.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/filters/ThrottleFilter.java
new file mode 100644
index 0000000000..6df84a39b8
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/filters/ThrottleFilter.java
@@ -0,0 +1,312 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.micro.gateway.enforcer.filters;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.json.JSONObject;
+import org.wso2.micro.gateway.enforcer.Filter;
+import org.wso2.micro.gateway.enforcer.api.RequestContext;
+import org.wso2.micro.gateway.enforcer.api.config.APIConfig;
+import org.wso2.micro.gateway.enforcer.api.config.ResourceConfig;
+import org.wso2.micro.gateway.enforcer.config.ConfigHolder;
+import org.wso2.micro.gateway.enforcer.constants.APIConstants;
+import org.wso2.micro.gateway.enforcer.security.AuthenticationContext;
+import org.wso2.micro.gateway.enforcer.throttle.ThrottleAgent;
+import org.wso2.micro.gateway.enforcer.throttle.ThrottleConstants;
+import org.wso2.micro.gateway.enforcer.throttle.ThrottleDataHolder;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.util.ThrottleEventConstants;
+import org.wso2.micro.gateway.enforcer.util.FilterUtils;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * This is the filter handling the authentication for the requests flowing through the gateway.
+ */
+public class ThrottleFilter implements Filter {
+ private static final Logger log = LogManager.getLogger(ThrottleFilter.class);
+
+ private final boolean isGlobalThrottlingEnabled;
+ private final ThrottleDataHolder dataHolder;
+
+ public ThrottleFilter() {
+ this.dataHolder = ThrottleDataHolder.getInstance();
+ this.isGlobalThrottlingEnabled = ConfigHolder.getInstance().getConfig().getThrottleConfig()
+ .isGlobalPublishingEnabled();
+ }
+
+ @Override
+ public void init(APIConfig apiConfig) {}
+
+ @Override
+ public boolean handleRequest(RequestContext requestContext) {
+ log.debug("Throttle filter received the request");
+
+ if (doThrottle(requestContext)) {
+ // breaking filter chain since request is throttled
+ return false;
+ }
+
+ // publish throttle event and continue the filter chain
+ ThrottleAgent.publishNonThrottledEvent(getThrottleEventMap(requestContext));
+ return true;
+ }
+
+ /**
+ * Evaluate the throttle policies to find out if the request is throttled at any supported throttling level.
+ *
+ * @param reqContext request context with all request related details,
+ * including the authentication details
+ * @return {@code true} if the request is throttled, otherwise {@code false}
+ */
+ private boolean doThrottle(RequestContext reqContext) {
+ AuthenticationContext authContext = reqContext.getAuthenticationContext();
+
+ // TODO: (Praminda) Handle unauthenticated + subscription validation false scenarios
+ if (reqContext.getAuthenticationContext() != null) {
+ log.debug("Found AuthenticationContext for the request");
+ APIConfig api = reqContext.getMathedAPI().getAPIConfig();
+ String apiContext = api.getBasePath();
+ String apiVersion = api.getVersion();
+ String appId = authContext.getApplicationId();
+ String apiTier = authContext.getApiTier();
+ String apiThrottleKey = getApiThrottleKey(apiContext, apiVersion);
+ String resourceTier = getResourceTier(reqContext.getMatchedResourcePath());
+ String resourceThrottleKey = getResourceThrottleKey(reqContext, apiContext, apiVersion);
+ String subTier = authContext.getTier();
+ String appTier = authContext.getApplicationTier();
+
+ if (isAPILevelThrottled(apiThrottleKey, apiTier)) {
+ FilterUtils.setThrottleErrorToContext(reqContext,
+ ThrottleConstants.API_THROTTLE_OUT_ERROR_CODE,
+ ThrottleConstants.THROTTLE_OUT_MESSAGE,
+ ThrottleConstants.THROTTLE_OUT_DESCRIPTION);
+ reqContext.getProperties().put(ThrottleConstants.THROTTLE_OUT_REASON,
+ ThrottleConstants.THROTTLE_OUT_REASON_API_LIMIT_EXCEEDED);
+ return true;
+ } else if (isResourceLevelThrottled(resourceThrottleKey, resourceTier)) {
+ FilterUtils.setThrottleErrorToContext(reqContext,
+ ThrottleConstants.RESOURCE_THROTTLE_OUT_ERROR_CODE,
+ ThrottleConstants.THROTTLE_OUT_MESSAGE,
+ ThrottleConstants.THROTTLE_OUT_DESCRIPTION);
+ reqContext.getProperties().put(ThrottleConstants.THROTTLE_OUT_REASON,
+ ThrottleConstants.THROTTLE_OUT_REASON_RESOURCE_LIMIT_EXCEEDED);
+ return true;
+ }
+ String subThrottleKey = getSubscriptionThrottleKey(appId, apiContext, apiVersion);
+ boolean isSubscriptionThrottled = isSubscriptionLevelThrottled(subThrottleKey, subTier);
+ if (isSubscriptionThrottled) {
+ if (authContext.isStopOnQuotaReach()) {
+ log.debug("Setting subscription throttle out response");
+ FilterUtils.setThrottleErrorToContext(reqContext,
+ ThrottleConstants.SUBSCRIPTION_THROTTLE_OUT_ERROR_CODE,
+ ThrottleConstants.THROTTLE_OUT_MESSAGE,
+ ThrottleConstants.THROTTLE_OUT_DESCRIPTION);
+ reqContext.getProperties().put(ThrottleConstants.THROTTLE_OUT_REASON,
+ ThrottleConstants.THROTTLE_OUT_REASON_SUBSCRIPTION_LIMIT_EXCEEDED);
+ return true;
+ }
+ log.debug("Proceeding since stopOnQuotaReach is false");
+ }
+
+ String appThrottleKey = appId + ':' + authContext.getUsername();
+ boolean isAppThrottled = isAppLevelThrottled(appThrottleKey, appTier);
+ if (isAppThrottled) {
+ log.debug("Setting application throttle out response");
+ FilterUtils.setThrottleErrorToContext(reqContext,
+ ThrottleConstants.APPLICATION_THROTTLE_OUT_ERROR_CODE,
+ ThrottleConstants.THROTTLE_OUT_MESSAGE,
+ ThrottleConstants.THROTTLE_OUT_DESCRIPTION);
+ reqContext.getProperties().put(ThrottleConstants.THROTTLE_OUT_REASON,
+ ThrottleConstants.THROTTLE_OUT_REASON_APPLICATION_LIMIT_EXCEEDED);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean isSubscriptionLevelThrottled(String throttleKey, String tier) {
+ boolean isThrottled = dataHolder.isThrottled(throttleKey);
+ log.debug("Subscription Level throttle decision is {} for key:tier {}:{}", isThrottled, throttleKey, tier);
+ return isThrottled;
+ }
+
+ private boolean isAppLevelThrottled(String throttleKey, String tier) {
+ boolean isThrottled = dataHolder.isThrottled(throttleKey);
+ log.debug("Application Level throttle decision is {} for key:tier {}:{}", isThrottled, throttleKey, tier);
+ return isThrottled;
+ }
+
+ private boolean isAPILevelThrottled(String throttleKey, String tier) {
+ log.debug("Checking if request is throttled at API level for tier: {}", tier);
+
+ if (ThrottleConstants.UNLIMITED_TIER.equals(tier)) {
+ return false;
+ }
+
+ if (isGlobalThrottlingEnabled) {
+ // TODO: (Praminda) Check conditional throttling decisions
+ boolean isThrottled;
+ throttleKey += "_default";
+
+ isThrottled = dataHolder.isThrottled(throttleKey);
+ log.debug("API Level throttle decision: {}", isThrottled);
+ return isThrottled;
+ }
+ return false;
+ }
+
+ private boolean isResourceLevelThrottled(String throttleKey, String tier) {
+ log.debug("Checking if request is throttled at resource level for tier: " + tier);
+
+ if (ThrottleConstants.UNLIMITED_TIER.equals(tier)) {
+ return false;
+ }
+
+ if (isGlobalThrottlingEnabled) {
+ boolean isThrottled;
+ throttleKey += "_default";
+
+ isThrottled = dataHolder.isThrottled(throttleKey);
+ log.debug("Resource Level throttle decision: {}", isThrottled);
+ return isThrottled;
+ }
+ return false;
+ }
+
+ //TODO (amaliMatharaarachchi) Add default values to keys.
+ // Handle fault invocations.
+ // Test all flows.
+ // Add unit tests.
+
+ /**
+ * This will generate the throttling event map to be publish to the traffic manager.
+ *
+ * @param requestContext request context
+ * @return Map of throttle event data
+ */
+ private Map getThrottleEventMap(RequestContext requestContext) {
+ AuthenticationContext authenticationContext = requestContext.getAuthenticationContext();
+ Map throttleEvent = new HashMap<>();
+
+ String basePath = requestContext.getMathedAPI().getAPIConfig().getBasePath();
+ String apiVersion = requestContext.getMathedAPI().getAPIConfig().getVersion();
+ String apiContext = basePath + ':' + apiVersion;
+ String apiName = requestContext.getMathedAPI().getAPIConfig().getName();
+ String tenantDomain = FilterUtils.getTenantDomainFromRequestURL(apiContext);
+ if (tenantDomain == null) {
+ tenantDomain = APIConstants.SUPER_TENANT_DOMAIN_NAME;
+ }
+ String resourceTier;
+ String resourceKey;
+
+ if (!ThrottleConstants.UNLIMITED_TIER.equals(authenticationContext.getApiTier()) &&
+ authenticationContext.getApiTier() != null &&
+ !authenticationContext.getApiTier().isBlank()) {
+ resourceTier = authenticationContext.getApiTier();
+ resourceKey = apiContext;
+ } else {
+ resourceTier = getResourceTier(requestContext.getMatchedResourcePath());
+ resourceKey = getResourceThrottleKey(requestContext, apiContext, apiVersion);
+ }
+
+ throttleEvent.put(ThrottleEventConstants.MESSAGE_ID, requestContext.getRequestID());
+ throttleEvent.put(ThrottleEventConstants.APP_KEY, authenticationContext.getApplicationId() + ':' +
+ authenticationContext.getUsername());
+ throttleEvent.put(ThrottleEventConstants.APP_TIER, authenticationContext.getApplicationTier());
+ throttleEvent.put(ThrottleEventConstants.API_KEY, apiContext);
+ throttleEvent.put(ThrottleEventConstants.API_TIER, authenticationContext.getApiTier());
+ throttleEvent.put(ThrottleEventConstants.SUBSCRIPTION_KEY, authenticationContext.getApplicationId() + ':' +
+ apiContext);
+ throttleEvent.put(ThrottleEventConstants.SUBSCRIPTION_TIER, authenticationContext.getTier());
+ throttleEvent.put(ThrottleEventConstants.RESOURCE_KEY, resourceKey);
+ throttleEvent.put(ThrottleEventConstants.RESOURCE_TIER, resourceTier);
+ throttleEvent.put(ThrottleEventConstants.USER_ID, authenticationContext.getUsername());
+ throttleEvent.put(ThrottleEventConstants.API_CONTEXT, basePath);
+ throttleEvent.put(ThrottleEventConstants.API_VERSION, apiVersion);
+ throttleEvent.put(ThrottleEventConstants.APP_TENANT, authenticationContext.getSubscriberTenantDomain());
+ throttleEvent.put(ThrottleEventConstants.API_TENANT, tenantDomain);
+ throttleEvent.put(ThrottleEventConstants.APP_ID, authenticationContext.getApplicationId());
+ throttleEvent.put(ThrottleEventConstants.API_NAME, apiName);
+ throttleEvent.put(ThrottleEventConstants.PROPERTIES, getProperties(requestContext).toString());
+ return throttleEvent;
+ }
+
+ private String getResourceThrottleKey(RequestContext requestContext, String apiContext, String apiVersion) {
+ String resourceThrottleKey = apiContext;
+ if (!apiVersion.isBlank()) {
+ resourceThrottleKey += "/" + apiVersion;
+ }
+ resourceThrottleKey += requestContext.getMatchedResourcePath().getPath() + ':' +
+ requestContext.getRequestMethod();
+ return resourceThrottleKey;
+ }
+
+ private String getApiThrottleKey(String apiContext, String apiVersion) {
+ String apiThrottleKey = apiContext;
+ if (!apiVersion.isBlank()) {
+ apiThrottleKey += ':' + apiVersion;
+ }
+ return apiThrottleKey;
+ }
+
+ private String getSubscriptionThrottleKey(String appId, String apiContext, String apiVersion) {
+ String subThrottleKey = appId + ':' + apiContext;
+ if (!apiVersion.isBlank()) {
+ subThrottleKey += ':' + apiVersion;
+ }
+ return subThrottleKey;
+ }
+
+ private String getResourceTier(ResourceConfig resourceConfig) {
+ if (!resourceConfig.getTier().isBlank()) {
+ return resourceConfig.getTier();
+ }
+ return ThrottleConstants.UNLIMITED_TIER;
+ }
+
+
+ private JSONObject getProperties(RequestContext requestContext) {
+ String remoteIP = requestContext.getAddress();
+ JSONObject jsonObMap = new JSONObject();
+ if (remoteIP != null && remoteIP.length() > 0) {
+ try {
+ InetAddress address = InetAddress.getByName(remoteIP);
+ if (address instanceof Inet4Address) {
+ jsonObMap.put(ThrottleConstants.IP, FilterUtils.ipToLong(remoteIP));
+ jsonObMap.put(ThrottleConstants.IPV6, 0);
+ } else if (address instanceof Inet6Address) {
+ jsonObMap.put(ThrottleConstants.IPV6, FilterUtils.ipToBigInteger(remoteIP));
+ jsonObMap.put(ThrottleConstants.IP, 0);
+ }
+ } catch (UnknownHostException e) {
+ //send empty value as ip
+ log.error("Error while parsing host IP {}", remoteIP, e);
+ jsonObMap.put(ThrottleConstants.IPV6, 0);
+ jsonObMap.put(ThrottleConstants.IP, 0);
+ }
+ }
+ // TODO(amaliMatharaarachchi) Add advance throttling data to additional properties.
+ return jsonObMap;
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/listener/events/DeployAPIInGatewayEvent.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/listener/events/DeployAPIInGatewayEvent.java
index fcb7220feb..f6c2c4f85a 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/listener/events/DeployAPIInGatewayEvent.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/listener/events/DeployAPIInGatewayEvent.java
@@ -20,7 +20,7 @@
import java.util.Set;
/**
- * Deploy API in Gateway Event
+ * Deploy API in Gateway Event.
*/
public class DeployAPIInGatewayEvent extends Event {
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/listener/events/PolicyEvent.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/listener/events/PolicyEvent.java
index 639333ea45..33acf5773b 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/listener/events/PolicyEvent.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/listener/events/PolicyEvent.java
@@ -22,7 +22,7 @@
import org.wso2.micro.gateway.enforcer.constants.APIConstants;
/**
- * Policy Event class
+ * Policy Event class.
*/
public class PolicyEvent extends Event {
protected APIConstants.PolicyType policyType;
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApiPolicy.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApiPolicy.java
index 72bae01419..1affda7ddc 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApiPolicy.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApiPolicy.java
@@ -24,7 +24,7 @@
import java.util.List;
/**
- * Holds details about API/resource level Policy
+ * Holds details about API/resource level Policy.
*/
public class ApiPolicy extends Policy {
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApplicationKeyMappingCacheKey.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApplicationKeyMappingCacheKey.java
index 9c97589c53..80a9976e51 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApplicationKeyMappingCacheKey.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApplicationKeyMappingCacheKey.java
@@ -21,7 +21,7 @@
import java.util.Objects;
/**
- * Cache Key For Application KeyMapping Entries
+ * Cache Key For Application KeyMapping Entries.
*/
public class ApplicationKeyMappingCacheKey {
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApplicationPolicy.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApplicationPolicy.java
index 438bea95d7..981adb5117 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApplicationPolicy.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/ApplicationPolicy.java
@@ -21,7 +21,7 @@
import org.wso2.micro.gateway.enforcer.common.CacheableEntity;
/**
- * Entity for keeping Application Policy
+ * Entity for keeping Application Policy.
*/
public class ApplicationPolicy extends Policy {
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/Subscription.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/Subscription.java
index a604131382..d56c590e71 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/Subscription.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/models/Subscription.java
@@ -22,7 +22,7 @@
import org.wso2.micro.gateway.enforcer.subscription.SubscriptionDataStoreUtil;
/**
- * Entity for representing a SubscriptionDTO in APIM
+ * Entity for representing a SubscriptionDTO in APIM.
*/
public class Subscription implements CacheableEntity {
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/AccessTokenInfo.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/AccessTokenInfo.java
index c8fd05aac0..48edbe9f4c 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/AccessTokenInfo.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/AccessTokenInfo.java
@@ -101,7 +101,7 @@ public void setConsumerKey(String consumerKey) {
}
/**
- * Get consumer secret corresponding to the access token
+ * Get consumer secret corresponding to the access token.
*
* @return consumer secret
*/
@@ -110,7 +110,7 @@ public String getConsumerSecret() {
}
/**
- * Set consumer secret corresponding to the access token
+ * Set consumer secret corresponding to the access token.
*
* @param consumerSecret consumer secret to set
*/
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/AuthenticationContext.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/AuthenticationContext.java
index 11dd83f20d..aaf0b82ebb 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/AuthenticationContext.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/AuthenticationContext.java
@@ -18,6 +18,9 @@
package org.wso2.micro.gateway.enforcer.security;
+import org.wso2.micro.gateway.enforcer.constants.Constants;
+import org.wso2.micro.gateway.enforcer.throttle.ThrottleConstants;
+
import java.util.List;
/**
@@ -50,6 +53,19 @@ public class AuthenticationContext {
private String apiPublisher;
private String apiVersion;
+ public AuthenticationContext() {
+ this.applicationId = Constants.UNKNOWN_VALUE;
+ this.apiPublisher = Constants.UNKNOWN_VALUE;
+ this.apiTier = "";
+ this.applicationId = Constants.UNKNOWN_VALUE;
+ this.applicationName = Constants.UNKNOWN_VALUE;
+ this.applicationTier = ThrottleConstants.UNLIMITED_TIER;
+ this.consumerKey = Constants.UNKNOWN_VALUE;
+ this.spikeArrestUnit = "";
+ this.subscriber = Constants.UNKNOWN_VALUE;
+ this.subscriberTenantDomain = Constants.UNKNOWN_VALUE;
+ }
+
public List getThrottlingDataList() {
return throttlingDataList;
}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/JWTAuthenticator.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/JWTAuthenticator.java
index ff8a977cc0..2819ac372c 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/JWTAuthenticator.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/JWTAuthenticator.java
@@ -115,11 +115,9 @@ public AuthenticationContext authenticate(RequestContext requestContext) throws
}
- JWTValidationInfo validationInfo =
- getJwtValidationInfo(signedJWTInfo, jwtTokenIdentifier);
+ JWTValidationInfo validationInfo = getJwtValidationInfo(signedJWTInfo, jwtTokenIdentifier);
if (validationInfo != null) {
if (validationInfo.isValid()) {
-
// Validate subscriptions
APIKeyValidationInfoDTO apiKeyValidationInfoDTO = null;
EnforcerConfig configuration = ConfigHolder.getInstance().getConfig();
@@ -167,8 +165,8 @@ public AuthenticationContext authenticate(RequestContext requestContext) throws
}
AuthenticationContext authenticationContext = FilterUtils
- .generateAuthenticationContext(jwtTokenIdentifier, validationInfo, apiKeyValidationInfoDTO,
- endUserToken, true);
+ .generateAuthenticationContext(requestContext, jwtTokenIdentifier, validationInfo,
+ apiKeyValidationInfoDTO, endUserToken, true);
//TODO: (VirajSalaka) Place the keytype population logic properly for self contained token
if (claims.getClaim("keytype") != null) {
authenticationContext.setKeyType(claims.getClaim("keytype").toString());
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/JWTUtil.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/JWTUtil.java
index 56f54b80e0..e1e3c5755b 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/JWTUtil.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/JWTUtil.java
@@ -78,7 +78,7 @@ public class JWTUtil {
private static volatile long ttl = -1L;
/**
- * This method used to retrieve JWKS keys from endpoint
+ * This method used to retrieve JWKS keys from endpoint.
*
* @param jwksEndpoint
* @return
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/SignedJWTInfo.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/SignedJWTInfo.java
index 6d25ec2ae1..5a2ba889d3 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/SignedJWTInfo.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/SignedJWTInfo.java
@@ -24,7 +24,7 @@
import java.io.Serializable;
/**
- * JWT internal Representation
+ * JWT internal Representation.
*/
public class SignedJWTInfo implements Serializable {
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/validator/RevokedJWTDataHolder.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/validator/RevokedJWTDataHolder.java
index 1d20ea03e8..90596244f5 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/validator/RevokedJWTDataHolder.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/security/jwt/validator/RevokedJWTDataHolder.java
@@ -27,7 +27,7 @@
import java.util.concurrent.ConcurrentHashMap;
/**
- * Singleton which stores the revoked JWT map
+ * Singleton which stores the revoked JWT map.
*/
public class RevokedJWTDataHolder {
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/server/AuthServer.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/server/AuthServer.java
index 6e5720dfd7..af959d1dff 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/server/AuthServer.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/server/AuthServer.java
@@ -37,6 +37,8 @@
import org.wso2.micro.gateway.enforcer.keymgt.KeyManagerHolder;
import org.wso2.micro.gateway.enforcer.security.jwt.validator.RevokedJWTDataHolder;
import org.wso2.micro.gateway.enforcer.subscription.SubscriptionDataHolder;
+import org.wso2.micro.gateway.enforcer.throttle.ThrottleAgent;
+import org.wso2.micro.gateway.enforcer.throttle.ThrottleEventListener;
import java.io.File;
import java.io.IOException;
@@ -62,6 +64,11 @@ public static void main(String[] args) {
// Initialise cache objects
CacheProvider.init();
+ if (ConfigHolder.getInstance().getConfig().getThrottleConfig().isGlobalPublishingEnabled()) {
+ ThrottleAgent.startThrottlePublisherPool();
+ ThrottleEventListener.init();
+ }
+
// Start the server
server.start();
logger.info("Sever started Listening in port : " + 8081);
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/server/RequestHandler.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/server/RequestHandler.java
index 6734c85e3e..c4c8431b0b 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/server/RequestHandler.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/server/RequestHandler.java
@@ -68,10 +68,16 @@ private RequestContext buildRequestContext(API api, CheckRequest request) {
.get(AdapterConstants.PROD_CLUSTER_HEADER_KEY);
String sandCluster = request.getAttributes().getContextExtensionsMap()
.get(AdapterConstants.SAND_CLUSTER_HEADER_KEY);
+ String requestID = request.getAttributes().getRequest().getHttp().getId();
+ String address = "";
+ if (request.getAttributes().getSource().hasAddress() &&
+ request.getAttributes().getSource().getAddress().hasSocketAddress()) {
+ address = request.getAttributes().getSource().getAddress().getSocketAddress().getAddress();
+ }
ResourceConfig resourceConfig = APIFactory.getInstance().getMatchedResource(api, res, method);
return new RequestContext.Builder(requestPath).matchedResourceConfig(resourceConfig).requestMethod(method)
- .matchedAPI(api).headers(headers).prodClusterHeader(prodCluster).sandClusterHeader(sandCluster)
- .build();
+ .matchedAPI(api).headers(headers).requestID(requestID).address(address).prodClusterHeader(prodCluster)
+ .sandClusterHeader(sandCluster).build();
}
}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/subscription/SubscriptionDataHolder.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/subscription/SubscriptionDataHolder.java
index 45b547f4a1..7cfc9abde0 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/subscription/SubscriptionDataHolder.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/subscription/SubscriptionDataHolder.java
@@ -19,7 +19,7 @@
package org.wso2.micro.gateway.enforcer.subscription;
/**
- * This class holds tenant wise subscription data stores
+ * This class holds tenant wise subscription data stores.
*/
public class SubscriptionDataHolder {
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/subscription/SubscriptionDataStore.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/subscription/SubscriptionDataStore.java
index cd727fbdaa..69d31f8f56 100644
--- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/subscription/SubscriptionDataStore.java
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/subscription/SubscriptionDataStore.java
@@ -35,7 +35,7 @@
public interface SubscriptionDataStore {
/**
- * Gets an {@link Application} by Id
+ * Gets an {@link Application} by Id.
*
* @param appId Id of the Application
* @return {@link Application} with the appId
@@ -43,7 +43,7 @@ public interface SubscriptionDataStore {
Application getApplicationById(int appId);
/**
- * Gets the {@link ApplicationKeyMapping} entry by Key
+ * Gets the {@link ApplicationKeyMapping} entry by Key.
*
* @param key .
* @param keyManager Keymanager Name
@@ -52,7 +52,7 @@ public interface SubscriptionDataStore {
ApplicationKeyMapping getKeyMappingByKeyAndKeyManager(String key, String keyManager);
/**
- * Get API by Context and Version
+ * Get API by Context and Version.
*
* @param context Context of the API
* @param version Version of the API
@@ -61,7 +61,7 @@ public interface SubscriptionDataStore {
API getApiByContextAndVersion(String context, String version);
/**
- * Gets Subscription by ID
+ * Gets Subscription by ID.
*
* @param appId Application associated with the Subscription
* @param apiId Api associated with the Subscription
@@ -70,7 +70,7 @@ public interface SubscriptionDataStore {
Subscription getSubscriptionById(int appId, int apiId);
/**
- * Gets API Throttling Policy by the name and Tenant Id
+ * Gets API Throttling Policy by the name and Tenant Id.
*
* @param policyName Name of the Throttling Policy
* @param tenantId Tenant ID in the Policy
@@ -79,7 +79,7 @@ public interface SubscriptionDataStore {
ApiPolicy getApiPolicyByName(String policyName, int tenantId);
/**
- * Gets Subscription Throttling Policy by the name and Tenant Id
+ * Gets Subscription Throttling Policy by the name and Tenant Id.
*
* @param policyName Name of the Throttling Policy
* @param tenantId Tenant ID in the Policy
@@ -88,7 +88,7 @@ public interface SubscriptionDataStore {
SubscriptionPolicy getSubscriptionPolicyByName(String policyName, int tenantId);
/**
- * Gets Application Throttling Policy by the name and Tenant Id
+ * Gets Application Throttling Policy by the name and Tenant Id.
*
* @param policyName Name of the Throttling Policy
* @param tenantId Tenant ID in the Policy
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/APICondition.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/APICondition.java
new file mode 100644
index 0000000000..6282a460d6
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/APICondition.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle;
+
+/**
+ * DTO of parameters defining a throttle condition.
+ */
+public class APICondition {
+ private final String resourceKey;
+ private final String name;
+
+ public APICondition(String resourceKey, String name) {
+ this.resourceKey = resourceKey;
+ this.name = name;
+ }
+
+ public String getResourceKey() {
+ return resourceKey;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String toString() {
+ return "resourceKey='" + resourceKey + "', name='" + name + '\'';
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/PolicyConstants.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/PolicyConstants.java
new file mode 100644
index 0000000000..388f3dfccd
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/PolicyConstants.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle;
+
+/**
+ * Throttle policy constants.
+ */
+public class PolicyConstants {
+ public static final String IP_RANGE_TYPE = "IPRange";
+ public static final String IP_SPECIFIC_TYPE = "IPSpecific";
+ public static final String HEADER_TYPE = "Header";
+ public static final String JWT_CLAIMS_TYPE = "JWTClaims";
+ public static final String QUERY_PARAMETER_TYPE = "QueryParameterType";
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleAgent.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleAgent.java
new file mode 100644
index 0000000000..d4d983701e
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleAgent.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle;
+
+import org.wso2.micro.gateway.enforcer.throttle.databridge.publisher.ThrottleDataPublisher;
+
+import java.util.Map;
+
+/**
+ * This class is used for ballerina interop invocations related to Global Throttle Event Publishing
+ * via binary communication.
+ */
+public class ThrottleAgent {
+
+ private static ThrottleDataPublisher throttleDataPublisher = null;
+
+ public static void startThrottlePublisherPool() {
+ throttleDataPublisher = new ThrottleDataPublisher();
+ }
+
+ public static void publishNonThrottledEvent(Map throttleEvent) {
+ throttleDataPublisher.publishNonThrottledEvent(throttleEvent);
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleCondition.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleCondition.java
new file mode 100644
index 0000000000..1e21b7d14b
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleCondition.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle;
+
+import java.math.BigInteger;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Defines the applicable conditions and the types of conditions for a conditional throttle policy.
+ */
+public class ThrottleCondition {
+ private IPCondition ipCondition;
+ private IPCondition ipRangeCondition;
+ private HeaderConditions headerConditions;
+ private QueryParamConditions queryParameterConditions;
+ private JWTClaimConditions jwtClaimConditions;
+
+ public IPCondition getIpCondition() {
+ return ipCondition;
+ }
+
+ public void setIpCondition(IPCondition ipCondition) {
+ this.ipCondition = ipCondition;
+ }
+
+ public IPCondition getIpRangeCondition() {
+ return ipRangeCondition;
+ }
+
+ public void setIpRangeCondition(IPCondition ipRangeCondition) {
+ this.ipRangeCondition = ipRangeCondition;
+ }
+
+ public HeaderConditions getHeaderConditions() {
+ return headerConditions;
+ }
+
+ public void setHeaderConditions(HeaderConditions headerConditions) {
+ this.headerConditions = headerConditions;
+ }
+
+ public QueryParamConditions getQueryParameterConditions() {
+ return queryParameterConditions;
+ }
+
+ public void setQueryParameterConditions(QueryParamConditions queryParameterConditions) {
+ this.queryParameterConditions = queryParameterConditions;
+ }
+
+ public JWTClaimConditions getJwtClaimConditions() {
+ return jwtClaimConditions;
+ }
+
+ public void setJwtClaimConditions(JWTClaimConditions jwtClaimConditions) {
+ this.jwtClaimConditions = jwtClaimConditions;
+ }
+
+ /**
+ * Throttle condition based on request headers.
+ */
+ public static class HeaderConditions {
+ private Map values = new HashMap<>();
+ private boolean invert;
+
+ public Map getValues() {
+ return values;
+ }
+
+ public void setValues(Map values) {
+ this.values = values;
+ }
+
+ public boolean isInvert() {
+ return invert;
+ }
+
+ public void setInvert(boolean invert) {
+ this.invert = invert;
+ }
+ }
+
+ /**
+ * Throttle condition based on request query parameters.
+ */
+ public static class QueryParamConditions {
+ private Map values = new HashMap<>();
+ private boolean invert;
+
+ public Map getValues() {
+ return values;
+ }
+
+ public void setValues(Map values) {
+ this.values = values;
+ }
+
+ public boolean isInvert() {
+ return invert;
+ }
+
+ public void setInvert(boolean invert) {
+ this.invert = invert;
+ }
+ }
+
+ /**
+ * Throttle condition based on jwt claim conditions.
+ */
+ public static class JWTClaimConditions {
+ private Map values = new HashMap<>();
+ private boolean invert;
+
+ public Map getValues() {
+ return values;
+ }
+
+ public void setValues(Map values) {
+ this.values = values;
+ }
+
+ public boolean isInvert() {
+ return invert;
+ }
+
+ public void setInvert(boolean invert) {
+ this.invert = invert;
+ }
+ }
+
+ /**
+ * Throttle condition based on request IP address.
+ */
+ public static class IPCondition {
+ private BigInteger specificIp;
+ private BigInteger startingIp;
+ private BigInteger endingIp;
+ private boolean invert;
+
+ public IPCondition() {
+
+ }
+
+ public IPCondition(BigInteger specificIp, boolean invert) {
+
+ this.specificIp = specificIp;
+ this.invert = invert;
+ }
+
+ public IPCondition(BigInteger startingIp, BigInteger endingIp, boolean invert) {
+
+ this.startingIp = startingIp;
+ this.endingIp = endingIp;
+ this.invert = invert;
+ }
+
+ public BigInteger getSpecificIp() {
+ return specificIp;
+ }
+
+ public void setSpecificIp(BigInteger specificIp) {
+ this.specificIp = specificIp;
+ }
+
+ public BigInteger getStartingIp() {
+ return startingIp;
+ }
+
+ public void setStartingIp(BigInteger startingIp) {
+ this.startingIp = startingIp;
+ }
+
+ public BigInteger getEndingIp() {
+ return endingIp;
+ }
+
+ public void setEndingIp(BigInteger endingIp) {
+ this.endingIp = endingIp;
+ }
+
+ public boolean isInvert() {
+ return invert;
+ }
+
+ public void setInvert(boolean invert) {
+ this.invert = invert;
+ }
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleConstants.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleConstants.java
new file mode 100644
index 0000000000..76a27baccb
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleConstants.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle;
+
+/**
+ * Constants related to Throttling
+ */
+public class ThrottleConstants {
+ public static final int API_THROTTLE_OUT_ERROR_CODE = 900800;
+ public static final int HARD_LIMIT_EXCEEDED_ERROR_CODE = 900801;
+ public static final int RESOURCE_THROTTLE_OUT_ERROR_CODE = 900802;
+ public static final int APPLICATION_THROTTLE_OUT_ERROR_CODE = 900803;
+ public static final int SUBSCRIPTION_THROTTLE_OUT_ERROR_CODE = 900804;
+ public static final int SUBSCRIPTION_BURST_THROTTLE_OUT_ERROR_CODE = 900807;
+ public static final int BLOCKED_ERROR_CODE = 900805;
+ public static final int CUSTOM_POLICY_THROTTLE_OUT_ERROR_CODE = 900806;
+ public static final int CONNECTIONS_COUNT_THROTTLE_OUT_ERROR_CODE = 900808;
+ public static final int EVENTS_COUNT_THROTTLE_OUT_ERROR_CODE = 900808;
+
+ public static final String THROTTLE_OUT_MESSAGE = "Message throttled out";
+ public static final String THROTTLE_OUT_DESCRIPTION = "You have exceeded your quota";
+ public static final String BLOCKING_MESSAGE = "Message blocked";
+ public static final String BLOCKING_DESCRIPTION = "You have been blocked from accessing the resource";
+
+ public static final String THROTTLE_OUT_REASON_API_LIMIT_EXCEEDED = "API_LIMIT_EXCEEDED";
+ public static final String THROTTLE_OUT_REASON_RESOURCE_LIMIT_EXCEEDED = "RESOURCE_LIMIT_EXCEEDED";
+ public static final String THROTTLE_OUT_REASON_SUBSCRIPTION_LIMIT_EXCEEDED = "SUBSCRIPTION_LIMIT_EXCEEDED";
+ public static final String THROTTLE_OUT_REASON_APPLICATION_LIMIT_EXCEEDED = "APPLICATION_LIMIT_EXCEEDED";
+ public static final String POLICY_NOT_FOUND_DESCRIPTION = "POLICY ENFORCEMENT ERROR";
+
+ public static final String UNLIMITED_TIER = "Unlimited";
+ public static final String IP = "ip";
+ public static final String IPV6 = "ipv6";
+ public static final String BLOCKING_CONDITION_KEY = "blockingCondition";
+ public static final String POLICY_TEMPLATE_KEY = "keyTemplateValue";
+ public static final String THROTTLE_KEY = "throttleKey";
+ public static final String THROTTLE_OUT_REASON = "THROTTLED_OUT_REASON";
+ public static final String TOPIC_THROTTLE_DATA = "throttleData";
+
+ /**
+ * Advanced Throttling related constants.
+ */
+ public static class AdvancedThrottleConstants {
+ public static final String IS_THROTTLED = "isThrottled";
+ public static final String THROTTLE_KEY = "throttleKey";
+ public static final String EXPIRY_TIMESTAMP = "expiryTimeStamp";
+ public static final String EVALUATED_CONDITIONS = "evaluatedConditions";
+ public static final String TRUE = "true";
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleDataHolder.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleDataHolder.java
new file mode 100644
index 0000000000..936cb8bf91
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleDataHolder.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle;
+
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * This class holds throttle data per given node. In addition to holding throttle data if provides
+ * required methods to evaluate throttle state of a given throttling key.
+ */
+public class ThrottleDataHolder {
+ private static final Log log = LogFactory.getLog(ThrottleDataHolder.class);
+
+ private final Map throttleDataMap;
+ private static ThrottleDataHolder instance;
+ private final Map>> conditionDtoMap = new ConcurrentHashMap<>();
+
+ private ThrottleDataHolder() {
+ throttleDataMap = new ConcurrentHashMap<>();
+ }
+
+ public static ThrottleDataHolder getInstance() {
+ if (instance == null) {
+ instance = new ThrottleDataHolder();
+ }
+
+ return instance;
+ }
+
+ /**
+ * Add throttle conditions to the Throttle Conditions map.
+ *
+ * @param key throttle key
+ * @param conditionKey condition key
+ * @param conditionValue conditions to be added to the map
+ */
+ public void addThrottledConditions(String key, String conditionKey, List conditionValue) {
+ Map> conditionMap;
+
+ if (conditionDtoMap.containsKey(key)) {
+ conditionMap = conditionDtoMap.get(key);
+ } else {
+ conditionMap = new ConcurrentHashMap<>();
+ conditionDtoMap.put(key, conditionMap);
+ }
+ if (!conditionMap.containsKey(conditionKey)) {
+ conditionMap.put(conditionKey, conditionValue);
+ }
+ }
+
+ /**
+ * Remove throttle conditions from the Throttle Conditions map.
+ *
+ * @param key throttle key
+ * @param conditionKey condition key to be removed
+ */
+ public void removeThrottledConditions(String key, String conditionKey) {
+ if (conditionDtoMap.containsKey(key)) {
+ Map> conditionMap = conditionDtoMap.get(key);
+ conditionMap.remove(conditionKey);
+ if (conditionMap.isEmpty()) {
+ conditionDtoMap.remove(key);
+ }
+ }
+ }
+
+ /**
+ * Add new throttle data item to the throttle data map.
+ *
+ * @param key throttle key to be added
+ * @param timestamp throttle timestamp
+ */
+ public void addThrottleData(String key, Long timestamp) {
+ throttleDataMap.put(key, timestamp);
+ }
+
+ /**
+ * Remove throttle data item from the throttle data map.
+ *
+ * @param key throttle key to be removed
+ */
+ public void removeThrottleData(String key) {
+ throttleDataMap.remove(key);
+ }
+
+ /**
+ * This method will check given key in throttle data Map. A key is considered throttled if,
+ *
+ *
A values for the given @{code key} exists in the throttle data map
+ *
Validity timestamp for the provided key is not passed already
+ *
+ *
+ * @param key throttle key
+ * @return {@code true} if event is throttled {@code false} if event is not throttled.
+ */
+ public boolean isThrottled(String key) {
+ boolean isThrottled = this.throttleDataMap.containsKey(key);
+
+ if (isThrottled) {
+ long currentTime = System.currentTimeMillis();
+ long timestamp = this.throttleDataMap.get(key);
+ if (timestamp < currentTime) {
+ this.throttleDataMap.remove(key);
+ isThrottled = false;
+ }
+ }
+
+ return isThrottled;
+ }
+
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleEventListener.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleEventListener.java
new file mode 100644
index 0000000000..8939b7e151
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleEventListener.java
@@ -0,0 +1,190 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.wso2.micro.gateway.enforcer.config.ConfigHolder;
+import org.wso2.micro.gateway.enforcer.config.dto.ThrottleConfigDto;
+
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.jms.JMSException;
+import javax.jms.MapMessage;
+import javax.jms.Message;
+import javax.jms.MessageListener;
+import javax.jms.Topic;
+import javax.jms.TopicConnection;
+import javax.jms.TopicConnectionFactory;
+import javax.jms.TopicSession;
+import javax.jms.TopicSubscriber;
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+/**
+ * JMS event listener for throttle data.
+ */
+public class ThrottleEventListener implements MessageListener {
+ private static final Logger log = LogManager.getLogger(ThrottleEventListener.class);
+
+ // These patterns will be used to determine for which type of keys the throttling condition has occurred.
+ private final Pattern apiPattern = Pattern.compile("/.*/(.*):\\1_(condition_(\\d*)|default)");
+ private static final int API_PATTERN_GROUPS = 3;
+ private static final int API_PATTERN_CONDITION_INDEX = 2;
+
+ private final Pattern resourcePattern = Pattern.compile("/.*/(.*)/\\1(.*)?:[A-Z]{0,7}_(condition_(\\d*)|default)");
+ public static final int RESOURCE_PATTERN_GROUPS = 4;
+ public static final int RESOURCE_PATTERN_CONDITION_INDEX = 3;
+
+ private ThrottleEventListener() {}
+
+ public static void init() {
+ ThrottleConfigDto throttleConf = ConfigHolder.getInstance().getConfig().getThrottleConfig();
+ String initialContextFactory = throttleConf.getJmsConnectionInitialContextFactory();
+ String connectionFactoryNamePrefix = "connectionfactory.";
+ String connectionFactoryName = "qpidConnectionfactory";
+ String eventReceiverURL = throttleConf.getJmsConnectionProviderUrl();
+ Runnable runnable = () -> {
+ try {
+ TopicConnection topicConnection;
+ TopicSession topicSession;
+ Properties properties = new Properties();
+ properties.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
+ properties.put(connectionFactoryNamePrefix + connectionFactoryName, eventReceiverURL);
+ InitialContext context = new InitialContext(properties);
+ TopicConnectionFactory connFactory = (TopicConnectionFactory) context.lookup(connectionFactoryName);
+ topicConnection = connFactory.createTopicConnection();
+ topicConnection.start();
+ topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
+ Topic gatewayJmsTopic = topicSession.createTopic(ThrottleConstants.TOPIC_THROTTLE_DATA);
+ TopicSubscriber listener = topicSession.createSubscriber(gatewayJmsTopic);
+ listener.setMessageListener(new ThrottleEventListener());
+ } catch (NamingException | JMSException e) {
+ log.error("Error while initiating jms connection...", e);
+ }
+ };
+ Thread jmsThread = new Thread(runnable);
+ jmsThread.start();
+ }
+
+ @Override
+ public void onMessage(Message message) {
+ if (message == null) {
+ log.warn("Dropping the empty/null event received through jms receiver");
+ return;
+ } else if (!(message instanceof MapMessage)) {
+ log.warn("Event dropped due to unsupported message type " + message.getClass());
+ return;
+ }
+
+ try {
+ Topic jmsDestination = (Topic) message.getJMSDestination();
+ MapMessage mapMessage = (MapMessage) message;
+ Map map = new HashMap<>();
+ Enumeration enumeration = mapMessage.getMapNames();
+ while (enumeration.hasMoreElements()) {
+ String key = (String) enumeration.nextElement();
+ map.put(key, mapMessage.getObject(key));
+ }
+
+ if (ThrottleConstants.TOPIC_THROTTLE_DATA.equalsIgnoreCase(jmsDestination.getTopicName())) {
+ if (map.get(ThrottleConstants.THROTTLE_KEY) != null) {
+ /*
+ * This message contains throttle data in map which contains Keys
+ * throttleKey - Key of particular throttling level
+ * isThrottled - Whether message has throttled or not
+ * expiryTimeStamp - When the throttling time window will expires
+ */
+
+ handleThrottleUpdateMessage(map);
+ }
+ }
+ } catch (JMSException e) {
+ log.error("Error occurred when processing the received message ", e);
+ }
+ }
+
+ private void handleThrottleUpdateMessage(Map map) {
+ String throttleKey = map.get(ThrottleConstants.AdvancedThrottleConstants.THROTTLE_KEY).toString();
+ String throttleState = map.get(ThrottleConstants.AdvancedThrottleConstants.IS_THROTTLED).toString();
+ long timeStamp = Long.parseLong(map.get(ThrottleConstants.
+ AdvancedThrottleConstants.EXPIRY_TIMESTAMP).toString());
+ Object evaluatedConditionObject = map.get(ThrottleConstants.AdvancedThrottleConstants.EVALUATED_CONDITIONS);
+ ThrottleDataHolder dataHolder = ThrottleDataHolder.getInstance();
+
+ if (log.isDebugEnabled()) {
+ log.debug("Received event - throttleKey : " + throttleKey + ", isThrottled: " +
+ throttleState + ", expiryTime: " + new Date(timeStamp).toString());
+ }
+
+ if (ThrottleConstants.AdvancedThrottleConstants.TRUE.equalsIgnoreCase(throttleState)) {
+ dataHolder.addThrottleData(throttleKey, timeStamp);
+ APICondition extractedKey = extractAPIorResourceKey(throttleKey);
+ log.debug("Adding throttling key : {}", extractedKey);
+
+ if (extractedKey != null) {
+ if (evaluatedConditionObject != null) {
+ String conditionStr = (String) evaluatedConditionObject;
+ List conditions = ThrottleUtils.extractThrottleCondition(conditionStr);
+ dataHolder.addThrottledConditions(extractedKey.getResourceKey(), extractedKey.getName(),
+ conditions);
+ }
+ }
+ } else {
+ dataHolder.removeThrottleData(throttleKey);
+ APICondition extractedKey = extractAPIorResourceKey(throttleKey);
+ if (extractedKey != null) {
+ if (log.isDebugEnabled()) {
+ log.debug("Removing throttling key : " + extractedKey.getResourceKey());
+ }
+
+ dataHolder.removeThrottledConditions(extractedKey.getResourceKey(), extractedKey.getName());
+ }
+ }
+ }
+
+ private APICondition extractAPIorResourceKey(String throttleKey) {
+ Matcher m = resourcePattern.matcher(throttleKey);
+ if (m.matches()) {
+ if (m.groupCount() == RESOURCE_PATTERN_GROUPS) {
+ String condition = m.group(RESOURCE_PATTERN_CONDITION_INDEX);
+ String resourceKey = throttleKey.substring(0, throttleKey.indexOf("_" + condition));
+ return new APICondition(resourceKey, condition);
+ }
+ } else {
+ m = apiPattern.matcher(throttleKey);
+ if (m.matches()) {
+ if (m.groupCount() == API_PATTERN_GROUPS) {
+ String condition = m.group(API_PATTERN_CONDITION_INDEX);
+ String resourceKey = throttleKey.substring(0, throttleKey.indexOf("_" + condition));
+ return new APICondition(resourceKey, condition);
+ }
+ }
+ }
+ return null;
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleUtils.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleUtils.java
new file mode 100644
index 0000000000..f3172eb07f
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/ThrottleUtils.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle;
+
+import com.google.gson.Gson;
+import org.apache.commons.codec.binary.Base64;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.json.JSONTokener;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Utilities related to throttling.
+ */
+public class ThrottleUtils {
+
+ /**
+ * Extract a {@code ThrottleCondition} from a provided compatible base64 encoded string.
+ *
+ * @param base64EncodedString base64 encoded string containing a json in compatible format
+ * @return list of extracted {@code ThrottleCondition}s
+ */
+ public static List extractThrottleCondition(String base64EncodedString) {
+
+ List conditionDtoList = new ArrayList<>();
+ String base64Decoded = new String(Base64.decodeBase64(base64EncodedString));
+ JSONTokener tokener = new JSONTokener(base64Decoded);
+ JSONArray conditionJsonArray = new JSONArray(tokener);
+ for (Object conditionJson : conditionJsonArray) {
+ ThrottleCondition conditionDto = new ThrottleCondition();
+ JSONObject conditionJsonObject = (JSONObject) conditionJson;
+ if (conditionJsonObject.has(PolicyConstants.IP_SPECIFIC_TYPE.toLowerCase())) {
+ JSONObject ipSpecificCondition = (JSONObject) conditionJsonObject.get(PolicyConstants.IP_SPECIFIC_TYPE
+ .toLowerCase());
+ ThrottleCondition.IPCondition ipCondition = new Gson().fromJson(ipSpecificCondition.toString(),
+ ThrottleCondition.IPCondition.class);
+ conditionDto.setIpCondition(ipCondition);
+ } else if (conditionJsonObject.has(PolicyConstants.IP_RANGE_TYPE.toLowerCase())) {
+ JSONObject ipRangeCondition = (JSONObject) conditionJsonObject.get(PolicyConstants.IP_RANGE_TYPE
+ .toLowerCase());
+ ThrottleCondition.IPCondition ipCondition = new Gson().fromJson(ipRangeCondition.toString(),
+ ThrottleCondition.IPCondition.class);
+ conditionDto.setIpRangeCondition(ipCondition);
+ }
+ if (conditionJsonObject.has(PolicyConstants.JWT_CLAIMS_TYPE.toLowerCase())) {
+ JSONObject jwtClaimConditions = (JSONObject) conditionJsonObject.get(PolicyConstants.JWT_CLAIMS_TYPE
+ .toLowerCase());
+ ThrottleCondition.JWTClaimConditions jwtClaimCondition = new Gson().fromJson(jwtClaimConditions
+ .toString(), ThrottleCondition.JWTClaimConditions.class);
+ conditionDto.setJwtClaimConditions(jwtClaimCondition);
+ }
+ if (conditionJsonObject.has(PolicyConstants.HEADER_TYPE.toLowerCase())) {
+ JSONObject headerConditionJson = (JSONObject) conditionJsonObject.get(PolicyConstants.HEADER_TYPE
+ .toLowerCase());
+ ThrottleCondition.HeaderConditions headerConditions = new Gson().fromJson(headerConditionJson
+ .toString(), ThrottleCondition.HeaderConditions.class);
+ conditionDto.setHeaderConditions(headerConditions);
+ }
+
+ if (conditionJsonObject.has(PolicyConstants.QUERY_PARAMETER_TYPE.toLowerCase())) {
+ JSONObject queryParamConditionJson = (JSONObject) conditionJsonObject.get(PolicyConstants
+ .QUERY_PARAMETER_TYPE.toLowerCase());
+ ThrottleCondition.QueryParamConditions queryParamCondition = new Gson().fromJson(queryParamConditionJson
+ .toString(), ThrottleCondition.QueryParamConditions.class);
+ conditionDto.setQueryParameterConditions(queryParamCondition);
+ }
+ conditionDtoList.add(conditionDto);
+ }
+ conditionDtoList.sort((o1, o2) -> {
+
+ if (o1.getIpCondition() != null && o2.getIpCondition() == null) {
+ return -1;
+ } else if (o1.getIpCondition() == null && o2.getIpCondition() != null) {
+ return 1;
+ } else {
+ if (o1.getIpRangeCondition() != null && o2.getIpRangeCondition() == null) {
+ return -1;
+ } else if (o1.getIpRangeCondition() == null && o2.getIpRangeCondition() != null) {
+ return 1;
+ } else {
+ if (o1.getHeaderConditions() != null && o2.getHeaderConditions() == null) {
+ return -1;
+ } else if (o1.getHeaderConditions() == null && o2.getHeaderConditions() != null) {
+ return 1;
+ } else {
+ if (o1.getQueryParameterConditions() != null && o2.getQueryParameterConditions() == null) {
+ return -1;
+ } else if (o1.getQueryParameterConditions() == null && o2.getQueryParameterConditions()
+ != null) {
+ return 1;
+ } else {
+ if (o1.getJwtClaimConditions() != null && o2.getJwtClaimConditions() == null) {
+ return -1;
+ } else if (o1.getJwtClaimConditions() == null && o2.getJwtClaimConditions() != null) {
+ return 1;
+ }
+ }
+ }
+ }
+ }
+ return 0;
+ });
+
+ return conditionDtoList;
+ }
+
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/agent/AgentHolder.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/agent/AgentHolder.java
new file mode 100644
index 0000000000..522e3065e7
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/agent/AgentHolder.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle.databridge.agent;
+
+
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.conf.AgentConfiguration;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.exception.DataEndpointException;
+
+/**
+ * The holder the created agent and this is singleton class.
+ */
+public class AgentHolder {
+
+ private static AgentHolder instance;
+ private DataEndpointAgent agent;
+
+ private AgentHolder() {
+ agent = new DataEndpointAgent(AgentConfiguration.getInstance());
+ }
+
+ public static synchronized AgentHolder getInstance() {
+ if (instance == null) {
+ instance = new AgentHolder();
+ }
+ return instance;
+ }
+
+ public static synchronized void shutdown() throws DataEndpointException {
+ if (instance != null) {
+ instance.agent.shutDown();
+ instance = null;
+ }
+ }
+
+ /**
+ * Returns the default agent,and the first element in the data.agent.config.yaml
+ * is taken as default data publisher type.
+ *
+ * @return DataEndpointAgent for the default endpoint name.
+ */
+ public DataEndpointAgent getDataEndpointAgent() {
+ return agent;
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/agent/DataEndpointAgent.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/agent/DataEndpointAgent.java
new file mode 100644
index 0000000000..4a49316c95
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/agent/DataEndpointAgent.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.micro.gateway.enforcer.throttle.databridge.agent;
+
+import org.apache.commons.pool.impl.GenericKeyedObjectPool;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.client.AbstractClientPoolFactory;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.client.AbstractSecureClientPoolFactory;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.client.ClientPool;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.conf.AgentConfiguration;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.endpoint.DataEndpoint;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.endpoint.binary.BinaryClientPoolFactory;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.endpoint.binary.BinaryDataEndpoint;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.endpoint.binary.BinarySecureClientPoolFactory;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.exception.DataEndpointException;
+
+
+import java.util.ArrayList;
+
+/**
+ * One agent is created for a specific data endpoint type,and this has the resources such as transport pool, etc
+ * which are shared by all the data publishers created for the endpoint type.
+ */
+
+public class DataEndpointAgent {
+
+ private ArrayList dataPublishers = new ArrayList<>();
+
+ private GenericKeyedObjectPool transportPool;
+
+ private GenericKeyedObjectPool securedTransportPool;
+
+ private AgentConfiguration agentConfiguration;
+
+ public DataEndpointAgent(AgentConfiguration agentConfiguration) {
+ this.agentConfiguration = agentConfiguration;
+ initialize();
+ }
+
+ private void initialize() {
+ AbstractClientPoolFactory clientPoolFactory = new BinaryClientPoolFactory();
+ AbstractSecureClientPoolFactory secureClientPoolFactory = new BinarySecureClientPoolFactory(
+ agentConfiguration.getTrustStore());
+ ClientPool clientPool = new ClientPool();
+ this.transportPool = clientPool.getClientPool(
+ clientPoolFactory,
+ agentConfiguration.getMaxTransportPoolSize(),
+ agentConfiguration.getMaxIdleConnections(),
+ true,
+ agentConfiguration.getEvictionTimePeriod(),
+ agentConfiguration.getMinIdleTimeInPool());
+
+ this.securedTransportPool = clientPool.getClientPool(
+ secureClientPoolFactory,
+ agentConfiguration.getSecureMaxTransportPoolSize(),
+ agentConfiguration.getSecureMaxIdleConnections(),
+ true,
+ agentConfiguration.getSecureEvictionTimePeriod(),
+ agentConfiguration.getSecureMinIdleTimeInPool());
+ }
+
+ public void addDataPublisher(DataPublisher dataPublisher) {
+ dataPublishers.add(dataPublisher);
+ }
+
+ public AgentConfiguration getAgentConfiguration() {
+ return agentConfiguration;
+ }
+
+ public GenericKeyedObjectPool getTransportPool() {
+ return transportPool;
+ }
+
+ public GenericKeyedObjectPool getSecuredTransportPool() {
+ return securedTransportPool;
+ }
+
+ public synchronized void shutDown(DataPublisher dataPublisher) {
+ dataPublishers.remove(dataPublisher);
+ }
+
+ public DataEndpoint getNewDataEndpoint() {
+ return new BinaryDataEndpoint();
+ }
+
+ public synchronized void shutDown() throws DataEndpointException {
+ for (DataPublisher dataPublisher : dataPublishers) {
+ dataPublisher.shutdown();
+ }
+ try {
+ transportPool.close();
+ securedTransportPool.close();
+ } catch (Exception e) {
+ throw new DataEndpointException("Error while closing the transport pool", e);
+ }
+ }
+}
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/agent/DataPublisher.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/agent/DataPublisher.java
new file mode 100644
index 0000000000..bce852a144
--- /dev/null
+++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/agent/DataPublisher.java
@@ -0,0 +1,313 @@
+/*
+ * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.micro.gateway.enforcer.throttle.databridge.agent;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.wso2.carbon.databridge.commons.Event;
+import org.wso2.carbon.databridge.commons.exception.TransportException;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.conf.DataEndpointConfiguration;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.endpoint.DataEndpoint;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.endpoint.DataEndpointGroup;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.exception.DataEndpointAuthenticationException;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.exception.DataEndpointConfigurationException;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.exception.DataEndpointException;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.exception.EventQueueFullException;
+import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.util.DataPublisherUtil;
+
+
+
+import java.util.ArrayList;
+import java.util.Map;
+
+/**
+ * API Used to communicate with Data Receivers WSO2 BAM/CEP. It can be used to send events to
+ * multiple DAS/CEP nodes with load balancing and failover logic.
+ */
+public class DataPublisher {
+
+ private static final Logger log = LogManager.getLogger(DataPublisher.class);
+
+ /**
+ * List of group of endpoints where events needs to dispatched when
+ * events are published using this API.
+ */
+ private ArrayList endpointGroups = new ArrayList<>();
+
+ /**
+ * The Agent for which the data publisher belongs to.
+ */
+ private DataEndpointAgent dataEndpointAgent;
+
+ private static final int FAILED_EVENT_LOG_INTERVAL = 10000;
+
+ /**
+ * The last failed event time kept, use to determine when to log an warning
+ * message, without continuously doing so.
+ */
+ private long lastFailedEventTime;
+
+ /**
+ * The current failed event count. A normal long is used here, rather
+ * than an AtomicLong, since this is not a critical stat.
+ */
+ private long failedEventCount;
+
+ /**
+ * Creates the DataPublisher instance for a specific user, and the it creates
+ * connection asynchronously to receiver endpoint.
+ *
+ * @param receiverURLSet The receiving endpoint URL Set. This can be either load balancing URL set,
+ * or Failover URL set.
+ * @param authURLSet The authenticating URL Set for the endpoints given in receiverURLSet parameter.
+ * This should be in the same format as receiverURL set parameter. If null is passed
+ * the authURLs will be offsetted by value of 100.
+ * @param username Authorized username at receiver.
+ * @param password The password of the username provided.
+ * @throws DataEndpointException Exception to be thrown when communicating with DataEndpoint.
+ * @throws DataEndpointConfigurationException Exception to be thrown When parsing the Data Endpoint
+ * configurations when initializing data publisher
+ * @throws DataEndpointAuthenticationException Exception to be thrown when connecting the Data Endpoint
+ * @throws TransportException Transport level exception
+ */
+ public DataPublisher(String receiverURLSet, String authURLSet, String username, String password)
+ throws DataEndpointException, DataEndpointConfigurationException,
+ DataEndpointAuthenticationException, TransportException {
+ dataEndpointAgent = AgentHolder.getInstance().getDataEndpointAgent();
+ if (authURLSet == null) {
+ authURLSet = DataPublisherUtil.getDefaultAuthURLSet(receiverURLSet);
+ }
+ processEndpoints(dataEndpointAgent, receiverURLSet, authURLSet, username, password);
+ dataEndpointAgent.addDataPublisher(this);
+ }
+
+ /**
+ * This validates the input that are passed in the DataPublisher creation,
+ * and initiates the endpoints connection.
+ *
+ * @param dataEndpointAgent Agent of the DataPublisher.
+ * @param receiverURLSet The receiving endpoint URL Set. This can be either load balancing URL set,
+ * or Failover URL set.
+ * @param authURLSet The authenticating URL Set for the endpoints given in receiverURLSet parameter.
+ * This should be in the same format as receiverURL set parameter. If the authURLSet
+ * is null, then default authURLSet will be generated from the receiverURL.
+ * @param username Authorized username at receiver.
+ * @param password The password of the username provided.
+ * @throws DataEndpointConfigurationException Exception to be thrown When parsing the Data Endpoint
+ * configurations when initializing data publisher
+ * @throws DataEndpointException Exception to be thrown when communicating with DataEndpoint.
+ * @throws DataEndpointAuthenticationException Exception to be thrown when connecting the Data Endpoint
+ * @throws TransportException Transport level exception
+ */
+ private void processEndpoints(DataEndpointAgent dataEndpointAgent,
+ String receiverURLSet, String authURLSet, String username, String password)
+ throws DataEndpointConfigurationException, DataEndpointException,
+ DataEndpointAuthenticationException, TransportException {
+ ArrayList