diff options
Diffstat (limited to 'bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy')
5 files changed, 440 insertions, 174 deletions
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/LoggingFilter.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/LoggingFilter.java index 665b9052eb..e02941944a 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/LoggingFilter.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/LoggingFilter.java @@ -1,130 +1,138 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.client.policy;
-
-import java.io.BufferedInputStream;
-
-import java.io.ByteArrayOutputStream;
-import java.io.FilterOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import java.util.logging.Logger;
-import javax.annotation.Priority;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.client.ClientRequestContext;
-import javax.ws.rs.client.ClientRequestFilter;
-import javax.ws.rs.client.ClientResponseContext;
-import javax.ws.rs.client.ClientResponseFilter;
-import javax.ws.rs.ext.WriterInterceptor;
-import javax.ws.rs.ext.WriterInterceptorContext;
-
-@Priority(Integer.MIN_VALUE)
-public class LoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor {
-
- private static final Logger logger = Logger.getLogger(LoggingFilter.class.getName());
- private static final String ENTITY_STREAM_PROPERTY = "LoggingFilter.entityStream";
- private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
- private final int maxEntitySize = 1024 * 8;
-
- private void log(StringBuilder sb) {
- logger.info(sb.toString());
- }
-
- private InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset)
- throws IOException {
- InputStream inputStream = stream;
- if (!inputStream.markSupported()) {
- inputStream = new BufferedInputStream(inputStream);
- }
- inputStream.mark(maxEntitySize + 1);
- final byte[] entity = new byte[maxEntitySize + 1];
- final int entitySize = inputStream.read(entity);
- b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset));
- if (entitySize > maxEntitySize) {
- b.append("...more...");
- }
- b.append('\n');
- inputStream.reset();
- return inputStream;
- }
-
- @Override
- public void filter(ClientRequestContext requestContext) throws IOException {
- if (requestContext.hasEntity()) {
- final OutputStream stream = new LoggingStream(requestContext.getEntityStream());
- requestContext.setEntityStream(stream);
- requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream);
- }
- }
-
- @Override
- public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
- final StringBuilder sb = new StringBuilder();
- if (responseContext.hasEntity()) {
- responseContext.setEntityStream(logInboundEntity(sb, responseContext.getEntityStream(), DEFAULT_CHARSET));
- log(sb);
- }
-
- }
-
- @Override
- public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
- final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY);
- context.proceed();
- if (stream != null) {
- log(stream.getStringBuilder(DEFAULT_CHARSET));
- }
- }
-
- private class LoggingStream extends FilterOutputStream {
-
- private final StringBuilder sb = new StringBuilder();
- private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- LoggingStream(OutputStream out) {
- super(out);
- }
-
- StringBuilder getStringBuilder(Charset charset) {
- // write entity to the builder
- final byte[] entity = baos.toByteArray();
-
- sb.append(new String(entity, 0, entity.length, charset));
- if (entity.length > maxEntitySize) {
- sb.append("...more...");
- }
- sb.append('\n');
-
- return sb;
- }
-
- @Override
- public void write(final int i) throws IOException {
- if (baos.size() <= maxEntitySize) {
- baos.write(i);
- }
- out.write(i);
- }
- }
-}
+/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.client.policy; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.logging.Logger; + +import javax.annotation.Priority; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; + +@Priority(Integer.MIN_VALUE) +public class LoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor { + + private static final Logger logger = Logger.getLogger(LoggingFilter.class.getName()); + private static final String ENTITY_STREAM_PROPERTY = "LoggingFilter.entityStream"; + private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; + private final int maxEntitySize; + + public LoggingFilter() { + maxEntitySize = 1024 * 1024; + } + + public LoggingFilter(int maxPayloadSize) { + this.maxEntitySize = Integer.min(maxPayloadSize, 1024 * 1024); + } + + private void log(StringBuilder sb) { + logger.info(sb.toString()); + } + + private InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset) + throws IOException { + if (!stream.markSupported()) { + stream = new BufferedInputStream(stream); + } + stream.mark(maxEntitySize + 1); + final byte[] entity = new byte[maxEntitySize + 1]; + final int entitySize = stream.read(entity); + if (entitySize != -1) { + b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset)); + } + if (entitySize > maxEntitySize) { + b.append("...more..."); + } + b.append('\n'); + stream.reset(); + return stream; + } + + @Override + public void filter(ClientRequestContext requestContext) throws IOException { + if (requestContext.hasEntity()) { + final OutputStream stream = new LoggingStream(requestContext.getEntityStream()); + requestContext.setEntityStream(stream); + requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream); + } + } + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + final StringBuilder sb = new StringBuilder(); + if (responseContext.hasEntity()) { + responseContext.setEntityStream(logInboundEntity(sb, responseContext.getEntityStream(), DEFAULT_CHARSET)); + log(sb); + } + } + + @Override + public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { + final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY); + context.proceed(); + if (stream != null) { + log(stream.getStringBuilder(DEFAULT_CHARSET)); + } + } + + private class LoggingStream extends FilterOutputStream { + + private final StringBuilder sb = new StringBuilder(); + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + LoggingStream(OutputStream out) { + super(out); + } + + StringBuilder getStringBuilder(Charset charset) { + // write entity to the builder + final byte[] entity = baos.toByteArray(); + + sb.append(new String(entity, 0, entity.length, charset)); + if (entity.length > maxEntitySize) { + sb.append("...more..."); + } + sb.append('\n'); + + return sb; + } + + @Override + public void write(final int i) throws IOException { + if (baos.size() <= maxEntitySize) { + baos.write(i); + } + out.write(i); + } + } +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestClient.java index 71ae56f55b..4ed2a887ef 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestClient.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestClient.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * ONAP - SO + * OPENECOMP - MSO * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -20,50 +20,47 @@ package org.openecomp.mso.client.policy; +import java.net.MalformedURLException; import java.util.Map; +import java.util.Optional; import java.util.UUID; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriBuilderException; +import org.openecomp.mso.client.ResponseExceptionMapperImpl; +import org.openecomp.mso.client.RestProperties; +import org.openecomp.mso.client.policy.entities.PolicyServiceType; import org.springframework.stereotype.Service; @Service public class PolicyRestClient extends RestClient { - private static final String ENDPOINT_KEY = "policy.endpoint"; private static final String X_ECOMP_REQUESTID = String.valueOf(UUID.randomUUID()); - - public PolicyRestClient() { - super(ENDPOINT_KEY); + private final PolicyRestProperties properties; + public PolicyRestClient(PolicyRestProperties props, PolicyServiceType serviceType) { + super(props, Optional.of(UriBuilder.fromPath(serviceType.toString()).build())); + this.properties = props; + this.getClient(); } @Override protected void initializeHeaderMap(Map<String, String> headerMap) { - headerMap.put("ClientAuth", properties.get("policy.client.auth")); - headerMap.put("Authorization", properties.get("policy.auth")); - headerMap.put("Environment", properties.get("policy.environment")); - headerMap.put("X-ECOMP-RequestID", X_ECOMP_REQUESTID); + headerMap.put("ClientAuth", properties.getClientAuth()); + headerMap.put("Authorization", properties.getAuth()); + headerMap.put("Environment", properties.getEnvironment()); + this.addRequestId(X_ECOMP_REQUESTID); } - public PolicyDecision getDecision(String serviceType, String vnfType, String bbID, String workStep, - String errorCode) { - DecisionAttributes decisionAttributes = new DecisionAttributes(); - decisionAttributes.setServiceType(serviceType); - decisionAttributes.setVNFType(vnfType); - decisionAttributes.setBBID(bbID); - decisionAttributes.setWorkStep(workStep); - decisionAttributes.setErrorCode(errorCode); - - return this.getDecision(decisionAttributes); + @Override + protected Optional<ClientResponseFilter> addResponseFilter() { + return Optional.of(new ResponseExceptionMapperImpl()); } - private PolicyDecision getDecision(DecisionAttributes decisionAttributes) { - PolicyDecisionRequest decisionRequest = new PolicyDecisionRequest(); - decisionRequest.setDecisionAttributes(decisionAttributes); - decisionRequest.setEcompcomponentName(ECOMP_COMPONENT_NAME); - - return this.getBuilder().accept(MediaType.APPLICATION_JSON_TYPE) - .post(Entity.entity(decisionRequest, MediaType.APPLICATION_JSON)).readEntity(PolicyDecision.class); + @Override + public RestClient addRequestId(String requestId) { + this.headerMap.put("X-ECOMP-RequestID", requestId); + return this; } }
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestProperties.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestProperties.java new file mode 100644 index 0000000000..d9336768fc --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestProperties.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.client.policy; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Map; + +import org.openecomp.mso.bpmn.core.PropertyConfiguration; +import org.openecomp.mso.client.RestProperties; + +public class PolicyRestProperties implements RestProperties { + + + final Map<String, String> props; + public PolicyRestProperties() { + this.props = PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties"); + + } + @Override + public URL getEndpoint() { + try { + return new URL(props.getOrDefault("policy.endpoint", "")); + } catch (MalformedURLException e) { + return null; + } + } + + @Override + public String getSystemName() { + return "MSO"; + } + + public String getClientAuth() { + return props.get("policy.client.auth"); + } + + public String getAuth() { + return props.get("policy.auth"); + } + + public String getEnvironment() { + return props.get("policy.environment"); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/RestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/RestClient.java index 81c072ff33..74b1c3f802 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/RestClient.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/RestClient.java @@ -20,51 +20,104 @@ package org.openecomp.mso.client.policy; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import java.util.logging.Logger; +import java.util.Optional; +import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.ext.ContextResolver; - -import org.openecomp.mso.bpmn.core.PropertyConfiguration; +import org.apache.log4j.Logger; +import org.openecomp.mso.client.RestProperties; import org.openecomp.mso.logger.MsoLogger; import org.springframework.stereotype.Service; +import com.fasterxml.jackson.databind.ObjectMapper; + @Service public abstract class RestClient { protected static final String ECOMP_COMPONENT_NAME = "MSO"; - + + private static final int MAX_PAYLOAD_SIZE = 1024 * 1024; private WebTarget webTarget; protected final Map<String, String> headerMap; protected final MsoLogger msoLogger; - protected Map<String, String> properties; - protected String host; + protected URL host; + protected Optional<URI> path; + protected Logger logger; + protected String accept; + protected String contentType; - protected RestClient(String endpointKey) { - Logger logger = Logger.getLogger(getClass().getName()); + protected RestClient(RestProperties props, Optional<URI> path) { + logger = Logger.getLogger(getClass().getName()); msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); - - properties = PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties"); + headerMap = new HashMap<>(); - initializeHeaderMap(headerMap); + try { + host = props.getEndpoint(); + } catch (MalformedURLException e) { + logger.error("url not valid", e); + throw new RuntimeException(e); + } + + this.path = path; + initializeClient(getClient()); + } - host = this.getHost(endpointKey); + protected RestClient(RestProperties props, Optional<URI> path, String accept, String contentType) { + this(props, path); + this.accept = accept; + this.contentType = contentType; - webTarget = ClientBuilder.newClient().register(logger).register(new LoggingFilter()) - .register(new CommonObjectMapperProvider()).target(host); } - private String getHost(String key) { - return properties.get(key); + protected RestClient(URL host, String contentType) { + headerMap = new HashMap<>(); + logger = Logger.getLogger(getClass().getName()); + msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + this.path = Optional.empty(); + this.host = host; + this.contentType = contentType; + initializeClient(getClient()); + } + + /** + * Override method to return false to disable logging. + * + * @return true - to enable logging, false otherwise + */ + protected boolean enableLogging() { + return true; + } + + /** + * Override method to return custom value for max payload size. + * + * @return Default value for MAX_PAYLOAD_SIZE = 1024 * 1024 + */ + protected int getMaxPayloadSize() + { + return MAX_PAYLOAD_SIZE; } protected Builder getBuilder() { + Builder builder = webTarget.request(); + initializeHeaderMap(headerMap); for (Entry<String, String> entry : headerMap.entrySet()) { builder.header(entry.getKey(), entry.getValue()); @@ -73,4 +126,100 @@ public abstract class RestClient { } protected abstract void initializeHeaderMap(Map<String, String> headerMap); + + protected abstract Optional<ClientResponseFilter> addResponseFilter(); + + public abstract RestClient addRequestId(String requestId); + + protected ContextResolver<ObjectMapper> getMapper() { + return new CommonObjectMapperProvider(); + } + + protected String getAccept() { + return accept; + } + + protected String getContentType() { + return contentType; + } + + protected String getMergeContentType() { + return "application/merge-patch+json"; + } + + protected Client getClient() { + return ClientBuilder.newBuilder().build(); + } + + protected void initializeClient(Client client) { + if (this.enableLogging()) { + client.register(logger).register(new LoggingFilter(this.getMaxPayloadSize())); + } + client.register(this.getMapper()); + Optional<ClientResponseFilter> responseFilter = this.addResponseFilter(); + if (responseFilter.isPresent()) { + client.register(responseFilter.get()); + } + if (!path.isPresent()) { + webTarget = client.target(host.toString()); + } else { + webTarget = client.target(UriBuilder.fromUri(host + path.get().toString())); + } + this.accept = MediaType.APPLICATION_JSON; + this.contentType = MediaType.APPLICATION_JSON; + } + + public Response get() { + return this.getBuilder().accept(this.getAccept()).get(); + } + + public Response post(Object obj) { + return this.getBuilder().accept(this.getAccept()).post(Entity.entity(obj, this.getContentType())); + } + + public Response patch(Object obj) { + return this.getBuilder().header("X-HTTP-Method-Override", "PATCH").accept(this.getAccept()) + .post(Entity.entity(obj, this.getMergeContentType())); + } + + public Response put(Object obj) { + return this.getBuilder().accept(this.getAccept()).put(Entity.entity(obj, this.getContentType())); + } + + public Response delete() { + return this.getBuilder().accept(this.getAccept()).delete(); + } + + public Response delete(Object obj) { + return this.getBuilder().header("X-HTTP-Method-Override", "DELETE").accept(this.getAccept()) + .put(Entity.entity(obj, this.getContentType())); + } + + public <T> T get(Class<T> resultClass) { + return this.get().readEntity(resultClass); + } + + public <T> T get(GenericType<T> resultClass) { + return this.get().readEntity(resultClass); + } + + public <T> T post(Object obj, Class<T> resultClass) { + return this.post(obj).readEntity(resultClass); + } + + public <T> T patch(Object obj, Class<T> resultClass) { + return this.patch(obj).readEntity(resultClass); + } + + public <T> T put(Object obj, Class<T> resultClass) { + return this.put(obj).readEntity(resultClass); + } + + public <T> T delete(Class<T> resultClass) { + return this.delete().readEntity(resultClass); + } + + public <T> T delete(Object obj, Class<T> resultClass) { + return this.delete(obj).readEntity(resultClass); + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/entities/PolicyServiceType.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/entities/PolicyServiceType.java new file mode 100644 index 0000000000..b5ab63ce35 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/entities/PolicyServiceType.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.client.policy.entities; + +public enum PolicyServiceType { + GET_CONFIG("getConfig"), + SEND_EVENT("sendEvent"), + PUSH_POLICY("pushPolicy"), + CREATE_POLICY("createPolicy"), + UPDATE_POLICY("updatePolicy"), + GET_DECISION("getDecision"), + GET_METRICS("getMetrics"), + DELETE_POLICY("deletePolicy"), + LIST_CONFIG("listConfig"), + CREATE_DICTIONARY_ITEM("createDictionaryItem"), + UPDATE_DICTIONARY_ITEM("updateDictionaryItem"), + GET_DICTIONARY_ITEMS("getDictionaryItems"); + + private final String name; + + private PolicyServiceType(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } + +} |