index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/TimeWindowEventResponse.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.List; import java.util.Map; /** * Response type to return a new state for the time window and to report batch item failures. This should be used along with {@link KinesisTimeWindowEvent} or {@link DynamodbTimeWindowEvent}. * https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html#services-kinesis-windows */ @Data @NoArgsConstructor @AllArgsConstructor @Builder(setterPrefix = "with") public class TimeWindowEventResponse implements Serializable { private static final long serialVersionUID = 2259096191791166028L; /** * New state after processing a batch of records. */ private Map<String, String> state; /** * A list of records which failed processing. Returning the first record which failed would retry all remaining records from the batch. */ private List<BatchItemFailure> batchItemFailures; @Data @NoArgsConstructor @AllArgsConstructor @Builder(setterPrefix = "with") public static class BatchItemFailure implements Serializable { private static final long serialVersionUID = 5224634072234167773L; /** * Sequence number of the record which failed processing. */ String itemIdentifier; } }
1,800
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/StreamsEventResponse.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.List; /** * Function response type to report batch item failures for {@link KinesisEvent} and {@link DynamodbEvent}. * https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html#services-kinesis-batchfailurereporting */ @Data @NoArgsConstructor @AllArgsConstructor @Builder(setterPrefix = "with") public class StreamsEventResponse implements Serializable { private static final long serialVersionUID = 3232053116472095907L; /** * A list of records which failed processing. Returning the first record which failed would retry all remaining records from the batch. */ private List<BatchItemFailure> batchItemFailures; @Data @NoArgsConstructor @AllArgsConstructor @Builder(setterPrefix = "with") public static class BatchItemFailure implements Serializable { private static final long serialVersionUID = 1473983466096085881L; /** * Sequence number of the record which failed processing. */ String itemIdentifier; } }
1,801
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/LambdaDestinationEvent.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.joda.time.DateTime; import java.io.Serializable; import java.util.Map; /** * Class to represent an invocation record for a Lambda event. * * @see <a href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html>Asynchronous invocation</a> * * @author msailes <msailes@amazon.co.uk> */ @Data @Builder(setterPrefix = "with") @NoArgsConstructor @AllArgsConstructor public class LambdaDestinationEvent implements Serializable, Cloneable { private String version; private DateTime timestamp; private RequestContext requestContext; private Map<String, Object> requestPayload; private Object responseContext; private Object responsePayload; @Data @Builder(setterPrefix = "with") @NoArgsConstructor @AllArgsConstructor public static class RequestContext implements Serializable, Cloneable { private String requestId; private String functionArn; private String condition; private int approximateInvokeCount; } }
1,802
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/ApplicationLoadBalancerResponseEvent.java
package com.amazonaws.services.lambda.runtime.events; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.List; import java.util.Map; /** * Class to represent the response event to Application Load Balancer. * * @see <a href="https://docs.aws.amazon.com/lambda/latest/dg/services-alb.html">Using AWS Lambda with an Application Load Balancer</a> * * @author msailes <msailes@amazon.co.uk> */ @NoArgsConstructor @Data public class ApplicationLoadBalancerResponseEvent implements Serializable, Cloneable { private int statusCode; private String statusDescription; private boolean isBase64Encoded; private Map<String, String> headers; private Map<String, List<String>> multiValueHeaders; private String body; }
1,803
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/AppSyncLambdaAuthorizerResponse.java
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events; import java.util.Map; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * Class that represents the output from an AppSync Lambda authorizer invocation. */ @Data @Builder(setterPrefix = "with") @NoArgsConstructor @AllArgsConstructor public class AppSyncLambdaAuthorizerResponse { private boolean isAuthorized; private Map<String, String> resolverContext; private List<String> deniedFields; private int ttlOverride; }
1,804
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/S3BatchEvent.java
package com.amazonaws.services.lambda.runtime.events; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; /** * Event to represent the payload which is sent to Lambda by S3 Batch to perform a custom * action. * * https://docs.aws.amazon.com/AmazonS3/latest/dev/batch-ops-invoke-lambda.html */ @Data @Builder(setterPrefix = "with") @NoArgsConstructor @AllArgsConstructor public class S3BatchEvent { private String invocationSchemaVersion; private String invocationId; private Job job; private List<Task> tasks; @Data @Builder(setterPrefix = "with") @NoArgsConstructor @AllArgsConstructor public static class Job { private String id; } @Data @Builder(setterPrefix = "with") @NoArgsConstructor @AllArgsConstructor public static class Task { private String taskId; private String s3Key; private String s3VersionId; private String s3BucketArn; } }
1,805
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/SNSEvent.java
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events; import org.joda.time.DateTime; import java.io.Serializable; import java.util.List; import java.util.Map; /** * Represents an Amazon SNS event. */ public class SNSEvent implements Serializable, Cloneable { private static final long serialVersionUID = -727529735144605167L; private List<SNSRecord> records; /** * Represents an SNS message attribute * */ public static class MessageAttribute implements Serializable, Cloneable { private static final long serialVersionUID = -5656179310535967619L; private String type; private String value; /** * default constructor * (not available in v1) */ public MessageAttribute() {} /** * Gets the attribute type * @return type */ public String getType() { return type; } /** * Sets the attribute type * @param type A string representing the attribute type */ public void setType(String type) { this.type = type; } /** * @param type type * @return MessageAttribute */ public MessageAttribute withType(String type) { setType(type); return this; } /** * Gets the attribute value * @return value */ public String getValue() { return value; } /** * Sets the attribute value * @param value A string containing the attribute value */ public void setValue(String value) { this.value = value; } /** * @param value attriute value * @return MessageAttribute */ public MessageAttribute withValue(String value) { setValue(value); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getType() != null) sb.append("type: ").append(getType()).append(","); if (getValue() != null) sb.append("value: ").append(getValue()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof MessageAttribute == false) return false; MessageAttribute other = (MessageAttribute) obj; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getValue() == null ^ this.getValue() == null) return false; if (other.getValue() != null && other.getValue().equals(this.getValue()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getValue() == null) ? 0 : getValue().hashCode()); return hashCode; } @Override public MessageAttribute clone() { try { return (MessageAttribute) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone()", e); } } } /** * Represents an SNS message */ public static class SNS implements Serializable, Cloneable { private static final long serialVersionUID = -7038894618736475592L; private Map<String, MessageAttribute> messageAttributes; private String signingCertUrl; private String messageId; private String message; private String subject; private String unsubscribeUrl; private String type; private String signatureVersion; private String signature; private DateTime timestamp; private String topicArn; /** * default constructor * (Not available in v1) */ public SNS() {} /** * Gets the attributes associated with the message * @return message attributes */ public Map<String, MessageAttribute> getMessageAttributes() { return messageAttributes; } /** * Sets the attributes associated with the message * @param messageAttributes A map object with string and message attribute key/value pairs */ public void setMessageAttributes( Map<String, MessageAttribute> messageAttributes) { this.messageAttributes = messageAttributes; } /** * @param messageAttributes message attributes * @return SNS */ public SNS withMessageAttributes(Map<String, MessageAttribute> messageAttributes) { setMessageAttributes(messageAttributes); return this; } /** * Gets the URL for the signing certificate * @return signing certificate url */ public String getSigningCertUrl() { return signingCertUrl; } /** * Sets the URL for the signing certificate * @param signingCertUrl A string containing a URL */ public void setSigningCertUrl(String signingCertUrl) { this.signingCertUrl = signingCertUrl; } /** * @param signingCertUrl signing cert url * @return SNS */ public SNS withSigningCertUrl(String signingCertUrl) { setSigningCertUrl(signingCertUrl); return this; } /** * Gets the message id * @return message id */ public String getMessageId() { return messageId; } /** * Sets the message id * @param messageId A string containing the message ID */ public void setMessageId(String messageId) { this.messageId = messageId; } /** * @param messageId message id * @return SNS */ public SNS withMessageId(String messageId) { setMessageId(messageId); return this; } /** * Gets the message * @return message string */ public String getMessage() { return message; } /** * Sets the message * @param message A string containing the message body */ public void setMessage(String message) { this.message = message; } /** * @param message string message * @return SNS */ public SNS withMessage(String message) { setMessage(message); return this; } /** * Gets the subject for the message * @return subject of message */ public String getSubject() { return subject; } /** * Sets the subject for the message * @param subject A string containing the message subject */ public void setSubject(String subject) { this.subject = subject; } /** * @param subject subject of message * @return SNS */ public SNS withSubject(String subject) { setSubject(subject); return this; } /** * Gets the message unsubscribe URL * @return unsubscribe url */ public String getUnsubscribeUrl() { return unsubscribeUrl; } /** * Sets the message unsubscribe URL * @param unsubscribeUrl A string with the URL */ public void setUnsubscribeUrl(String unsubscribeUrl) { this.unsubscribeUrl = unsubscribeUrl; } /** * @param unsubscribeUrl unsubscribe url * @return SNS */ public SNS withUnsubscribeUrl(String unsubscribeUrl) { setUnsubscribeUrl(unsubscribeUrl); return this; } /** * Gets the message type * @return message type */ public String getType() { return type; } /** * Sets the message type * @param type A string containing the message type */ public void setType(String type) { this.type = type; } /** * @param type type * @return SNS */ public SNS withType(String type) { setType(type); return this; } /** * Gets the signature version used to sign the message * @return signature version */ public String getSignatureVersion() { return signatureVersion; } /** * The signature version used to sign the message * @param signatureVersion A string containing the signature version */ public void setSignatureVersion(String signatureVersion) { this.signatureVersion = signatureVersion; } /** * @param signatureVersion signature version * @return SNS */ public SNS withSignatureVersion(String signatureVersion) { setSignatureVersion(signatureVersion); return this; } /** * Gets the message signature * @return message signature */ public String getSignature() { return signature; } /** * Sets the message signature * @param signature A string containing the message signature */ public void setSignature(String signature) { this.signature = signature; } /** * @param signature signature * @return SNS */ public SNS withSignature(String signature) { setSignature(signature); return this; } /** * Gets the message time stamp * @return timestamp of sns message */ public DateTime getTimestamp() { return timestamp; } /** * Sets the message time stamp * @param timestamp A Date object representing the message time stamp */ public void setTimestamp(DateTime timestamp) { this.timestamp = timestamp; } /** * @param timestamp timestamp * @return SNS */ public SNS withTimestamp(DateTime timestamp) { setTimestamp(timestamp); return this; } /** * Gets the topic ARN * @return topic arn */ public String getTopicArn() { return topicArn; } /** * Sets the topic ARN * @param topicArn A string containing the topic ARN */ public void setTopicArn(String topicArn) { this.topicArn = topicArn; } /** * @param topicArn topic ARN * @return SNS */ public SNS withTopicArn(String topicArn) { setTopicArn(topicArn); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMessageAttributes() != null) sb.append("messageAttributes: ").append(getMessageAttributes().toString()).append(","); if (getSigningCertUrl() != null) sb.append("signingCertUrl: ").append(getSigningCertUrl()).append(","); if (getMessageId() != null) sb.append("messageId: ").append(getMessageId()).append(","); if (getMessage() != null) sb.append("message: ").append(getMessage()).append(","); if (getSubject() != null) sb.append("subject: ").append(getSubject()).append(","); if (getUnsubscribeUrl() != null) sb.append("unsubscribeUrl: ").append(getUnsubscribeUrl()).append(","); if (getType() != null) sb.append("type: ").append(getType()).append(","); if (getSignatureVersion() != null) sb.append("signatureVersion: ").append(getSignatureVersion()).append(","); if (getSignature() != null) sb.append("signature: ").append(getSignature()).append(","); if (getTimestamp() != null) sb.append("timestamp: ").append(getTimestamp().toString()).append(","); if (getTopicArn() != null) sb.append("topicArn: ").append(getTopicArn()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof SNS == false) return false; SNS other = (SNS) obj; if (other.getMessageAttributes() == null ^ this.getMessageAttributes() == null) return false; if (other.getMessageAttributes() != null && other.getMessageAttributes().equals(this.getMessageAttributes()) == false) return false; if (other.getSigningCertUrl() == null ^ this.getSigningCertUrl() == null) return false; if (other.getSigningCertUrl() != null && other.getSigningCertUrl().equals(this.getSigningCertUrl()) == false) return false; if (other.getMessageId() == null ^ this.getMessageId() == null) return false; if (other.getMessageId() != null && other.getMessageId().equals(this.getMessageId()) == false) return false; if (other.getMessage() == null ^ this.getMessage() == null) return false; if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false) return false; if (other.getSubject() == null ^ this.getSubject() == null) return false; if (other.getSubject() != null && other.getSubject().equals(this.getSubject()) == false) return false; if (other.getUnsubscribeUrl() == null ^ this.getUnsubscribeUrl() == null) return false; if (other.getUnsubscribeUrl() != null && other.getUnsubscribeUrl().equals(this.getUnsubscribeUrl()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getSignatureVersion() == null ^ this.getSignatureVersion() == null) return false; if (other.getSignatureVersion() != null && other.getSignatureVersion().equals(this.getSignatureVersion()) == false) return false; if (other.getSignature() == null ^ this.getSignature() == null) return false; if (other.getSignature() != null && other.getSignature().equals(this.getSignature()) == false) return false; if (other.getTimestamp() == null ^ this.getTimestamp() == null) return false; if (other.getTimestamp() != null && other.getTimestamp().equals(this.getTimestamp()) == false) return false; if (other.getTopicArn() == null ^ this.getTopicArn() == null) return false; if (other.getTopicArn() != null && other.getTopicArn().equals(this.getTopicArn()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMessageAttributes() == null) ? 0 : getMessageAttributes().hashCode()); hashCode = prime * hashCode + ((getSigningCertUrl() == null) ? 0 : getSigningCertUrl().hashCode()); hashCode = prime * hashCode + ((getMessageId() == null) ? 0 : getMessageId().hashCode()); hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode()); hashCode = prime * hashCode + ((getSubject() == null) ? 0 : getSubject().hashCode()); hashCode = prime * hashCode + ((getUnsubscribeUrl() == null) ? 0 : getUnsubscribeUrl().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getSignatureVersion() == null) ? 0 : getSignatureVersion().hashCode()); hashCode = prime * hashCode + ((getSignature() == null) ? 0 : getSignature().hashCode()); hashCode = prime * hashCode + ((getTimestamp() == null) ? 0 : getTimestamp().hashCode()); hashCode = prime * hashCode + ((getTopicArn() == null) ? 0 : getTopicArn().hashCode()); return hashCode; } @Override public SNS clone() { try { return (SNS) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone()", e); } } } /** * Represents an SNS message record. SNS message records are used to send * SNS messages to Lambda Functions. * */ public static class SNSRecord implements Serializable, Cloneable { private static final long serialVersionUID = -209065548155161859L; private SNS sns; private String eventVersion; private String eventSource; private String eventSubscriptionArn; /** * default constructor * (Not available in v1) */ public SNSRecord() {} /** * Gets the SNS message * @return sns body of message */ public SNS getSNS() { return sns; } /** * Sets the SNS message * @param sns An SNS object representing the SNS message */ public void setSns(SNS sns) { this.sns = sns; } /** * @param sns SNS message object * @return SNSRecord */ public SNSRecord withSns(SNS sns) { setSns(sns); return this; } /** * Gets the event version * @return event version */ public String getEventVersion() { return eventVersion; } /** * Sets the event version * @param eventVersion A string containing the event version */ public void setEventVersion(String eventVersion) { this.eventVersion = eventVersion; } /** * @param eventVersion event version * @return SNSRecord */ public SNSRecord withEventVersion(String eventVersion) { setEventVersion(eventVersion); return this; } /** * Gets the event source * @return event source */ public String getEventSource() { return eventSource; } /** * Sets the event source * @param eventSource A string containing the event source */ public void setEventSource(String eventSource) { this.eventSource = eventSource; } /** * @param eventSource event source * @return SNSRecord */ public SNSRecord withEventSource(String eventSource) { setEventSource(eventSource); return this; } /** * Gets the event subscription ARN * @return event subscription arn */ public String getEventSubscriptionArn() { return eventSubscriptionArn; } /** * Sets the event subscription ARN * @param eventSubscriptionArn A string containing the event subscription ARN */ public void setEventSubscriptionArn(String eventSubscriptionArn) { this.eventSubscriptionArn = eventSubscriptionArn; } /** * @param eventSubscriptionArn event subscription arn * @return SNSRecord */ public SNSRecord withEventSubscriptionArn(String eventSubscriptionArn) { setEventSubscriptionArn(eventSubscriptionArn); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSNS() != null) sb.append("sns: ").append(getSNS().toString()).append(","); if (getEventVersion() != null) sb.append("eventVersion: ").append(getEventVersion()).append(","); if (getEventSource() != null) sb.append("eventSource: ").append(getEventSource()).append(","); if (getEventSubscriptionArn() != null) sb.append("eventSubscriptionArn: ").append(getEventSubscriptionArn()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof SNSRecord == false) return false; SNSRecord other = (SNSRecord) obj; if (other.getSNS() == null ^ this.getSNS() == null) return false; if (other.getSNS() != null && other.getSNS().equals(this.getSNS()) == false) return false; if (other.getEventVersion() == null ^ this.getEventVersion() == null) return false; if (other.getEventVersion() != null && other.getEventVersion().equals(this.getEventVersion()) == false) return false; if (other.getEventSource() == null ^ this.getEventSource() == null) return false; if (other.getEventSource() != null && other.getEventSource().equals(this.getEventSource()) == false) return false; if (other.getEventSubscriptionArn() == null ^ this.getEventSubscriptionArn() == null) return false; if (other.getEventSubscriptionArn() != null && other.getEventSubscriptionArn().equals(this.getEventSubscriptionArn()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSNS() == null) ? 0 : getSNS().hashCode()); hashCode = prime * hashCode + ((getEventVersion() == null) ? 0 : getEventVersion().hashCode()); hashCode = prime * hashCode + ((getEventSource() == null) ? 0 : getEventSource().hashCode()); hashCode = prime * hashCode + ((getEventSubscriptionArn() == null) ? 0 : getEventSubscriptionArn().hashCode()); return hashCode; } @Override public SNSRecord clone() { try { return (SNSRecord) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone()", e); } } } /** * default constructor * (Not available in v1) */ public SNSEvent() {} /** * Gets the list of SNS records * @return List of records */ public List<SNSRecord> getRecords() { return records; } /** * Sets a list of SNS records * @param records A list of SNS record objects */ public void setRecords(List<SNSRecord> records) { this.records = records; } /** * @param records a List of SNSRecords * @return SNSEvent */ public SNSEvent withRecords(List<SNSRecord> records) { setRecords(records); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRecords() != null) sb.append(getRecords()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof SNSEvent == false) return false; SNSEvent other = (SNSEvent) obj; if (other.getRecords() == null ^ this.getRecords() == null) return false; if (other.getRecords() != null && other.getRecords().equals(this.getRecords()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRecords() == null) ? 0 : getRecords().hashCode()); return hashCode; } @Override public SNSEvent clone() { try { return (SNSEvent) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone()", e); } } }
1,806
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/ActiveMQEvent.java
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.List; import java.util.Map; /** * Represents an Active MQ event sent to Lambda * <a href="https://docs.aws.amazon.com/lambda/latest/dg/with-mq.html">Onboarding Amazon MQ as event source to Lambda</a> */ @Data @NoArgsConstructor @AllArgsConstructor @Builder(setterPrefix = "with") public class ActiveMQEvent { private String eventSource; private String eventSourceArn; private List<ActiveMQMessage> messages; @Data @NoArgsConstructor @AllArgsConstructor @Builder(setterPrefix = "with") public static class ActiveMQMessage { private String messageID; private String messageType; private long timestamp; private int deliveryMode; private String correlationID; private String replyTo; private Destination destination; private boolean redelivered; private String type; private long expiration; private int priority; /** Message data sent to Active MQ broker encooded in Base 64 **/ private String data; private long brokerInTime; private long brokerOutTime; private Map<String, String> properties; } @Data @NoArgsConstructor @AllArgsConstructor @Builder(setterPrefix = "with") public static class Destination { /** Queue Name **/ private String physicalName; } }
1,807
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/DynamodbEvent.java
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events; import java.io.Serializable; import java.util.List; /** * Represents an Amazon DynamoDB event */ public class DynamodbEvent implements Serializable, Cloneable { private static final long serialVersionUID = -2354616079899981231L; private List<DynamodbStreamRecord> records; /** * The unit of data of an Amazon DynamoDB event */ public static class DynamodbStreamRecord extends com.amazonaws.services.lambda.runtime.events.models.dynamodb.Record { private static final long serialVersionUID = 3638381544604354963L; private String eventSourceARN; /** * default constructor * (Not available in v1) */ public DynamodbStreamRecord() {} /** * Gets the event source arn of DynamoDB * @return event source arn */ public String getEventSourceARN() { return eventSourceARN; } /** * Sets the event source arn of DynamoDB * @param eventSourceARN A string containing the event source arn */ public void setEventSourceARN(String eventSourceARN) { this.eventSourceARN = eventSourceARN; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getEventID() != null) sb.append("eventID: ").append(getEventID()).append(","); if (getEventName() != null) sb.append("eventName: ").append(getEventName()).append(","); if (getEventVersion() != null) sb.append("eventVersion: ").append(getEventVersion()).append(","); if (getEventSource() != null) sb.append("eventSource: ").append(getEventSource()).append(","); if (getAwsRegion() != null) sb.append("awsRegion: ").append(getAwsRegion()).append(","); if (getDynamodb() != null) sb.append("dynamodb: ").append(getDynamodb()).append(","); if (getUserIdentity() != null) sb.append("userIdentity: ").append(getUserIdentity()).append(","); if (getEventSourceARN() != null) sb.append("eventSourceArn: ").append(getEventSourceARN()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DynamodbStreamRecord == false) return false; DynamodbStreamRecord other = (DynamodbStreamRecord) obj; if (other.getEventID() == null ^ this.getEventID() == null) return false; if (other.getEventID() != null && other.getEventID().equals(this.getEventID()) == false) return false; if (other.getEventName() == null ^ this.getEventName() == null) return false; if (other.getEventName() != null && other.getEventName().equals(this.getEventName()) == false) return false; if (other.getEventVersion() == null ^ this.getEventVersion() == null) return false; if (other.getEventVersion() != null && other.getEventVersion().equals(this.getEventVersion()) == false) return false; if (other.getEventSource() == null ^ this.getEventSource() == null) return false; if (other.getEventSource() != null && other.getEventSource().equals(this.getEventSource()) == false) return false; if (other.getAwsRegion() == null ^ this.getAwsRegion() == null) return false; if (other.getAwsRegion() != null && other.getAwsRegion().equals(this.getAwsRegion()) == false) return false; if (other.getDynamodb() == null ^ this.getDynamodb() == null) return false; if (other.getDynamodb() != null && other.getDynamodb().equals(this.getDynamodb()) == false) return false; if (other.getUserIdentity() == null ^ this.getUserIdentity() == null) return false; if (other.getUserIdentity() != null && other.getUserIdentity().equals(this.getUserIdentity()) == false) return false; if (other.getEventSourceARN() == null ^ this.getEventSourceARN() == null) return false; if (other.getEventSourceARN() != null && other.getEventSourceARN().equals(this.getEventSourceARN()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = super.hashCode(); hashCode = prime * hashCode + ((getEventSourceARN() == null) ? 0 : getEventSourceARN().hashCode()); return hashCode; } @Override public DynamodbStreamRecord clone() { return (DynamodbStreamRecord) super.clone(); } } /** * default constructor * (Not available in v1) */ public DynamodbEvent() {} /** * Gets the list of DynamoDB event records * @return list of dynamodb event records */ public List<DynamodbStreamRecord> getRecords() { return records; } /** * Sets the list of DynamoDB event records * @param records a list of DynamoDb event records */ public void setRecords(List<DynamodbStreamRecord> records) { this.records = records; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRecords() != null) sb.append(getRecords()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DynamodbEvent == false) return false; DynamodbEvent other = (DynamodbEvent) obj; if (other.getRecords() == null ^ this.getRecords() == null) return false; if (other.getRecords() != null && other.getRecords().equals(this.getRecords()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRecords() == null) ? 0 : getRecords().hashCode()); return hashCode; } @Override public DynamodbEvent clone() { try { return (DynamodbEvent) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone()", e); } } }
1,808
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/CognitoUserPoolPreSignUpEvent.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events; import lombok.*; import java.util.Map; /** * Represent the class for the Cognito User Pool Pre Sign-up Lambda Trigger * * See <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html">Pre Sign-up Lambda Trigger</a> * * @author jvdl <jvdl@amazon.com> */ @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @ToString(callSuper = true) public class CognitoUserPoolPreSignUpEvent extends CognitoUserPoolEvent { /** * The request from the Amazon Cognito service. */ private Request request; /** * The response from your Lambda trigger. */ private Response response; @Builder(setterPrefix = "with") public CognitoUserPoolPreSignUpEvent( String version, String triggerSource, String region, String userPoolId, String userName, CallerContext callerContext, Request request, Response response) { super(version, triggerSource, region, userPoolId, userName, callerContext); this.request = request; this.response = response; } @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @ToString(callSuper = true) public static class Request extends CognitoUserPoolEvent.Request { /** * One or more name-value pairs containing the validation data in the request to register a user. * The validation data is set and then passed from the client in the request to register a user. */ private Map<String, String> validationData; /** * One or more key-value pairs that you can provide as custom input * to the Lambda function that you specify for the pre sign-up trigger. */ private Map<String, String> clientMetadata; @Builder(setterPrefix = "with") public Request(Map<String, String> userAttributes, Map<String, String> validationData, Map<String, String> clientMetadata) { super(userAttributes); this.validationData = validationData; this.clientMetadata = clientMetadata; } } @AllArgsConstructor @Builder(setterPrefix = "with") @Data @NoArgsConstructor public static class Response { /** * Set to true to auto-confirm the user, or false otherwise. */ private boolean autoConfirmUser; /** * Set to true to set as verified the phone number of a user who is signing up, or false otherwise. * If autoVerifyPhone is set to true, the phone_number attribute must have a valid, non-null value. */ private boolean autoVerifyPhone; /** * Set to true to set as verified the email of a user who is signing up, or false otherwise. * If autoVerifyEmail is set to true, the email attribute must have a valid, non-null value. */ private boolean autoVerifyEmail; } }
1,809
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/TimeWindow.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * Represents a time window. */ @Data @Builder(setterPrefix = "with") @NoArgsConstructor @AllArgsConstructor public class TimeWindow { /** * Window start instant represented as ISO-8601 string. */ private String start; /** * Window end instant represented as ISO-8601 string. */ private String end; }
1,810
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/kinesis/EncryptionType.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models.kinesis; public enum EncryptionType { NONE("NONE"), KMS("KMS"); private String value; private EncryptionType(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return EncryptionType corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static EncryptionType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (EncryptionType enumEntry : EncryptionType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
1,811
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/kinesis/Record.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models.kinesis; import java.io.Serializable; /** * <p> * The unit of data of the Kinesis data stream, which is composed of a sequence number, a partition key, and a data * blob. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/Record" target="_top">AWS API * Documentation</a> */ public class Record implements Serializable, Cloneable { /** * <p> * The unique identifier of the record within its shard. * </p> */ private String sequenceNumber; /** * <p> * The approximate time that the record was inserted into the stream. * </p> */ private java.util.Date approximateArrivalTimestamp; /** * <p> * The data blob. The data in the blob is both opaque and immutable to Kinesis Data Streams, which does not inspect, * interpret, or change the data in the blob in any way. When the data blob (the payload before base64-encoding) is * added to the partition key size, the total size must not exceed the maximum record size (1 MB). * </p> */ private java.nio.ByteBuffer data; /** * <p> * Identifies which shard in the stream the data record is assigned to. * </p> */ private String partitionKey; /** * <p> * The encryption type used on the record. This parameter can be one of the following values: * </p> * <ul> * <li> * <p> * <code>NONE</code>: Do not encrypt the records in the stream. * </p> * </li> * <li> * <p> * <code>KMS</code>: Use server-side encryption on the records in the stream using a customer-managed AWS KMS key. * </p> * </li> * </ul> */ private String encryptionType; /** * <p> * The unique identifier of the record within its shard. * </p> * * @param sequenceNumber * The unique identifier of the record within its shard. */ public void setSequenceNumber(String sequenceNumber) { this.sequenceNumber = sequenceNumber; } /** * <p> * The unique identifier of the record within its shard. * </p> * * @return The unique identifier of the record within its shard. */ public String getSequenceNumber() { return this.sequenceNumber; } /** * <p> * The unique identifier of the record within its shard. * </p> * * @param sequenceNumber * The unique identifier of the record within its shard. * @return Returns a reference to this object so that method calls can be chained together. */ public Record withSequenceNumber(String sequenceNumber) { setSequenceNumber(sequenceNumber); return this; } /** * <p> * The approximate time that the record was inserted into the stream. * </p> * * @param approximateArrivalTimestamp * The approximate time that the record was inserted into the stream. */ public void setApproximateArrivalTimestamp(java.util.Date approximateArrivalTimestamp) { this.approximateArrivalTimestamp = approximateArrivalTimestamp; } /** * <p> * The approximate time that the record was inserted into the stream. * </p> * * @return The approximate time that the record was inserted into the stream. */ public java.util.Date getApproximateArrivalTimestamp() { return this.approximateArrivalTimestamp; } /** * <p> * The approximate time that the record was inserted into the stream. * </p> * * @param approximateArrivalTimestamp * The approximate time that the record was inserted into the stream. * @return Returns a reference to this object so that method calls can be chained together. */ public Record withApproximateArrivalTimestamp(java.util.Date approximateArrivalTimestamp) { setApproximateArrivalTimestamp(approximateArrivalTimestamp); return this; } /** * <p> * The data blob. The data in the blob is both opaque and immutable to Kinesis Data Streams, which does not inspect, * interpret, or change the data in the blob in any way. When the data blob (the payload before base64-encoding) is * added to the partition key size, the total size must not exceed the maximum record size (1 MB). * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param data * The data blob. The data in the blob is both opaque and immutable to Kinesis Data Streams, which does not * inspect, interpret, or change the data in the blob in any way. When the data blob (the payload before * base64-encoding) is added to the partition key size, the total size must not exceed the maximum record * size (1 MB). */ public void setData(java.nio.ByteBuffer data) { this.data = data; } /** * <p> * The data blob. The data in the blob is both opaque and immutable to Kinesis Data Streams, which does not inspect, * interpret, or change the data in the blob in any way. When the data blob (the payload before base64-encoding) is * added to the partition key size, the total size must not exceed the maximum record size (1 MB). * </p> * <p> * {@code ByteBuffer}s are stateful. Calling their {@code get} methods changes their {@code position}. We recommend * using {@link java.nio.ByteBuffer#asReadOnlyBuffer()} to create a read-only view of the buffer with an independent * {@code position}, and calling {@code get} methods on this rather than directly on the returned {@code ByteBuffer}. * Doing so will ensure that anyone else using the {@code ByteBuffer} will not be affected by changes to the * {@code position}. * </p> * * @return The data blob. The data in the blob is both opaque and immutable to Kinesis Data Streams, which does not * inspect, interpret, or change the data in the blob in any way. When the data blob (the payload before * base64-encoding) is added to the partition key size, the total size must not exceed the maximum record * size (1 MB). */ public java.nio.ByteBuffer getData() { return this.data; } /** * <p> * The data blob. The data in the blob is both opaque and immutable to Kinesis Data Streams, which does not inspect, * interpret, or change the data in the blob in any way. When the data blob (the payload before base64-encoding) is * added to the partition key size, the total size must not exceed the maximum record size (1 MB). * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param data * The data blob. The data in the blob is both opaque and immutable to Kinesis Data Streams, which does not * inspect, interpret, or change the data in the blob in any way. When the data blob (the payload before * base64-encoding) is added to the partition key size, the total size must not exceed the maximum record * size (1 MB). * @return Returns a reference to this object so that method calls can be chained together. */ public Record withData(java.nio.ByteBuffer data) { setData(data); return this; } /** * <p> * Identifies which shard in the stream the data record is assigned to. * </p> * * @param partitionKey * Identifies which shard in the stream the data record is assigned to. */ public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } /** * <p> * Identifies which shard in the stream the data record is assigned to. * </p> * * @return Identifies which shard in the stream the data record is assigned to. */ public String getPartitionKey() { return this.partitionKey; } /** * <p> * Identifies which shard in the stream the data record is assigned to. * </p> * * @param partitionKey * Identifies which shard in the stream the data record is assigned to. * @return Returns a reference to this object so that method calls can be chained together. */ public Record withPartitionKey(String partitionKey) { setPartitionKey(partitionKey); return this; } /** * <p> * The encryption type used on the record. This parameter can be one of the following values: * </p> * <ul> * <li> * <p> * <code>NONE</code>: Do not encrypt the records in the stream. * </p> * </li> * <li> * <p> * <code>KMS</code>: Use server-side encryption on the records in the stream using a customer-managed AWS KMS key. * </p> * </li> * </ul> * * @param encryptionType * The encryption type used on the record. This parameter can be one of the following values:</p> * <ul> * <li> * <p> * <code>NONE</code>: Do not encrypt the records in the stream. * </p> * </li> * <li> * <p> * <code>KMS</code>: Use server-side encryption on the records in the stream using a customer-managed AWS KMS * key. * </p> * </li> * @see EncryptionType */ public void setEncryptionType(String encryptionType) { this.encryptionType = encryptionType; } /** * <p> * The encryption type used on the record. This parameter can be one of the following values: * </p> * <ul> * <li> * <p> * <code>NONE</code>: Do not encrypt the records in the stream. * </p> * </li> * <li> * <p> * <code>KMS</code>: Use server-side encryption on the records in the stream using a customer-managed AWS KMS key. * </p> * </li> * </ul> * * @return The encryption type used on the record. This parameter can be one of the following values:</p> * <ul> * <li> * <p> * <code>NONE</code>: Do not encrypt the records in the stream. * </p> * </li> * <li> * <p> * <code>KMS</code>: Use server-side encryption on the records in the stream using a customer-managed AWS * KMS key. * </p> * </li> * @see EncryptionType */ public String getEncryptionType() { return this.encryptionType; } /** * <p> * The encryption type used on the record. This parameter can be one of the following values: * </p> * <ul> * <li> * <p> * <code>NONE</code>: Do not encrypt the records in the stream. * </p> * </li> * <li> * <p> * <code>KMS</code>: Use server-side encryption on the records in the stream using a customer-managed AWS KMS key. * </p> * </li> * </ul> * * @param encryptionType * The encryption type used on the record. This parameter can be one of the following values:</p> * <ul> * <li> * <p> * <code>NONE</code>: Do not encrypt the records in the stream. * </p> * </li> * <li> * <p> * <code>KMS</code>: Use server-side encryption on the records in the stream using a customer-managed AWS KMS * key. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see EncryptionType */ public Record withEncryptionType(String encryptionType) { setEncryptionType(encryptionType); return this; } /** * <p> * The encryption type used on the record. This parameter can be one of the following values: * </p> * <ul> * <li> * <p> * <code>NONE</code>: Do not encrypt the records in the stream. * </p> * </li> * <li> * <p> * <code>KMS</code>: Use server-side encryption on the records in the stream using a customer-managed AWS KMS key. * </p> * </li> * </ul> * * @param encryptionType * The encryption type used on the record. This parameter can be one of the following values:</p> * <ul> * <li> * <p> * <code>NONE</code>: Do not encrypt the records in the stream. * </p> * </li> * <li> * <p> * <code>KMS</code>: Use server-side encryption on the records in the stream using a customer-managed AWS KMS * key. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see EncryptionType */ public Record withEncryptionType(EncryptionType encryptionType) { this.encryptionType = encryptionType.toString(); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSequenceNumber() != null) sb.append("SequenceNumber: ").append(getSequenceNumber()).append(","); if (getApproximateArrivalTimestamp() != null) sb.append("ApproximateArrivalTimestamp: ").append(getApproximateArrivalTimestamp()).append(","); if (getData() != null) sb.append("Data: ").append(getData()).append(","); if (getPartitionKey() != null) sb.append("PartitionKey: ").append(getPartitionKey()).append(","); if (getEncryptionType() != null) sb.append("EncryptionType: ").append(getEncryptionType()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Record == false) return false; Record other = (Record) obj; if (other.getSequenceNumber() == null ^ this.getSequenceNumber() == null) return false; if (other.getSequenceNumber() != null && other.getSequenceNumber().equals(this.getSequenceNumber()) == false) return false; if (other.getApproximateArrivalTimestamp() == null ^ this.getApproximateArrivalTimestamp() == null) return false; if (other.getApproximateArrivalTimestamp() != null && other.getApproximateArrivalTimestamp().equals(this.getApproximateArrivalTimestamp()) == false) return false; if (other.getData() == null ^ this.getData() == null) return false; if (other.getData() != null && other.getData().equals(this.getData()) == false) return false; if (other.getPartitionKey() == null ^ this.getPartitionKey() == null) return false; if (other.getPartitionKey() != null && other.getPartitionKey().equals(this.getPartitionKey()) == false) return false; if (other.getEncryptionType() == null ^ this.getEncryptionType() == null) return false; if (other.getEncryptionType() != null && other.getEncryptionType().equals(this.getEncryptionType()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSequenceNumber() == null) ? 0 : getSequenceNumber().hashCode()); hashCode = prime * hashCode + ((getApproximateArrivalTimestamp() == null) ? 0 : getApproximateArrivalTimestamp().hashCode()); hashCode = prime * hashCode + ((getData() == null) ? 0 : getData().hashCode()); hashCode = prime * hashCode + ((getPartitionKey() == null) ? 0 : getPartitionKey().hashCode()); hashCode = prime * hashCode + ((getEncryptionType() == null) ? 0 : getEncryptionType().hashCode()); return hashCode; } @Override public Record clone() { try { return (Record) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
1,812
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/s3/S3EventNotification.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models.s3; import org.joda.time.DateTime; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.List; /** * A helper class that represents a strongly typed S3 EventNotification item sent * to SQS, SNS, or Lambda. */ public class S3EventNotification { private final List<S3EventNotificationRecord> records; public S3EventNotification(List<S3EventNotificationRecord> records) { this.records = records; } /** * @return the records in this notification */ public List<S3EventNotificationRecord> getRecords() { return records; } public static class UserIdentityEntity { private final String principalId; public UserIdentityEntity(String principalId) { this.principalId = principalId; } public String getPrincipalId() { return principalId; } } public static class S3BucketEntity { private final String name; private final UserIdentityEntity ownerIdentity; private final String arn; public S3BucketEntity(String name, UserIdentityEntity ownerIdentity, String arn) { this.name = name; this.ownerIdentity = ownerIdentity; this.arn = arn; } public String getName() { return name; } public UserIdentityEntity getOwnerIdentity() { return ownerIdentity; } public String getArn() { return arn; } } public static class S3ObjectEntity { private final String key; private final Long size; private final String eTag; private final String versionId; private final String sequencer; @Deprecated public S3ObjectEntity( String key, Integer size, String eTag, String versionId) { this.key = key; this.size = size == null ? null : size.longValue(); this.eTag = eTag; this.versionId = versionId; this.sequencer = null; } @Deprecated public S3ObjectEntity( String key, Long size, String eTag, String versionId) { this(key, size, eTag, versionId, null); } public S3ObjectEntity(String key, Long size, String eTag, String versionId, String sequencer) { this.key = key; this.size = size; this.eTag = eTag; this.versionId = versionId; this.sequencer = sequencer; } public String getKey() { return key; } /** * S3 URL encodes the key of the object involved in the event. This is * a convenience method to automatically URL decode the key. * @return The URL decoded object key. */ public String getUrlDecodedKey() { return urlDecode(getKey()); } private static final String DEFAULT_ENCODING = "UTF-8"; /** * Decode a string for use in the path of a URL; uses URLDecoder.decode, * which decodes a string for use in the query portion of a URL. * * @param value The value to decode * @return The decoded value if parameter is not null, otherwise, null is returned. */ private static String urlDecode(final String value) { if (value == null) { return null; } try { return URLDecoder.decode(value, DEFAULT_ENCODING); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * @deprecated use {@link #getSizeAsLong()} instead. */ @Deprecated public Integer getSize() { return size == null ? null : size.intValue(); } public Long getSizeAsLong() { return size; } public String geteTag() { return eTag; } public String getVersionId() { return versionId; } public String getSequencer() { return sequencer; } } public static class S3Entity { private final String configurationId; private final S3BucketEntity bucket; private final S3ObjectEntity object; private final String s3SchemaVersion; public S3Entity(String configurationId, S3BucketEntity bucket, S3ObjectEntity object, String s3SchemaVersion) { this.configurationId = configurationId; this.bucket = bucket; this.object = object; this.s3SchemaVersion = s3SchemaVersion; } public String getConfigurationId() { return configurationId; } public S3BucketEntity getBucket() { return bucket; } public S3ObjectEntity getObject() { return object; } public String getS3SchemaVersion() { return s3SchemaVersion; } } public static class RequestParametersEntity { private final String sourceIPAddress; public RequestParametersEntity(String sourceIPAddress) { this.sourceIPAddress = sourceIPAddress; } public String getSourceIPAddress() { return sourceIPAddress; } } public static class ResponseElementsEntity { private final String xAmzId2; private final String xAmzRequestId; public ResponseElementsEntity(String xAmzId2, String xAmzRequestId) { this.xAmzId2 = xAmzId2; this.xAmzRequestId = xAmzRequestId; } public String getxAmzId2() { return xAmzId2; } public String getxAmzRequestId() { return xAmzRequestId; } } public static class S3EventNotificationRecord { private final String awsRegion; private final String eventName; private final String eventSource; private DateTime eventTime; private final String eventVersion; private final RequestParametersEntity requestParameters; private final ResponseElementsEntity responseElements; private final S3Entity s3; private final UserIdentityEntity userIdentity; public S3EventNotificationRecord(String awsRegion, String eventName, String eventSource, String eventTime, String eventVersion, RequestParametersEntity requestParameters, ResponseElementsEntity responseElements, S3Entity s3, UserIdentityEntity userIdentity) { this.awsRegion = awsRegion; this.eventName = eventName; this.eventSource = eventSource; if (eventTime != null) { this.eventTime = DateTime.parse(eventTime); } this.eventVersion = eventVersion; this.requestParameters = requestParameters; this.responseElements = responseElements; this.s3 = s3; this.userIdentity = userIdentity; } public String getAwsRegion() { return awsRegion; } public String getEventName() { return eventName; } public String getEventSource() { return eventSource; } public DateTime getEventTime() { return eventTime; } public String getEventVersion() { return eventVersion; } public RequestParametersEntity getRequestParameters() { return requestParameters; } public ResponseElementsEntity getResponseElements() { return responseElements; } public S3Entity getS3() { return s3; } public UserIdentityEntity getUserIdentity() { return userIdentity; } } }
1,813
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/dynamodb/OperationType.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models.dynamodb; public enum OperationType { INSERT("INSERT"), MODIFY("MODIFY"), REMOVE("REMOVE"); private String value; private OperationType(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return OperationType corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static OperationType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (OperationType enumEntry : OperationType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
1,814
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/dynamodb/StreamRecord.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models.dynamodb; import java.io.Serializable; /** * <p> * A description of a single data modification that was performed on an item in a DynamoDB table. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/streams-dynamodb-2012-08-10/StreamRecord" target="_top">AWS API * Documentation</a> */ public class StreamRecord implements Serializable, Cloneable { /** * <p> * The approximate date and time when the stream record was created, in <a * href="http://www.epochconverter.com/">UNIX epoch time</a> format. * </p> */ private java.util.Date approximateCreationDateTime; /** * <p> * The primary key attribute(s) for the DynamoDB item that was modified. * </p> */ private java.util.Map<String, AttributeValue> keys; /** * <p> * The item in the DynamoDB table as it appeared after it was modified. * </p> */ private java.util.Map<String, AttributeValue> newImage; /** * <p> * The item in the DynamoDB table as it appeared before it was modified. * </p> */ private java.util.Map<String, AttributeValue> oldImage; /** * <p> * The sequence number of the stream record. * </p> */ private String sequenceNumber; /** * <p> * The size of the stream record, in bytes. * </p> */ private Long sizeBytes; /** * <p> * The type of data from the modified DynamoDB item that was captured in this stream record: * </p> * <ul> * <li> * <p> * <code>KEYS_ONLY</code> - only the key attributes of the modified item. * </p> * </li> * <li> * <p> * <code>NEW_IMAGE</code> - the entire item, as it appeared after it was modified. * </p> * </li> * <li> * <p> * <code>OLD_IMAGE</code> - the entire item, as it appeared before it was modified. * </p> * </li> * <li> * <p> * <code>NEW_AND_OLD_IMAGES</code> - both the new and the old item images of the item. * </p> * </li> * </ul> */ private String streamViewType; /** * <p> * The approximate date and time when the stream record was created, in <a * href="http://www.epochconverter.com/">UNIX epoch time</a> format. * </p> * * @param approximateCreationDateTime * The approximate date and time when the stream record was created, in <a * href="http://www.epochconverter.com/">UNIX epoch time</a> format. */ public void setApproximateCreationDateTime(java.util.Date approximateCreationDateTime) { this.approximateCreationDateTime = approximateCreationDateTime; } /** * <p> * The approximate date and time when the stream record was created, in <a * href="http://www.epochconverter.com/">UNIX epoch time</a> format. * </p> * * @return The approximate date and time when the stream record was created, in <a * href="http://www.epochconverter.com/">UNIX epoch time</a> format. */ public java.util.Date getApproximateCreationDateTime() { return this.approximateCreationDateTime; } /** * <p> * The approximate date and time when the stream record was created, in <a * href="http://www.epochconverter.com/">UNIX epoch time</a> format. * </p> * * @param approximateCreationDateTime * The approximate date and time when the stream record was created, in <a * href="http://www.epochconverter.com/">UNIX epoch time</a> format. * @return Returns a reference to this object so that method calls can be chained together. */ public StreamRecord withApproximateCreationDateTime(java.util.Date approximateCreationDateTime) { setApproximateCreationDateTime(approximateCreationDateTime); return this; } /** * <p> * The primary key attribute(s) for the DynamoDB item that was modified. * </p> * * @return The primary key attribute(s) for the DynamoDB item that was modified. */ public java.util.Map<String, AttributeValue> getKeys() { return keys; } /** * <p> * The primary key attribute(s) for the DynamoDB item that was modified. * </p> * * @param keys * The primary key attribute(s) for the DynamoDB item that was modified. */ public void setKeys(java.util.Map<String, AttributeValue> keys) { this.keys = keys; } /** * <p> * The primary key attribute(s) for the DynamoDB item that was modified. * </p> * * @param keys * The primary key attribute(s) for the DynamoDB item that was modified. * @return Returns a reference to this object so that method calls can be chained together. */ public StreamRecord withKeys(java.util.Map<String, AttributeValue> keys) { setKeys(keys); return this; } public StreamRecord addKeysEntry(String key, AttributeValue value) { if (null == this.keys) { this.keys = new java.util.HashMap<String, AttributeValue>(); } if (this.keys.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.keys.put(key, value); return this; } /** * Removes all the entries added into Keys. * * @return Returns a reference to this object so that method calls can be chained together. */ public StreamRecord clearKeysEntries() { this.keys = null; return this; } /** * <p> * The item in the DynamoDB table as it appeared after it was modified. * </p> * * @return The item in the DynamoDB table as it appeared after it was modified. */ public java.util.Map<String, AttributeValue> getNewImage() { return newImage; } /** * <p> * The item in the DynamoDB table as it appeared after it was modified. * </p> * * @param newImage * The item in the DynamoDB table as it appeared after it was modified. */ public void setNewImage(java.util.Map<String, AttributeValue> newImage) { this.newImage = newImage; } /** * <p> * The item in the DynamoDB table as it appeared after it was modified. * </p> * * @param newImage * The item in the DynamoDB table as it appeared after it was modified. * @return Returns a reference to this object so that method calls can be chained together. */ public StreamRecord withNewImage(java.util.Map<String, AttributeValue> newImage) { setNewImage(newImage); return this; } public StreamRecord addNewImageEntry(String key, AttributeValue value) { if (null == this.newImage) { this.newImage = new java.util.HashMap<String, AttributeValue>(); } if (this.newImage.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.newImage.put(key, value); return this; } /** * Removes all the entries added into NewImage. * * @return Returns a reference to this object so that method calls can be chained together. */ public StreamRecord clearNewImageEntries() { this.newImage = null; return this; } /** * <p> * The item in the DynamoDB table as it appeared before it was modified. * </p> * * @return The item in the DynamoDB table as it appeared before it was modified. */ public java.util.Map<String, AttributeValue> getOldImage() { return oldImage; } /** * <p> * The item in the DynamoDB table as it appeared before it was modified. * </p> * * @param oldImage * The item in the DynamoDB table as it appeared before it was modified. */ public void setOldImage(java.util.Map<String, AttributeValue> oldImage) { this.oldImage = oldImage; } /** * <p> * The item in the DynamoDB table as it appeared before it was modified. * </p> * * @param oldImage * The item in the DynamoDB table as it appeared before it was modified. * @return Returns a reference to this object so that method calls can be chained together. */ public StreamRecord withOldImage(java.util.Map<String, AttributeValue> oldImage) { setOldImage(oldImage); return this; } public StreamRecord addOldImageEntry(String key, AttributeValue value) { if (null == this.oldImage) { this.oldImage = new java.util.HashMap<String, AttributeValue>(); } if (this.oldImage.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.oldImage.put(key, value); return this; } /** * Removes all the entries added into OldImage. * * @return Returns a reference to this object so that method calls can be chained together. */ public StreamRecord clearOldImageEntries() { this.oldImage = null; return this; } /** * <p> * The sequence number of the stream record. * </p> * * @param sequenceNumber * The sequence number of the stream record. */ public void setSequenceNumber(String sequenceNumber) { this.sequenceNumber = sequenceNumber; } /** * <p> * The sequence number of the stream record. * </p> * * @return The sequence number of the stream record. */ public String getSequenceNumber() { return this.sequenceNumber; } /** * <p> * The sequence number of the stream record. * </p> * * @param sequenceNumber * The sequence number of the stream record. * @return Returns a reference to this object so that method calls can be chained together. */ public StreamRecord withSequenceNumber(String sequenceNumber) { setSequenceNumber(sequenceNumber); return this; } /** * <p> * The size of the stream record, in bytes. * </p> * * @param sizeBytes * The size of the stream record, in bytes. */ public void setSizeBytes(Long sizeBytes) { this.sizeBytes = sizeBytes; } /** * <p> * The size of the stream record, in bytes. * </p> * * @return The size of the stream record, in bytes. */ public Long getSizeBytes() { return this.sizeBytes; } /** * <p> * The size of the stream record, in bytes. * </p> * * @param sizeBytes * The size of the stream record, in bytes. * @return Returns a reference to this object so that method calls can be chained together. */ public StreamRecord withSizeBytes(Long sizeBytes) { setSizeBytes(sizeBytes); return this; } /** * <p> * The type of data from the modified DynamoDB item that was captured in this stream record: * </p> * <ul> * <li> * <p> * <code>KEYS_ONLY</code> - only the key attributes of the modified item. * </p> * </li> * <li> * <p> * <code>NEW_IMAGE</code> - the entire item, as it appeared after it was modified. * </p> * </li> * <li> * <p> * <code>OLD_IMAGE</code> - the entire item, as it appeared before it was modified. * </p> * </li> * <li> * <p> * <code>NEW_AND_OLD_IMAGES</code> - both the new and the old item images of the item. * </p> * </li> * </ul> * * @return The type of data from the modified DynamoDB item that was captured in this stream record:</p> * <ul> * <li> * <p> * <code>KEYS_ONLY</code> - only the key attributes of the modified item. * </p> * </li> * <li> * <p> * <code>NEW_IMAGE</code> - the entire item, as it appeared after it was modified. * </p> * </li> * <li> * <p> * <code>OLD_IMAGE</code> - the entire item, as it appeared before it was modified. * </p> * </li> * <li> * <p> * <code>NEW_AND_OLD_IMAGES</code> - both the new and the old item images of the item. * </p> * </li> * @see StreamViewType */ public String getStreamViewType() { return this.streamViewType; } /** * <p> * The type of data from the modified DynamoDB item that was captured in this stream record: * </p> * <ul> * <li> * <p> * <code>KEYS_ONLY</code> - only the key attributes of the modified item. * </p> * </li> * <li> * <p> * <code>NEW_IMAGE</code> - the entire item, as it appeared after it was modified. * </p> * </li> * <li> * <p> * <code>OLD_IMAGE</code> - the entire item, as it appeared before it was modified. * </p> * </li> * <li> * <p> * <code>NEW_AND_OLD_IMAGES</code> - both the new and the old item images of the item. * </p> * </li> * </ul> * * @param streamViewType * The type of data from the modified DynamoDB item that was captured in this stream record:</p> * <ul> * <li> * <p> * <code>KEYS_ONLY</code> - only the key attributes of the modified item. * </p> * </li> * <li> * <p> * <code>NEW_IMAGE</code> - the entire item, as it appeared after it was modified. * </p> * </li> * <li> * <p> * <code>OLD_IMAGE</code> - the entire item, as it appeared before it was modified. * </p> * </li> * <li> * <p> * <code>NEW_AND_OLD_IMAGES</code> - both the new and the old item images of the item. * </p> * </li> * @see StreamViewType */ public void setStreamViewType(StreamViewType streamViewType) { withStreamViewType(streamViewType); } /** * <p> * The type of data from the modified DynamoDB item that was captured in this stream record: * </p> * <ul> * <li> * <p> * <code>KEYS_ONLY</code> - only the key attributes of the modified item. * </p> * </li> * <li> * <p> * <code>NEW_IMAGE</code> - the entire item, as it appeared after it was modified. * </p> * </li> * <li> * <p> * <code>OLD_IMAGE</code> - the entire item, as it appeared before it was modified. * </p> * </li> * <li> * <p> * <code>NEW_AND_OLD_IMAGES</code> - both the new and the old item images of the item. * </p> * </li> * </ul> * * @param streamViewType * The type of data from the modified DynamoDB item that was captured in this stream record:</p> * <ul> * <li> * <p> * <code>KEYS_ONLY</code> - only the key attributes of the modified item. * </p> * </li> * <li> * <p> * <code>NEW_IMAGE</code> - the entire item, as it appeared after it was modified. * </p> * </li> * <li> * <p> * <code>OLD_IMAGE</code> - the entire item, as it appeared before it was modified. * </p> * </li> * <li> * <p> * <code>NEW_AND_OLD_IMAGES</code> - both the new and the old item images of the item. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see StreamViewType */ public StreamRecord withStreamViewType(StreamViewType streamViewType) { this.streamViewType = streamViewType.toString(); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getApproximateCreationDateTime() != null) sb.append("ApproximateCreationDateTime: ").append(getApproximateCreationDateTime()).append(","); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNewImage() != null) sb.append("NewImage: ").append(getNewImage()).append(","); if (getOldImage() != null) sb.append("OldImage: ").append(getOldImage()).append(","); if (getSequenceNumber() != null) sb.append("SequenceNumber: ").append(getSequenceNumber()).append(","); if (getSizeBytes() != null) sb.append("SizeBytes: ").append(getSizeBytes()).append(","); if (getStreamViewType() != null) sb.append("StreamViewType: ").append(getStreamViewType()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof StreamRecord == false) return false; StreamRecord other = (StreamRecord) obj; if (other.getApproximateCreationDateTime() == null ^ this.getApproximateCreationDateTime() == null) return false; if (other.getApproximateCreationDateTime() != null && other.getApproximateCreationDateTime().equals(this.getApproximateCreationDateTime()) == false) return false; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNewImage() == null ^ this.getNewImage() == null) return false; if (other.getNewImage() != null && other.getNewImage().equals(this.getNewImage()) == false) return false; if (other.getOldImage() == null ^ this.getOldImage() == null) return false; if (other.getOldImage() != null && other.getOldImage().equals(this.getOldImage()) == false) return false; if (other.getSequenceNumber() == null ^ this.getSequenceNumber() == null) return false; if (other.getSequenceNumber() != null && other.getSequenceNumber().equals(this.getSequenceNumber()) == false) return false; if (other.getSizeBytes() == null ^ this.getSizeBytes() == null) return false; if (other.getSizeBytes() != null && other.getSizeBytes().equals(this.getSizeBytes()) == false) return false; if (other.getStreamViewType() == null ^ this.getStreamViewType() == null) return false; if (other.getStreamViewType() != null && other.getStreamViewType().equals(this.getStreamViewType()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getApproximateCreationDateTime() == null) ? 0 : getApproximateCreationDateTime().hashCode()); hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNewImage() == null) ? 0 : getNewImage().hashCode()); hashCode = prime * hashCode + ((getOldImage() == null) ? 0 : getOldImage().hashCode()); hashCode = prime * hashCode + ((getSequenceNumber() == null) ? 0 : getSequenceNumber().hashCode()); hashCode = prime * hashCode + ((getSizeBytes() == null) ? 0 : getSizeBytes().hashCode()); hashCode = prime * hashCode + ((getStreamViewType() == null) ? 0 : getStreamViewType().hashCode()); return hashCode; } @Override public StreamRecord clone() { try { return (StreamRecord) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
1,815
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/dynamodb/Identity.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models.dynamodb; import java.io.Serializable; /** * <p> * Contains details about the type of identity that made the request. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/streams-dynamodb-2012-08-10/Identity" target="_top">AWS API * Documentation</a> */ public class Identity implements Serializable, Cloneable { /** * <p> * A unique identifier for the entity that made the call. For Time To Live, the principalId is * "dynamodb.amazonaws.com". * </p> */ private String principalId; /** * <p> * The type of the identity. For Time To Live, the type is "Service". * </p> */ private String type; /** * <p> * A unique identifier for the entity that made the call. For Time To Live, the principalId is * "dynamodb.amazonaws.com". * </p> * * @param principalId * A unique identifier for the entity that made the call. For Time To Live, the principalId is * "dynamodb.amazonaws.com". */ public void setPrincipalId(String principalId) { this.principalId = principalId; } /** * <p> * A unique identifier for the entity that made the call. For Time To Live, the principalId is * "dynamodb.amazonaws.com". * </p> * * @return A unique identifier for the entity that made the call. For Time To Live, the principalId is * "dynamodb.amazonaws.com". */ public String getPrincipalId() { return this.principalId; } /** * <p> * A unique identifier for the entity that made the call. For Time To Live, the principalId is * "dynamodb.amazonaws.com". * </p> * * @param principalId * A unique identifier for the entity that made the call. For Time To Live, the principalId is * "dynamodb.amazonaws.com". * @return Returns a reference to this object so that method calls can be chained together. */ public Identity withPrincipalId(String principalId) { setPrincipalId(principalId); return this; } /** * <p> * The type of the identity. For Time To Live, the type is "Service". * </p> * * @param type * The type of the identity. For Time To Live, the type is "Service". */ public void setType(String type) { this.type = type; } /** * <p> * The type of the identity. For Time To Live, the type is "Service". * </p> * * @return The type of the identity. For Time To Live, the type is "Service". */ public String getType() { return this.type; } /** * <p> * The type of the identity. For Time To Live, the type is "Service". * </p> * * @param type * The type of the identity. For Time To Live, the type is "Service". * @return Returns a reference to this object so that method calls can be chained together. */ public Identity withType(String type) { setType(type); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPrincipalId() != null) sb.append("PrincipalId: ").append(getPrincipalId()).append(","); if (getType() != null) sb.append("Type: ").append(getType()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Identity == false) return false; Identity other = (Identity) obj; if (other.getPrincipalId() == null ^ this.getPrincipalId() == null) return false; if (other.getPrincipalId() != null && other.getPrincipalId().equals(this.getPrincipalId()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPrincipalId() == null) ? 0 : getPrincipalId().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); return hashCode; } @Override public Identity clone() { try { return (Identity) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
1,816
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/dynamodb/StreamViewType.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models.dynamodb; public enum StreamViewType { NEW_IMAGE("NEW_IMAGE"), OLD_IMAGE("OLD_IMAGE"), NEW_AND_OLD_IMAGES("NEW_AND_OLD_IMAGES"), KEYS_ONLY("KEYS_ONLY"); private String value; StreamViewType(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value real value * @return StreamViewType corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static StreamViewType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (StreamViewType enumEntry : StreamViewType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
1,817
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/dynamodb/Record.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models.dynamodb; import java.io.Serializable; /** * <p> * A description of a unique event within a stream. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/streams-dynamodb-2012-08-10/Record" target="_top">AWS API * Documentation</a> */ public class Record implements Serializable, Cloneable { /** * <p> * A globally unique identifier for the event that was recorded in this stream record. * </p> */ private String eventID; /** * <p> * The type of data modification that was performed on the DynamoDB table: * </p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * </ul> */ private String eventName; /** * <p> * The version number of the stream record format. This number is updated whenever the structure of * <code>Record</code> is modified. * </p> * <p> * Client applications must not assume that <code>eventVersion</code> will remain at a particular value, as this * number is subject to change at any time. In general, <code>eventVersion</code> will only increase as the * low-level DynamoDB Streams API evolves. * </p> */ private String eventVersion; /** * <p> * The AWS service from which the stream record originated. For DynamoDB Streams, this is <code>aws:dynamodb</code>. * </p> */ private String eventSource; /** * <p> * The region in which the <code>GetRecords</code> request was received. * </p> */ private String awsRegion; /** * <p> * The main body of the stream record, containing all of the DynamoDB-specific fields. * </p> */ private StreamRecord dynamodb; /** * <p> * Items that are deleted by the Time to Live process after expiration have the following fields: * </p> * <ul> * <li> * <p> * Records[].userIdentity.type * </p> * <p> * "Service" * </p> * </li> * <li> * <p> * Records[].userIdentity.principalId * </p> * <p> * "dynamodb.amazonaws.com" * </p> * </li> * </ul> */ private Identity userIdentity; /** * <p> * A globally unique identifier for the event that was recorded in this stream record. * </p> * * @param eventID * A globally unique identifier for the event that was recorded in this stream record. */ public void setEventID(String eventID) { this.eventID = eventID; } /** * <p> * A globally unique identifier for the event that was recorded in this stream record. * </p> * * @return A globally unique identifier for the event that was recorded in this stream record. */ public String getEventID() { return this.eventID; } /** * <p> * A globally unique identifier for the event that was recorded in this stream record. * </p> * * @param eventID * A globally unique identifier for the event that was recorded in this stream record. * @return Returns a reference to this object so that method calls can be chained together. */ public Record withEventID(String eventID) { setEventID(eventID); return this; } /** * <p> * The type of data modification that was performed on the DynamoDB table: * </p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * </ul> * * @param eventName * The type of data modification that was performed on the DynamoDB table:</p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * @see OperationType */ public void setEventName(String eventName) { this.eventName = eventName; } /** * <p> * The type of data modification that was performed on the DynamoDB table: * </p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * </ul> * * @return The type of data modification that was performed on the DynamoDB table:</p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * @see OperationType */ public String getEventName() { return this.eventName; } /** * <p> * The type of data modification that was performed on the DynamoDB table: * </p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * </ul> * * @param eventName * The type of data modification that was performed on the DynamoDB table:</p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see OperationType */ public Record withEventName(String eventName) { setEventName(eventName); return this; } /** * <p> * The type of data modification that was performed on the DynamoDB table: * </p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * </ul> * * @param eventName * The type of data modification that was performed on the DynamoDB table:</p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * @see OperationType */ public void setEventName(OperationType eventName) { this.eventName = eventName.toString(); } /** * <p> * The type of data modification that was performed on the DynamoDB table: * </p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * </ul> * * @param eventName * The type of data modification that was performed on the DynamoDB table:</p> * <ul> * <li> * <p> * <code>INSERT</code> - a new item was added to the table. * </p> * </li> * <li> * <p> * <code>MODIFY</code> - one or more of an existing item's attributes were modified. * </p> * </li> * <li> * <p> * <code>REMOVE</code> - the item was deleted from the table * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see OperationType */ public Record withEventName(OperationType eventName) { setEventName(eventName); return this; } /** * <p> * The version number of the stream record format. This number is updated whenever the structure of * <code>Record</code> is modified. * </p> * <p> * Client applications must not assume that <code>eventVersion</code> will remain at a particular value, as this * number is subject to change at any time. In general, <code>eventVersion</code> will only increase as the * low-level DynamoDB Streams API evolves. * </p> * * @param eventVersion * The version number of the stream record format. This number is updated whenever the structure of * <code>Record</code> is modified.</p> * <p> * Client applications must not assume that <code>eventVersion</code> will remain at a particular value, as * this number is subject to change at any time. In general, <code>eventVersion</code> will only increase as * the low-level DynamoDB Streams API evolves. */ public void setEventVersion(String eventVersion) { this.eventVersion = eventVersion; } /** * <p> * The version number of the stream record format. This number is updated whenever the structure of * <code>Record</code> is modified. * </p> * <p> * Client applications must not assume that <code>eventVersion</code> will remain at a particular value, as this * number is subject to change at any time. In general, <code>eventVersion</code> will only increase as the * low-level DynamoDB Streams API evolves. * </p> * * @return The version number of the stream record format. This number is updated whenever the structure of * <code>Record</code> is modified.</p> * <p> * Client applications must not assume that <code>eventVersion</code> will remain at a particular value, as * this number is subject to change at any time. In general, <code>eventVersion</code> will only increase as * the low-level DynamoDB Streams API evolves. */ public String getEventVersion() { return this.eventVersion; } /** * <p> * The version number of the stream record format. This number is updated whenever the structure of * <code>Record</code> is modified. * </p> * <p> * Client applications must not assume that <code>eventVersion</code> will remain at a particular value, as this * number is subject to change at any time. In general, <code>eventVersion</code> will only increase as the * low-level DynamoDB Streams API evolves. * </p> * * @param eventVersion * The version number of the stream record format. This number is updated whenever the structure of * <code>Record</code> is modified.</p> * <p> * Client applications must not assume that <code>eventVersion</code> will remain at a particular value, as * this number is subject to change at any time. In general, <code>eventVersion</code> will only increase as * the low-level DynamoDB Streams API evolves. * @return Returns a reference to this object so that method calls can be chained together. */ public Record withEventVersion(String eventVersion) { setEventVersion(eventVersion); return this; } /** * <p> * The AWS service from which the stream record originated. For DynamoDB Streams, this is <code>aws:dynamodb</code>. * </p> * * @param eventSource * The AWS service from which the stream record originated. For DynamoDB Streams, this is * <code>aws:dynamodb</code>. */ public void setEventSource(String eventSource) { this.eventSource = eventSource; } /** * <p> * The AWS service from which the stream record originated. For DynamoDB Streams, this is <code>aws:dynamodb</code>. * </p> * * @return The AWS service from which the stream record originated. For DynamoDB Streams, this is * <code>aws:dynamodb</code>. */ public String getEventSource() { return this.eventSource; } /** * <p> * The AWS service from which the stream record originated. For DynamoDB Streams, this is <code>aws:dynamodb</code>. * </p> * * @param eventSource * The AWS service from which the stream record originated. For DynamoDB Streams, this is * <code>aws:dynamodb</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public Record withEventSource(String eventSource) { setEventSource(eventSource); return this; } /** * <p> * The region in which the <code>GetRecords</code> request was received. * </p> * * @param awsRegion * The region in which the <code>GetRecords</code> request was received. */ public void setAwsRegion(String awsRegion) { this.awsRegion = awsRegion; } /** * <p> * The region in which the <code>GetRecords</code> request was received. * </p> * * @return The region in which the <code>GetRecords</code> request was received. */ public String getAwsRegion() { return this.awsRegion; } /** * <p> * The region in which the <code>GetRecords</code> request was received. * </p> * * @param awsRegion * The region in which the <code>GetRecords</code> request was received. * @return Returns a reference to this object so that method calls can be chained together. */ public Record withAwsRegion(String awsRegion) { setAwsRegion(awsRegion); return this; } /** * <p> * The main body of the stream record, containing all of the DynamoDB-specific fields. * </p> * * @param dynamodb * The main body of the stream record, containing all of the DynamoDB-specific fields. */ public void setDynamodb(StreamRecord dynamodb) { this.dynamodb = dynamodb; } /** * <p> * The main body of the stream record, containing all of the DynamoDB-specific fields. * </p> * * @return The main body of the stream record, containing all of the DynamoDB-specific fields. */ public StreamRecord getDynamodb() { return this.dynamodb; } /** * <p> * The main body of the stream record, containing all of the DynamoDB-specific fields. * </p> * * @param dynamodb * The main body of the stream record, containing all of the DynamoDB-specific fields. * @return Returns a reference to this object so that method calls can be chained together. */ public Record withDynamodb(StreamRecord dynamodb) { setDynamodb(dynamodb); return this; } /** * <p> * Items that are deleted by the Time to Live process after expiration have the following fields: * </p> * <ul> * <li> * <p> * Records[].userIdentity.type * </p> * <p> * "Service" * </p> * </li> * <li> * <p> * Records[].userIdentity.principalId * </p> * <p> * "dynamodb.amazonaws.com" * </p> * </li> * </ul> * * @param userIdentity * Items that are deleted by the Time to Live process after expiration have the following fields: </p> * <ul> * <li> * <p> * Records[].userIdentity.type * </p> * <p> * "Service" * </p> * </li> * <li> * <p> * Records[].userIdentity.principalId * </p> * <p> * "dynamodb.amazonaws.com" * </p> * </li> */ public void setUserIdentity(Identity userIdentity) { this.userIdentity = userIdentity; } /** * <p> * Items that are deleted by the Time to Live process after expiration have the following fields: * </p> * <ul> * <li> * <p> * Records[].userIdentity.type * </p> * <p> * "Service" * </p> * </li> * <li> * <p> * Records[].userIdentity.principalId * </p> * <p> * "dynamodb.amazonaws.com" * </p> * </li> * </ul> * * @return Items that are deleted by the Time to Live process after expiration have the following fields: </p> * <ul> * <li> * <p> * Records[].userIdentity.type * </p> * <p> * "Service" * </p> * </li> * <li> * <p> * Records[].userIdentity.principalId * </p> * <p> * "dynamodb.amazonaws.com" * </p> * </li> */ public Identity getUserIdentity() { return this.userIdentity; } /** * <p> * Items that are deleted by the Time to Live process after expiration have the following fields: * </p> * <ul> * <li> * <p> * Records[].userIdentity.type * </p> * <p> * "Service" * </p> * </li> * <li> * <p> * Records[].userIdentity.principalId * </p> * <p> * "dynamodb.amazonaws.com" * </p> * </li> * </ul> * * @param userIdentity * Items that are deleted by the Time to Live process after expiration have the following fields: </p> * <ul> * <li> * <p> * Records[].userIdentity.type * </p> * <p> * "Service" * </p> * </li> * <li> * <p> * Records[].userIdentity.principalId * </p> * <p> * "dynamodb.amazonaws.com" * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public Record withUserIdentity(Identity userIdentity) { setUserIdentity(userIdentity); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getEventID() != null) sb.append("EventID: ").append(getEventID()).append(","); if (getEventName() != null) sb.append("EventName: ").append(getEventName()).append(","); if (getEventVersion() != null) sb.append("EventVersion: ").append(getEventVersion()).append(","); if (getEventSource() != null) sb.append("EventSource: ").append(getEventSource()).append(","); if (getAwsRegion() != null) sb.append("AwsRegion: ").append(getAwsRegion()).append(","); if (getDynamodb() != null) sb.append("Dynamodb: ").append(getDynamodb()).append(","); if (getUserIdentity() != null) sb.append("UserIdentity: ").append(getUserIdentity()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Record == false) return false; Record other = (Record) obj; if (other.getEventID() == null ^ this.getEventID() == null) return false; if (other.getEventID() != null && other.getEventID().equals(this.getEventID()) == false) return false; if (other.getEventName() == null ^ this.getEventName() == null) return false; if (other.getEventName() != null && other.getEventName().equals(this.getEventName()) == false) return false; if (other.getEventVersion() == null ^ this.getEventVersion() == null) return false; if (other.getEventVersion() != null && other.getEventVersion().equals(this.getEventVersion()) == false) return false; if (other.getEventSource() == null ^ this.getEventSource() == null) return false; if (other.getEventSource() != null && other.getEventSource().equals(this.getEventSource()) == false) return false; if (other.getAwsRegion() == null ^ this.getAwsRegion() == null) return false; if (other.getAwsRegion() != null && other.getAwsRegion().equals(this.getAwsRegion()) == false) return false; if (other.getDynamodb() == null ^ this.getDynamodb() == null) return false; if (other.getDynamodb() != null && other.getDynamodb().equals(this.getDynamodb()) == false) return false; if (other.getUserIdentity() == null ^ this.getUserIdentity() == null) return false; if (other.getUserIdentity() != null && other.getUserIdentity().equals(this.getUserIdentity()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getEventID() == null) ? 0 : getEventID().hashCode()); hashCode = prime * hashCode + ((getEventName() == null) ? 0 : getEventName().hashCode()); hashCode = prime * hashCode + ((getEventVersion() == null) ? 0 : getEventVersion().hashCode()); hashCode = prime * hashCode + ((getEventSource() == null) ? 0 : getEventSource().hashCode()); hashCode = prime * hashCode + ((getAwsRegion() == null) ? 0 : getAwsRegion().hashCode()); hashCode = prime * hashCode + ((getDynamodb() == null) ? 0 : getDynamodb().hashCode()); hashCode = prime * hashCode + ((getUserIdentity() == null) ? 0 : getUserIdentity().hashCode()); return hashCode; } @Override public Record clone() { try { return (Record) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
1,818
0
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models
Create_ds/aws-lambda-java-libs/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/models/dynamodb/AttributeValue.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.lambda.runtime.events.models.dynamodb; import java.io.Serializable; /** * <p> * Represents the data for an attribute. * </p> * <p> * Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. * </p> * <p> * For more information, see <a href= * "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes" * >Data Types</a> in the <i>Amazon DynamoDB Developer Guide</i>. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/AttributeValue" target="_top">AWS API * Documentation</a> */ public class AttributeValue implements Serializable, Cloneable { /** * <p> * An attribute of type String. For example: * </p> * <p> * <code>"S": "Hello"</code> * </p> */ private String s; /** * <p> * An attribute of type Number. For example: * </p> * <p> * <code>"N": "123.45"</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * </p> */ private String n; /** * <p> * An attribute of type Binary. For example: * </p> * <p> * <code>"B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk"</code> * </p> */ private java.nio.ByteBuffer b; /** * <p> * An attribute of type String Set. For example: * </p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> * </p> */ private java.util.List<String> sS; /** * <p> * An attribute of type Number Set. For example: * </p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * </p> */ private java.util.List<String> nS; /** * <p> * An attribute of type Binary Set. For example: * </p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> * </p> */ private java.util.List<java.nio.ByteBuffer> bS; /** * <p> * An attribute of type Map. For example: * </p> * <p> * <code>"M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}}</code> * </p> */ private java.util.Map<String, AttributeValue> m; /** * <p> * An attribute of type List. For example: * </p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> * </p> */ private java.util.List<AttributeValue> l; /** * <p> * An attribute of type Null. For example: * </p> * <p> * <code>"NULL": true</code> * </p> */ private Boolean nULLValue; /** * <p> * An attribute of type Boolean. For example: * </p> * <p> * <code>"BOOL": true</code> * </p> */ private Boolean bOOL; /** * Default constructor for DynamodbAttributeValue object. Callers should use the setter or fluent setter (with...) methods * to initialize the object after creating it. */ public AttributeValue() { } /** * Constructs a new DynamodbAttributeValue object. Callers should use the setter or fluent setter (with...) methods to * initialize any additional object members. * * @param s * An attribute of type String. For example:</p> * <p> * <code>"S": "Hello"</code> */ public AttributeValue(String s) { setS(s); } /** * Constructs a new DynamodbAttributeValue object. Callers should use the setter or fluent setter (with...) methods to * initialize any additional object members. * * @param sS * An attribute of type String Set. For example:</p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> */ public AttributeValue(java.util.List<String> sS) { setSS(sS); } /** * <p> * An attribute of type String. For example: * </p> * <p> * <code>"S": "Hello"</code> * </p> * * @param s * An attribute of type String. For example:</p> * <p> * <code>"S": "Hello"</code> */ public void setS(String s) { this.s = s; } /** * <p> * An attribute of type String. For example: * </p> * <p> * <code>"S": "Hello"</code> * </p> * * @return An attribute of type String. For example:</p> * <p> * <code>"S": "Hello"</code> */ public String getS() { return this.s; } /** * <p> * An attribute of type String. For example: * </p> * <p> * <code>"S": "Hello"</code> * </p> * * @param s * An attribute of type String. For example:</p> * <p> * <code>"S": "Hello"</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withS(String s) { setS(s); return this; } /** * <p> * An attribute of type Number. For example: * </p> * <p> * <code>"N": "123.45"</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * </p> * * @param n * An attribute of type Number. For example:</p> * <p> * <code>"N": "123.45"</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. */ public void setN(String n) { this.n = n; } /** * <p> * An attribute of type Number. For example: * </p> * <p> * <code>"N": "123.45"</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * </p> * * @return An attribute of type Number. For example:</p> * <p> * <code>"N": "123.45"</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages * and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. */ public String getN() { return this.n; } /** * <p> * An attribute of type Number. For example: * </p> * <p> * <code>"N": "123.45"</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * </p> * * @param n * An attribute of type Number. For example:</p> * <p> * <code>"N": "123.45"</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withN(String n) { setN(n); return this; } /** * <p> * An attribute of type Binary. For example: * </p> * <p> * <code>"B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk"</code> * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param b * An attribute of type Binary. For example:</p> * <p> * <code>"B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk"</code> */ public void setB(java.nio.ByteBuffer b) { this.b = b; } /** * <p> * An attribute of type Binary. For example: * </p> * <p> * <code>"B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk"</code> * </p> * <p> * {@code ByteBuffer}s are stateful. Calling their {@code get} methods changes their {@code position}. We recommend * using {@link java.nio.ByteBuffer#asReadOnlyBuffer()} to create a read-only view of the buffer with an independent * {@code position}, and calling {@code get} methods on this rather than directly on the returned {@code ByteBuffer}. * Doing so will ensure that anyone else using the {@code ByteBuffer} will not be affected by changes to the * {@code position}. * </p> * * @return An attribute of type Binary. For example:</p> * <p> * <code>"B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk"</code> */ public java.nio.ByteBuffer getB() { return this.b; } /** * <p> * An attribute of type Binary. For example: * </p> * <p> * <code>"B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk"</code> * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param b * An attribute of type Binary. For example:</p> * <p> * <code>"B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk"</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withB(java.nio.ByteBuffer b) { setB(b); return this; } /** * <p> * An attribute of type String Set. For example: * </p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> * </p> * * @return An attribute of type String Set. For example:</p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> */ public java.util.List<String> getSS() { return sS; } /** * <p> * An attribute of type String Set. For example: * </p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> * </p> * * @param sS * An attribute of type String Set. For example:</p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> */ public void setSS(java.util.Collection<String> sS) { if (sS == null) { this.sS = null; return; } this.sS = new java.util.ArrayList<String>(sS); } /** * <p> * An attribute of type String Set. For example: * </p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setSS(java.util.Collection)} or {@link #withSS(java.util.Collection)} if you want to override the * existing values. * </p> * * @param sS * An attribute of type String Set. For example:</p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withSS(String... sS) { if (this.sS == null) { setSS(new java.util.ArrayList<String>(sS.length)); } for (String ele : sS) { this.sS.add(ele); } return this; } /** * <p> * An attribute of type String Set. For example: * </p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> * </p> * * @param sS * An attribute of type String Set. For example:</p> * <p> * <code>"SS": ["Giraffe", "Hippo" ,"Zebra"]</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withSS(java.util.Collection<String> sS) { setSS(sS); return this; } /** * <p> * An attribute of type Number Set. For example: * </p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * </p> * * @return An attribute of type Number Set. For example:</p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages * and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. */ public java.util.List<String> getNS() { return nS; } /** * <p> * An attribute of type Number Set. For example: * </p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * </p> * * @param nS * An attribute of type Number Set. For example:</p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. */ public void setNS(java.util.Collection<String> nS) { if (nS == null) { this.nS = null; return; } this.nS = new java.util.ArrayList<String>(nS); } /** * <p> * An attribute of type Number Set. For example: * </p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setNS(java.util.Collection)} or {@link #withNS(java.util.Collection)} if you want to override the * existing values. * </p> * * @param nS * An attribute of type Number Set. For example:</p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withNS(String... nS) { if (this.nS == null) { setNS(new java.util.ArrayList<String>(nS.length)); } for (String ele : nS) { this.nS.add(ele); } return this; } /** * <p> * An attribute of type Number Set. For example: * </p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * </p> * * @param nS * An attribute of type Number Set. For example:</p> * <p> * <code>"NS": ["42.2", "-19", "7.5", "3.14"]</code> * </p> * <p> * Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and * libraries. However, DynamoDB treats them as number type attributes for mathematical operations. * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withNS(java.util.Collection<String> nS) { setNS(nS); return this; } /** * <p> * An attribute of type Binary Set. For example: * </p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> * </p> * * @return An attribute of type Binary Set. For example:</p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> */ public java.util.List<java.nio.ByteBuffer> getBS() { return bS; } /** * <p> * An attribute of type Binary Set. For example: * </p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> * </p> * * @param bS * An attribute of type Binary Set. For example:</p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> */ public void setBS(java.util.Collection<java.nio.ByteBuffer> bS) { if (bS == null) { this.bS = null; return; } this.bS = new java.util.ArrayList<java.nio.ByteBuffer>(bS); } /** * <p> * An attribute of type Binary Set. For example: * </p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setBS(java.util.Collection)} or {@link #withBS(java.util.Collection)} if you want to override the * existing values. * </p> * * @param bS * An attribute of type Binary Set. For example:</p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withBS(java.nio.ByteBuffer... bS) { if (this.bS == null) { setBS(new java.util.ArrayList<java.nio.ByteBuffer>(bS.length)); } for (java.nio.ByteBuffer ele : bS) { this.bS.add(ele); } return this; } /** * <p> * An attribute of type Binary Set. For example: * </p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> * </p> * * @param bS * An attribute of type Binary Set. For example:</p> * <p> * <code>"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withBS(java.util.Collection<java.nio.ByteBuffer> bS) { setBS(bS); return this; } /** * <p> * An attribute of type Map. For example: * </p> * <p> * <code>"M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}}</code> * </p> * * @return An attribute of type Map. For example:</p> * <p> * <code>"M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}}</code> */ public java.util.Map<String, AttributeValue> getM() { return m; } /** * <p> * An attribute of type Map. For example: * </p> * <p> * <code>"M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}}</code> * </p> * * @param m * An attribute of type Map. For example:</p> * <p> * <code>"M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}}</code> */ public void setM(java.util.Map<String, AttributeValue> m) { this.m = m; } /** * <p> * An attribute of type Map. For example: * </p> * <p> * <code>"M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}}</code> * </p> * * @param m * An attribute of type Map. For example:</p> * <p> * <code>"M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}}</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withM(java.util.Map<String, AttributeValue> m) { setM(m); return this; } public AttributeValue addMEntry(String key, AttributeValue value) { if (null == this.m) { this.m = new java.util.HashMap<String, AttributeValue>(); } if (this.m.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.m.put(key, value); return this; } /** * Removes all the entries added into M. * * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue clearMEntries() { this.m = null; return this; } /** * <p> * An attribute of type List. For example: * </p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> * </p> * * @return An attribute of type List. For example:</p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> */ public java.util.List<AttributeValue> getL() { return l; } /** * <p> * An attribute of type List. For example: * </p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> * </p> * * @param l * An attribute of type List. For example:</p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> */ public void setL(java.util.Collection<AttributeValue> l) { if (l == null) { this.l = null; return; } this.l = new java.util.ArrayList<AttributeValue>(l); } /** * <p> * An attribute of type List. For example: * </p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setL(java.util.Collection)} or {@link #withL(java.util.Collection)} if you want to override the existing * values. * </p> * * @param l * An attribute of type List. For example:</p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withL(AttributeValue... l) { if (this.l == null) { setL(new java.util.ArrayList<AttributeValue>(l.length)); } for (AttributeValue ele : l) { this.l.add(ele); } return this; } /** * <p> * An attribute of type List. For example: * </p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> * </p> * * @param l * An attribute of type List. For example:</p> * <p> * <code>"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withL(java.util.Collection<AttributeValue> l) { setL(l); return this; } /** * <p> * An attribute of type Null. For example: * </p> * <p> * <code>"NULL": true</code> * </p> * * @param nULLValue * An attribute of type Null. For example:</p> * <p> * <code>"NULL": true</code> */ public void setNULL(Boolean nULLValue) { this.nULLValue = nULLValue; } /** * <p> * An attribute of type Null. For example: * </p> * <p> * <code>"NULL": true</code> * </p> * * @return An attribute of type Null. For example:</p> * <p> * <code>"NULL": true</code> */ public Boolean getNULL() { return this.nULLValue; } /** * <p> * An attribute of type Null. For example: * </p> * <p> * <code>"NULL": true</code> * </p> * * @param nULLValue * An attribute of type Null. For example:</p> * <p> * <code>"NULL": true</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withNULL(Boolean nULLValue) { setNULL(nULLValue); return this; } /** * <p> * An attribute of type Null. For example: * </p> * <p> * <code>"NULL": true</code> * </p> * * @return An attribute of type Null. For example:</p> * <p> * <code>"NULL": true</code> */ public Boolean isNULL() { return this.nULLValue; } /** * <p> * An attribute of type Boolean. For example: * </p> * <p> * <code>"BOOL": true</code> * </p> * * @param bOOL * An attribute of type Boolean. For example:</p> * <p> * <code>"BOOL": true</code> */ public void setBOOL(Boolean bOOL) { this.bOOL = bOOL; } /** * <p> * An attribute of type Boolean. For example: * </p> * <p> * <code>"BOOL": true</code> * </p> * * @return An attribute of type Boolean. For example:</p> * <p> * <code>"BOOL": true</code> */ public Boolean getBOOL() { return this.bOOL; } /** * <p> * An attribute of type Boolean. For example: * </p> * <p> * <code>"BOOL": true</code> * </p> * * @param bOOL * An attribute of type Boolean. For example:</p> * <p> * <code>"BOOL": true</code> * @return Returns a reference to this object so that method calls can be chained together. */ public AttributeValue withBOOL(Boolean bOOL) { setBOOL(bOOL); return this; } /** * <p> * An attribute of type Boolean. For example: * </p> * <p> * <code>"BOOL": true</code> * </p> * * @return An attribute of type Boolean. For example:</p> * <p> * <code>"BOOL": true</code> */ public Boolean isBOOL() { return this.bOOL; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getS() != null) sb.append("S: ").append(getS()).append(","); if (getN() != null) sb.append("N: ").append(getN()).append(","); if (getB() != null) sb.append("B: ").append(getB()).append(","); if (getSS() != null) sb.append("SS: ").append(getSS()).append(","); if (getNS() != null) sb.append("NS: ").append(getNS()).append(","); if (getBS() != null) sb.append("BS: ").append(getBS()).append(","); if (getM() != null) sb.append("M: ").append(getM()).append(","); if (getL() != null) sb.append("L: ").append(getL()).append(","); if (getNULL() != null) sb.append("NULL: ").append(getNULL()).append(","); if (getBOOL() != null) sb.append("BOOL: ").append(getBOOL()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AttributeValue == false) return false; AttributeValue other = (AttributeValue) obj; if (other.getS() == null ^ this.getS() == null) return false; if (other.getS() != null && other.getS().equals(this.getS()) == false) return false; if (other.getN() == null ^ this.getN() == null) return false; if (other.getN() != null && other.getN().equals(this.getN()) == false) return false; if (other.getB() == null ^ this.getB() == null) return false; if (other.getB() != null && other.getB().equals(this.getB()) == false) return false; if (other.getSS() == null ^ this.getSS() == null) return false; if (other.getSS() != null && other.getSS().equals(this.getSS()) == false) return false; if (other.getNS() == null ^ this.getNS() == null) return false; if (other.getNS() != null && other.getNS().equals(this.getNS()) == false) return false; if (other.getBS() == null ^ this.getBS() == null) return false; if (other.getBS() != null && other.getBS().equals(this.getBS()) == false) return false; if (other.getM() == null ^ this.getM() == null) return false; if (other.getM() != null && other.getM().equals(this.getM()) == false) return false; if (other.getL() == null ^ this.getL() == null) return false; if (other.getL() != null && other.getL().equals(this.getL()) == false) return false; if (other.getNULL() == null ^ this.getNULL() == null) return false; if (other.getNULL() != null && other.getNULL().equals(this.getNULL()) == false) return false; if (other.getBOOL() == null ^ this.getBOOL() == null) return false; if (other.getBOOL() != null && other.getBOOL().equals(this.getBOOL()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getS() == null) ? 0 : getS().hashCode()); hashCode = prime * hashCode + ((getN() == null) ? 0 : getN().hashCode()); hashCode = prime * hashCode + ((getB() == null) ? 0 : getB().hashCode()); hashCode = prime * hashCode + ((getSS() == null) ? 0 : getSS().hashCode()); hashCode = prime * hashCode + ((getNS() == null) ? 0 : getNS().hashCode()); hashCode = prime * hashCode + ((getBS() == null) ? 0 : getBS().hashCode()); hashCode = prime * hashCode + ((getM() == null) ? 0 : getM().hashCode()); hashCode = prime * hashCode + ((getL() == null) ? 0 : getL().hashCode()); hashCode = prime * hashCode + ((getNULL() == null) ? 0 : getNULL().hashCode()); hashCode = prime * hashCode + ((getBOOL() == null) ? 0 : getBOOL().hashCode()); return hashCode; } @Override public AttributeValue clone() { try { return (AttributeValue) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() even though we're Cloneable!", e); } } }
1,819
0
Create_ds/Nicobar/nicobar-groovy2/src/test/resources/testmodule
Create_ds/Nicobar/nicobar-groovy2/src/test/resources/testmodule/customizers/TestCompilationCustomizer.java
package testmodule.customizers; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.customizers.CompilationCustomizer; public class TestCompilationCustomizer extends CompilationCustomizer { public TestCompilationCustomizer() { super(CompilePhase.SEMANTIC_ANALYSIS); } @Override public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { // no op customizer }; }
1,820
0
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2/plugin/Groovy2PluginTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.groovy2.plugin; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.fail; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.Callable; import org.apache.commons.io.FileUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.PathScriptArchive; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.execution.HystrixScriptModuleExecutor; import com.netflix.nicobar.core.execution.ScriptModuleExecutable; import com.netflix.nicobar.core.module.ScriptModule; import com.netflix.nicobar.core.module.ScriptModuleLoader; import com.netflix.nicobar.core.module.ScriptModuleUtils; import com.netflix.nicobar.core.plugin.BytecodeLoadingPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import com.netflix.nicobar.groovy2.internal.compile.Groovy2Compiler; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil.TestScript; /** * Integration tests for the Groovy2 language plugin * * @author James Kojo * @author Vasanth Asokan */ public class Groovy2PluginTest { private static final String GROOVY2_COMPILER_PLUGIN = Groovy2CompilerPlugin.class.getName(); private static final Random RANDOM = new Random(System.currentTimeMillis()); private Path uncompilableArchiveDir; private Path uncompilableScriptRelativePath; @BeforeClass public void setup() throws Exception { //Module.setModuleLogger(new StreamModuleLogger(System.err)); uncompilableArchiveDir = Files.createTempDirectory(Groovy2PluginTest.class.getSimpleName()+"_"); FileUtils.forceDeleteOnExit(uncompilableArchiveDir.toFile()); uncompilableScriptRelativePath = Paths.get("Uncompilable.groovy"); byte[] randomBytes = new byte[1024]; RANDOM.nextBytes(randomBytes); Files.write(uncompilableArchiveDir.resolve(uncompilableScriptRelativePath), randomBytes); } @Test public void testLoadSimpleScript() throws Exception { ScriptModuleLoader moduleLoader = createGroovyModuleLoader().build(); // create a new script archive consisting of HellowWorld.groovy and add it the loader. // Declares a dependency on the Groovy2RuntimeModule. Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.HELLO_WORLD); ScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath) .setRecurseRoot(false) .addFile(TestScript.HELLO_WORLD.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.HELLO_WORLD.getModuleId()).build()) .build(); moduleLoader.updateScriptArchives(Collections.singleton(scriptArchive)); // locate the class file in the module and execute it ScriptModule scriptModule = moduleLoader.getScriptModule(TestScript.HELLO_WORLD.getModuleId()); Class<?> clazz = findClassByName(scriptModule, TestScript.HELLO_WORLD); assertGetMessage(clazz, "Hello, World!"); } @Test public void testLoadScriptWithInterface() throws Exception { ScriptModuleLoader moduleLoader = createGroovyModuleLoader().build(); Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.IMPLEMENTS_INTERFACE); ScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath) .setRecurseRoot(false) .addFile(TestScript.IMPLEMENTS_INTERFACE.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.IMPLEMENTS_INTERFACE.getModuleId()).build()) .build(); moduleLoader.updateScriptArchives(Collections.singleton(scriptArchive)); // locate the class file in the module and execute it via the executor ScriptModuleExecutable<String> executable = new ScriptModuleExecutable<String>() { @SuppressWarnings({"rawtypes","unchecked"}) @Override public String execute(ScriptModule scriptModule) throws Exception { Class<Callable> callable = (Class<Callable>) ScriptModuleUtils.findAssignableClass(scriptModule, Callable.class); assertNotNull(callable, "couldn't find Callable for module " + scriptModule.getModuleId()); Callable<String> instance = callable.newInstance(); String result = instance.call(); return result; } }; HystrixScriptModuleExecutor<String> executor = new HystrixScriptModuleExecutor<String>("TestModuleExecutor"); List<String> results = executor.executeModules(Collections.singletonList(TestScript.IMPLEMENTS_INTERFACE.getModuleId()), executable, moduleLoader); assertEquals(results, Collections.singletonList("I'm a Callable<String>")); } /** * Test loading/executing a script which has a dependency on a library */ @Test public void testLoadScriptWithLibrary() throws Exception { ScriptModuleLoader moduleLoader = createGroovyModuleLoader().build(); Path dependsOnARootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.DEPENDS_ON_A); ScriptArchive dependsOnAArchive = new PathScriptArchive.Builder(dependsOnARootPath) .setRecurseRoot(false) .addFile(TestScript.DEPENDS_ON_A.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.DEPENDS_ON_A.getModuleId()) .addModuleDependency(TestScript.LIBRARY_A.getModuleId()) .build()) .build(); Path libARootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.LIBRARY_A); ScriptArchive libAArchive = new PathScriptArchive.Builder(libARootPath) .setRecurseRoot(false) .addFile(TestScript.LIBRARY_A.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.LIBRARY_A.getModuleId()).build()) .build(); // load them in dependency order to make sure that transitive dependency resolution is working moduleLoader.updateScriptArchives(new LinkedHashSet<ScriptArchive>(Arrays.asList(dependsOnAArchive, libAArchive))); // locate the class file in the module and execute it ScriptModule scriptModule = moduleLoader.getScriptModule(TestScript.DEPENDS_ON_A.getModuleId()); Class<?> clazz = findClassByName(scriptModule, TestScript.DEPENDS_ON_A); assertGetMessage(clazz, "DepondOnA: Called LibraryA and got message:'I'm LibraryA!'"); } /** * Test loading/executing a script which has a dependency on a library */ @Test public void testReloadLibrary() throws Exception { ScriptModuleLoader moduleLoader = createGroovyModuleLoader().build(); Path dependsOnARootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.DEPENDS_ON_A); ScriptArchive dependsOnAArchive = new PathScriptArchive.Builder(dependsOnARootPath) .setRecurseRoot(false) .addFile(TestScript.DEPENDS_ON_A.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.DEPENDS_ON_A.getModuleId()) .addModuleDependency(TestScript.LIBRARY_A.getModuleId()) .build()) .build(); Path libARootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.LIBRARY_A); ScriptArchive libAArchive = new PathScriptArchive.Builder(libARootPath) .setRecurseRoot(false) .addFile(TestScript.LIBRARY_A.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.LIBRARY_A.getModuleId()).build()) .build(); moduleLoader.updateScriptArchives(new LinkedHashSet<ScriptArchive>(Arrays.asList(dependsOnAArchive, libAArchive))); // reload the library with version 2 Path libAV2RootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.LIBRARY_AV2); ScriptArchive libAV2Archive = new PathScriptArchive.Builder(libAV2RootPath) .setRecurseRoot(false) .addFile(TestScript.LIBRARY_AV2.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.LIBRARY_A.getModuleId()).build()) .build(); moduleLoader.updateScriptArchives(Collections.singleton(libAV2Archive)); // find the dependent and execute it ScriptModule scriptModuleDependOnA = moduleLoader.getScriptModule(TestScript.DEPENDS_ON_A.getModuleId()); Class<?> clazz = findClassByName(scriptModuleDependOnA, TestScript.DEPENDS_ON_A); assertGetMessage(clazz, "DepondOnA: Called LibraryA and got message:'I'm LibraryA V2!'"); } /** * Tests that if we deploy an uncompilable dependency, the dependents continue to function */ @Test public void testDeployBadDependency() throws Exception { ScriptModuleLoader moduleLoader = createGroovyModuleLoader().build(); Path dependsOnARootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.DEPENDS_ON_A); ScriptArchive dependsOnAArchive = new PathScriptArchive.Builder(dependsOnARootPath) .setRecurseRoot(false) .addFile(TestScript.DEPENDS_ON_A.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.DEPENDS_ON_A.getModuleId()) .addModuleDependency(TestScript.LIBRARY_A.getModuleId()) .build()) .build(); Path libARootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.LIBRARY_A); ScriptArchive libAArchive = new PathScriptArchive.Builder(libARootPath) .setRecurseRoot(false) .addFile(TestScript.LIBRARY_A.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.LIBRARY_A.getModuleId()).build()) .build(); moduleLoader.updateScriptArchives(new LinkedHashSet<ScriptArchive>(Arrays.asList(dependsOnAArchive, libAArchive))); assertEquals(moduleLoader.getAllScriptModules().size(), 2); // attempt reload library-A with invalid groovy libAArchive = new PathScriptArchive.Builder(uncompilableArchiveDir) .setRecurseRoot(false) .addFile(uncompilableScriptRelativePath) .setModuleSpec(createGroovyModuleSpec(TestScript.LIBRARY_A.getModuleId()).build()) .build(); moduleLoader.updateScriptArchives(new LinkedHashSet<ScriptArchive>(Arrays.asList(libAArchive))); assertEquals(moduleLoader.getAllScriptModules().size(), 2); // find the dependent and execute it ScriptModule scriptModuleDependOnA = moduleLoader.getScriptModule(TestScript.DEPENDS_ON_A.getModuleId()); Class<?> clazz = findClassByName(scriptModuleDependOnA, TestScript.DEPENDS_ON_A); assertGetMessage(clazz, "DepondOnA: Called LibraryA and got message:'I'm LibraryA!'"); } /** * Test loading a module which is composed of several interdependent scripts. * InternalDepdencyA->InternalDepdencyB-InternalDepdencyC->InternalDepdencyD */ @Test public void testLoadScriptWithInternalDependencies() throws Exception { ScriptModuleLoader moduleLoader = createGroovyModuleLoader().build(); Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.INTERNAL_DEPENDENCY_A); ScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath) .setRecurseRoot(false) .addFile(Paths.get("InternalDependencyB.groovy")) .addFile(Paths.get("InternalDependencyA.groovy")) .addFile(Paths.get("InternalDependencyD.groovy")) .addFile(Paths.get("subpackage/InternalDependencyC.groovy")) .setModuleSpec(createGroovyModuleSpec(TestScript.INTERNAL_DEPENDENCY_A.getModuleId()).build()) .build(); moduleLoader.updateScriptArchives(Collections.singleton(scriptArchive)); // locate the class file in the module and execute it ScriptModule scriptModule = moduleLoader.getScriptModule(TestScript.INTERNAL_DEPENDENCY_A.getModuleId()); Class<?> clazz = findClassByName(scriptModule, TestScript.INTERNAL_DEPENDENCY_A); assertGetMessage(clazz, "I'm A. Called B and got: I'm B. Called C and got: I'm C. Called D and got: I'm D."); } @Test public void testMixedModule() throws Exception { ScriptModuleLoader.Builder moduleLoaderBuilder = createGroovyModuleLoader(); ScriptModuleLoader loader = moduleLoaderBuilder.addPluginSpec( new ScriptCompilerPluginSpec.Builder(BytecodeLoadingPlugin.PLUGIN_ID) .withPluginClassName(BytecodeLoadingPlugin.class.getName()).build()) .build(); Path jarPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.MIXED_MODULE).resolve(TestScript.MIXED_MODULE.getScriptPath()); ScriptArchive archive = new JarScriptArchive.Builder(jarPath).build(); loader.updateScriptArchives(Collections.singleton(archive)); ScriptModule scriptModule = loader.getScriptModule(TestScript.MIXED_MODULE.getModuleId()); Class<?> clazz = findClassByName(scriptModule, TestScript.MIXED_MODULE); Object instance = clazz.newInstance(); Method method = clazz.getMethod("execute"); String message = (String)method.invoke(instance); assertEquals(message, "Hello Mixed Module!"); // Verify groovy class clazz = findClassByName(scriptModule, "com.netflix.nicobar.test.HelloBytecode"); method = clazz.getMethod("execute"); message = (String)method.invoke(clazz.newInstance()); assertEquals(message, "Hello Bytecode!"); } /** * Test loading/executing a script with app package import filters, * and which is dependent a library. * */ @Test public void testLoadScriptWithAppImports() throws Exception { ScriptModuleLoader moduleLoader = createGroovyModuleLoader().build(); Path dependsOnARootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.DEPENDS_ON_A); ScriptArchive dependsOnAArchive = new PathScriptArchive.Builder(dependsOnARootPath) .setRecurseRoot(false) .addFile(TestScript.DEPENDS_ON_A.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.DEPENDS_ON_A.getModuleId()) .addModuleDependency(TestScript.LIBRARY_A.getModuleId()) .addAppImportFilter("test") .build()) .build(); Path libARootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.LIBRARY_A); ScriptArchive libAArchive = new PathScriptArchive.Builder(libARootPath) .setRecurseRoot(false) .addFile(TestScript.LIBRARY_A.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.LIBRARY_A.getModuleId()) .addAppImportFilter("test") .build()) .build(); // load them in dependency order to make sure that transitive dependency resolution is working moduleLoader.updateScriptArchives(new LinkedHashSet<ScriptArchive>(Arrays.asList(dependsOnAArchive, libAArchive))); // locate the class file in the module and execute it ScriptModule scriptModule = moduleLoader.getScriptModule(TestScript.DEPENDS_ON_A.getModuleId()); Class<?> clazz = findClassByName(scriptModule, TestScript.DEPENDS_ON_A); assertGetMessage(clazz, "DepondOnA: Called LibraryA and got message:'I'm LibraryA!'"); } /** * Create a module loader this is wired up with the groovy compiler plugin */ private ScriptModuleLoader.Builder createGroovyModuleLoader() throws Exception { // create the groovy plugin spec. this plugin specified a new module and classloader called "Groovy2Runtime" // which contains the groovy-all-2.1.6.jar and the nicobar-groovy2 project. ScriptCompilerPluginSpec pluginSpec = new ScriptCompilerPluginSpec.Builder(Groovy2Compiler.GROOVY2_COMPILER_ID) .addRuntimeResource(GroovyTestResourceUtil.getGroovyRuntime()) .addRuntimeResource(GroovyTestResourceUtil.getGroovyPluginLocation()) // hack to make the gradle build work. still doesn't seem to properly instrument the code // should probably add a classloader dependency on the system classloader instead .addRuntimeResource(GroovyTestResourceUtil.getCoberturaJar(getClass().getClassLoader())) .withPluginClassName(GROOVY2_COMPILER_PLUGIN) .build(); // create and start the builder with the plugin return new ScriptModuleLoader.Builder().addPluginSpec(pluginSpec); } /** * Create a module spec builder with pre-populated groovy dependency */ private ScriptModuleSpec.Builder createGroovyModuleSpec(String moduleId) { return new ScriptModuleSpec.Builder(moduleId) .addCompilerPluginId(Groovy2CompilerPlugin.PLUGIN_ID); } private Class<?> findClassByName(ScriptModule scriptModule, TestScript testScript) { assertNotNull(scriptModule, "Missing scriptModule for " + testScript); return findClassByName(scriptModule, testScript.getClassName()); } private Class<?> findClassByName(ScriptModule scriptModule, String className) { Set<Class<?>> classes = scriptModule.getLoadedClasses(); for (Class<?> clazz : classes) { if (clazz.getName().equals(className)) { return clazz; } } fail("couldn't find class " + className); return null; } private void assertGetMessage(Class<?> targetClass, String expectedMessage) throws Exception { Object instance = targetClass.newInstance(); Method method = targetClass.getMethod("getMessage"); String message = (String)method.invoke(instance); assertEquals(message, expectedMessage); } }
1,821
0
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2/plugin/ScriptModuleUtilsTest.java
package com.netflix.nicobar.groovy2.plugin; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import org.testng.annotations.Test; import com.google.common.collect.Sets; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.PathScriptArchive; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.module.ScriptModule; import com.netflix.nicobar.core.module.ScriptModuleLoader; import com.netflix.nicobar.core.module.ScriptModuleUtils; import com.netflix.nicobar.core.plugin.BytecodeLoadingPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import com.netflix.nicobar.groovy2.internal.compile.Groovy2Compiler; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil.TestScript; /** * Unit tests for {@link ScriptModuleUtils} * * @author Vasanth Asokan */ public class ScriptModuleUtilsTest { private ScriptModuleLoader moduleLoader; /** * Convert a groovy based ScriptModule to a bytecode ScriptArchive * using {@link ScriptModuleUtils.toCompiledScriptArchive()} and * ensure that it works the same. * * @throws Exception */ @Test public void testScriptModuleConversion() throws Exception { Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.HELLO_WORLD); ScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath) .setRecurseRoot(false) .addFile(TestScript.HELLO_WORLD.getScriptPath()) .setModuleSpec(createGroovyModuleSpec(TestScript.HELLO_WORLD.getModuleId()).build()) .build(); moduleLoader = createGroovyModuleLoader().build(); moduleLoader.updateScriptArchives(Collections.singleton(scriptArchive)); // locate the class file in the module and execute it ScriptModule scriptModule = moduleLoader.getScriptModule(TestScript.HELLO_WORLD.getModuleId()); assertNotNull(scriptModule); Path tmpDir = Files.createTempDirectory("ScriptModuleUtilsTest"); Path convertedJarPath = tmpDir.resolve("converted.jar"); ScriptModuleUtils.toCompiledScriptArchive(scriptModule, convertedJarPath, Sets.newHashSet(".class", ".groovy")); moduleLoader.removeScriptModule(ModuleId.create(TestScript.HELLO_WORLD.getModuleId())); // Now load the module again from the the converted jar archive JarScriptArchive convertedJarArchive = new JarScriptArchive.Builder(convertedJarPath).build(); moduleLoader.updateScriptArchives(Collections.singleton(convertedJarArchive)); scriptModule = moduleLoader.getScriptModule(TestScript.HELLO_WORLD.getModuleId()); assertNotNull(scriptModule); Class<?> targetClass = ScriptModuleUtils.findClass(scriptModule, "HelloWorld"); Object instance = targetClass.newInstance(); Method method = targetClass.getMethod("getMessage"); String message = (String)method.invoke(instance); assertEquals(message, "Hello, World!"); } private ScriptModuleLoader.Builder createGroovyModuleLoader() throws Exception { // create the groovy plugin spec. this plugin specified a new module and classloader called "Groovy2Runtime" // which contains the groovy-all-2.1.6.jar and the nicobar-groovy2 project. ScriptCompilerPluginSpec pluginSpec = new ScriptCompilerPluginSpec.Builder(Groovy2Compiler.GROOVY2_COMPILER_ID) .addRuntimeResource(GroovyTestResourceUtil.getGroovyRuntime()) .addRuntimeResource(GroovyTestResourceUtil.getGroovyPluginLocation()) // hack to make the gradle build work. still doesn't seem to properly instrument the code // should probably add a classloader dependency on the system classloader instead .addRuntimeResource(GroovyTestResourceUtil.getCoberturaJar(getClass().getClassLoader())) .withPluginClassName(Groovy2CompilerPlugin.class.getName()) .build(); // Create a compiler spec for the bytecode loading plugin ScriptCompilerPluginSpec bytecodeCompilerSpec = new ScriptCompilerPluginSpec.Builder(BytecodeLoadingPlugin.PLUGIN_ID) .withPluginClassName(BytecodeLoadingPlugin.class.getName()) .build(); // create and start the builder with the plugin return new ScriptModuleLoader.Builder().addPluginSpec(pluginSpec).addPluginSpec(bytecodeCompilerSpec); } /** * Create a module spec builder with pre-populated groovy dependency */ private ScriptModuleSpec.Builder createGroovyModuleSpec(String moduleId) { return new ScriptModuleSpec.Builder(moduleId) .addCompilerPluginId(Groovy2CompilerPlugin.PLUGIN_ID); } }
1,822
0
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2/compile/Groovy2CompilerTest.java
package com.netflix.nicobar.groovy2.compile; import static org.testng.Assert.assertTrue; import java.lang.reflect.Field; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.PathScriptArchive; import com.netflix.nicobar.groovy2.internal.compile.Groovy2Compiler; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil.TestScript; public class Groovy2CompilerTest { @SuppressWarnings("unchecked") @Test public void testCustomiizerParamsProcessing() throws Exception { Groovy2Compiler compiler; List<CompilationCustomizer> customizers; Map<String, Object> compilerParams; Field f = Groovy2Compiler.class.getDeclaredField("customizerClassNames"); f.setAccessible(true); // empty parameters map compiler = new Groovy2Compiler(new HashMap<String, Object>()); customizers = (List<CompilationCustomizer>)f.get(compiler); assertTrue(customizers.size() == 0, "no valid objects expected"); // null value customizers parameter compilerParams = new HashMap<String, Object>(); compilerParams.put(Groovy2Compiler.GROOVY2_COMPILER_PARAMS_CUSTOMIZERS, null); compiler = new Groovy2Compiler(compilerParams); customizers = (List)f.get(compiler); assertTrue(customizers.size() == 0, "no valid objects expected"); // list with valid customizer compilerParams = new HashMap<String, Object>(); compilerParams.put(Groovy2Compiler.GROOVY2_COMPILER_PARAMS_CUSTOMIZERS, Arrays.asList(new String[] {"org.codehaus.groovy.control.customizers.ImportCustomizer"})); compiler = new Groovy2Compiler(compilerParams); customizers = (List)f.get(compiler); assertTrue(customizers.size() == 1, "one valid object expected"); // list with invalid objects compilerParams = new HashMap<String, Object>(); compilerParams.put(Groovy2Compiler.GROOVY2_COMPILER_PARAMS_CUSTOMIZERS, Arrays.asList(new Object[] {"org.codehaus.groovy.control.customizers.ImportCustomizer", "org.codehaus.groovy.control.customizers.ImportCustomizer", new HashMap<String, Object>(), null})); compiler = new Groovy2Compiler(compilerParams); customizers = (List)f.get(compiler); assertTrue(customizers.size() == 2, "two valid objects expected"); } @Test public void testCompile() throws Exception { Groovy2Compiler compiler; List<CompilationCustomizer> customizers; Map<String, Object> compilerParams; Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.HELLO_WORLD); PathScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath) .setRecurseRoot(false) .addFile(TestScript.HELLO_WORLD.getScriptPath()) .build(); compilerParams = new HashMap<String, Object>(); compilerParams.put(Groovy2Compiler.GROOVY2_COMPILER_PARAMS_CUSTOMIZERS, Arrays.asList(new Object[] {"testmodule.customizers.TestCompilationCustomizer"})); compiler = new Groovy2Compiler(compilerParams); compiler.compile(scriptArchive, null, scriptRootPath); } }
1,823
0
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2/compile/Groovy2CompilerHelperTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.groovy2.compile; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertNotNull; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.codehaus.groovy.tools.GroovyClass; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.PathScriptArchive; import com.netflix.nicobar.groovy2.internal.compile.Groovy2CompilerHelper; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil; import com.netflix.nicobar.groovy2.testutil.GroovyTestResourceUtil.TestScript; /** * Unit Tests for {@link Groovy2CompilerHelper} * * @author James Kojo * @author Vasanth Asokan */ public class Groovy2CompilerHelperTest { /** * Compile using current classloader, and no dependencies * @throws Exception */ @Test public void testSimpleCompile() throws Exception { Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.HELLO_WORLD); PathScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath) .setRecurseRoot(false) .addFile(TestScript.HELLO_WORLD.getScriptPath()) .build(); Set<GroovyClass> compiledClasses = new Groovy2CompilerHelper(Files.createTempDirectory("Groovy2CompilerHelperTest")) .addScriptArchive(scriptArchive) .compile(); assertFalse(CollectionUtils.isEmpty(compiledClasses)); TestByteLoadingClassLoader testClassLoader = new TestByteLoadingClassLoader(getClass().getClassLoader(), compiledClasses); Class<?> loadedClass = testClassLoader.loadClass(TestScript.HELLO_WORLD.getClassName()); assertNotNull(loadedClass); Object instance = loadedClass.newInstance(); Method method = loadedClass.getMethod("getMessage"); String message = (String)method.invoke(instance); assertEquals(message, "Hello, World!"); } /** * Compile with custom config * @throws Exception */ @Test public void testCompileWithCompilerCustomizer() throws Exception { Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.HELLO_WORLD); PathScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath) .setRecurseRoot(false) .addFile(TestScript.HELLO_WORLD.getScriptPath()) .build(); TestCompilationCustomizer customizer = new TestCompilationCustomizer(); CompilerConfiguration compilerConfig = new CompilerConfiguration(); compilerConfig.addCompilationCustomizers(customizer); Set<GroovyClass> compiledClasses = new Groovy2CompilerHelper(Files.createTempDirectory("Groovy2CompilerHelperTest")) .addScriptArchive(scriptArchive) .withConfiguration(compilerConfig) .compile(); assertTrue(customizer.isExecuted(), "customizer has not been executed"); assertFalse(CollectionUtils.isEmpty(compiledClasses)); TestByteLoadingClassLoader testClassLoader = new TestByteLoadingClassLoader(getClass().getClassLoader(), compiledClasses); Class<?> loadedClass = testClassLoader.loadClass(TestScript.HELLO_WORLD.getClassName()); assertNotNull(loadedClass); Object instance = loadedClass.newInstance(); Method method = loadedClass.getMethod("getMessage"); String message = (String)method.invoke(instance); assertEquals(message, "Hello, World!"); } /** * Compile a script with a package name using current classloader, and no dependencies */ @Test public void testCompileWithPackage() throws Exception { Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.HELLO_PACKAGE); PathScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath) .setRecurseRoot(false) .addFile(TestScript.HELLO_PACKAGE.getScriptPath()) .build(); Set<GroovyClass> compiledClasses = new Groovy2CompilerHelper(Files.createTempDirectory("Groovy2CompilerHelperTest")) .addScriptArchive(scriptArchive) .compile(); assertFalse(CollectionUtils.isEmpty(compiledClasses)); TestByteLoadingClassLoader testClassLoader = new TestByteLoadingClassLoader(getClass().getClassLoader(), compiledClasses); Class<?> loadedClass = testClassLoader.loadClass(TestScript.HELLO_PACKAGE.getClassName()); assertNotNull(loadedClass); Object instance = loadedClass.newInstance(); Method method = loadedClass.getMethod("getMessage"); String message = (String)method.invoke(instance); assertEquals(message, "Hello, Package!"); } /** * Test class loader that can load bytes provided by the groovy compiler */ public static class TestByteLoadingClassLoader extends ClassLoader { private final Map<String, byte[]> classBytes; public TestByteLoadingClassLoader(ClassLoader parentClassLoader, Set<GroovyClass> groovyClasses) { super(parentClassLoader); this.classBytes = new HashMap<String, byte[]>(); for (GroovyClass groovyClass : groovyClasses) { classBytes.put(groovyClass.getName(), groovyClass.getBytes()); } } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] bytes = classBytes.get(name); if (bytes == null) { throw new ClassNotFoundException("Couldn't find " + name); } return defineClass(name, bytes, 0, bytes.length); } } /** * Test compilation customizer */ private static class TestCompilationCustomizer extends CompilationCustomizer { private boolean executed = false; public TestCompilationCustomizer() { super(CompilePhase.SEMANTIC_ANALYSIS); } public boolean isExecuted() { return this.executed; } @Override public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { this.executed = true; }; } }
1,824
0
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2
Create_ds/Nicobar/nicobar-groovy2/src/test/java/com/netflix/nicobar/groovy2/testutil/GroovyTestResourceUtil.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.groovy2.testutil; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import javax.annotation.Nullable; import com.netflix.nicobar.core.archive.PathScriptArchive; import com.netflix.nicobar.core.utils.ClassPathUtils; import com.netflix.nicobar.groovy2.plugin.Groovy2CompilerPlugin; /** * utility class for finding test resources such as scripts * * @author James Kojo * @author Vasanth Asokan */ public class GroovyTestResourceUtil { /** name of the root directory where the test modules are located */ private static final String TEST_MODULES_BASE_DIR = "testmodules"; /** * Metadata for test script found in test/resource. * Use in conjunction with {@link GroovyTestResourceUtil#findRootPathForScript(TestScript)}. */ public static enum TestScript { HELLO_WORLD("helloworld", "HelloWorld.groovy", "HelloWorld"), HELLO_PACKAGE("hellopackage", "package1/HelloPackage.groovy", "package1.HelloPackage"), LIBRARY_A("libA", "LibraryA.groovy", "LibraryA"), LIBRARY_AV2("libAV2", "LibraryA.groovy", "LibraryA"), DEPENDS_ON_A("dependsonA", "DependsOnA.groovy", "DependsOnA"), INTERNAL_DEPENDENCY_A("internaldependencies", "InternalDependencyA.groovy", "InternalDependencyA"), IMPLEMENTS_INTERFACE("implementsinterface", "MyCallable.groovy", "MyCallable"), MIXED_MODULE("mixedmodule", "mixedmodule.jar", "com.netflix.nicobar.test.MixedModule"); private String moduleId; private final Path scriptPath; private final String className; private TestScript(String moduleId, String resourcePath, String className) { this.moduleId = moduleId; this.scriptPath = Paths.get(resourcePath); this.className = className; } /** * @return relative path suitable for passing to {@link PathScriptArchive.Builder#addFile(Path)} */ public Path getScriptPath() { return scriptPath; } /** * @return name of the resultant class after it's been loaded */ public String getClassName() { return className; } /** * @return the default moduleId if this script is converted to an archive */ public String getModuleId() { return moduleId; } } /** * Locate the root directory for the given script in the class path. Used for * generating the root path for the {@link PathScriptArchive} * * @param script script identifier * @return absolute path to the root of the script */ public static Path findRootPathForScript(TestScript script) throws Exception { URL resourceUrl = GroovyTestResourceUtil.class.getClassLoader().getResource(TEST_MODULES_BASE_DIR + "/" + script.getModuleId()); assertNotNull(resourceUrl, "couldn't locate directory for script " + script.getModuleId()); assertEquals(resourceUrl.getProtocol(), "file"); return Paths.get(resourceUrl.getFile()); } /** * locate the groovy-all jar on the classpath */ public static Path getGroovyRuntime() { // assume that the classloader of this test has the runtime in it's classpath. // further assume that the runtime contains the file "groovy-release-info.properties" // which it had at the time of groovy-all-2.1.6.jar Path path = ClassPathUtils.findRootPathForResource("META-INF/groovy-release-info.properties", GroovyTestResourceUtil.class.getClassLoader()); assertNotNull(path, "coudln't find groovy-all jar"); return path; } /** * Locate the classpath root which contains the nicobar-groovy2 project */ public static Path getGroovyPluginLocation() { Path path = ClassPathUtils.findRootPathForClass(Groovy2CompilerPlugin.class); assertNotNull(path, "nicobar-groovy2 project on classpath."); return path; } /** * Locate the cobertura jar * @param classLoader {@link ClassLoader} to search * @return path of the jar or null if not present */ @Nullable public static Path getCoberturaJar(ClassLoader classLoader) { return ClassPathUtils.findRootPathForResource("net/sourceforge/cobertura/coveragedata/HasBeenInstrumented.class", GroovyTestResourceUtil.class.getClassLoader()); } }
1,825
0
Create_ds/Nicobar/nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2
Create_ds/Nicobar/nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/plugin/Groovy2CompilerPlugin.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.groovy2.plugin; import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.plugin.ScriptCompilerPlugin; import com.netflix.nicobar.groovy2.internal.compile.Groovy2Compiler; /** * Factory class for the Groovy 2 language plug-in * * @author James Kojo * @author Vasanth Asokan */ public class Groovy2CompilerPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "groovy2"; public Groovy2CompilerPlugin() { } @Override public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) { return Collections.singleton(new Groovy2Compiler(compilerParams)); } }
1,826
0
Create_ds/Nicobar/nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal
Create_ds/Nicobar/nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal/compile/Groovy2Compiler.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.groovy2.internal.compile; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.compile.ScriptCompilationException; import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; /** * Groovy specific implementation of the {@link ScriptArchiveCompiler} * * @author James Kojo * @author Vasanth Asokan */ public class Groovy2Compiler implements ScriptArchiveCompiler { public final static String GROOVY2_COMPILER_ID = "groovy2"; public final static String GROOVY2_COMPILER_PARAMS_CUSTOMIZERS = "customizerClassNames"; private List<String> customizerClassNames = new LinkedList<String>(); public Groovy2Compiler(Map<String, Object> compilerParams) { this.processCompilerParams(compilerParams); } private void processCompilerParams(Map<String, Object> compilerParams) { // filtering compilation customizers class names if (compilerParams.containsKey(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS)) { Object customizers = compilerParams.get(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS); if (customizers instanceof List) { for (Object customizerClassName: (List<?>) customizers) { if (customizerClassName instanceof String) { this.customizerClassNames.add((String)customizerClassName); } } } } } private CompilationCustomizer getCustomizerInstanceFromString(String className, JBossModuleClassLoader moduleClassLoader) { CompilationCustomizer instance = null; try { // TODO: replace JBossModuleClassLoader with generic class loader ClassLoader classLoader = moduleClassLoader != null ? moduleClassLoader : Thread.currentThread().getContextClassLoader(); Class<?> klass = classLoader.loadClass(className); instance = (CompilationCustomizer)klass.newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ClassCastException e) { e.printStackTrace(); // TODO: add logger support for compiler (due to a separate class loader logger is not visible) } return instance; } @Override public boolean shouldCompile(ScriptArchive archive) { return archive.getModuleSpec().getCompilerPluginIds().contains(GROOVY2_COMPILER_ID); } @Override public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path compilationRootDir) throws ScriptCompilationException, IOException { List<CompilationCustomizer> customizers = new LinkedList<CompilationCustomizer>(); for (String klassName: this.customizerClassNames) { CompilationCustomizer instance = this.getCustomizerInstanceFromString(klassName, moduleClassLoader); if (instance != null ) { customizers.add(instance); } } CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT); config.addCompilationCustomizers(customizers.toArray(new CompilationCustomizer[0])); new Groovy2CompilerHelper(compilationRootDir) .addScriptArchive(archive) .withParentClassloader(moduleClassLoader) // TODO: replace JBossModuleClassLoader with generic class loader .withConfiguration(config) .compile(); return Collections.emptySet(); } }
1,827
0
Create_ds/Nicobar/nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal
Create_ds/Nicobar/nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal/compile/Groovy2CompilerHelper.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.groovy2.internal.compile; import groovy.lang.GroovyClassLoader; import java.io.IOException; import java.nio.file.Path; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Set; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.tools.GroovyClass; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.compile.ScriptCompilationException; /** * Helper class for compiling Groovy files into classes. This class takes as it's input a collection * of {@link ScriptArchive}s and outputs a {@link GroovyClassLoader} with the classes pre-loaded into it. * * If a parent {@link ClassLoader} is not provided, the current thread context classloader is used. * * @author James Kojo * @author Vasanth Asokan */ public class Groovy2CompilerHelper { private final Path targetDir; private final List<Path> sourceFiles = new LinkedList<Path>(); private final List<ScriptArchive> scriptArchives = new LinkedList<ScriptArchive>(); private ClassLoader parentClassLoader; private CompilerConfiguration compileConfig; public Groovy2CompilerHelper(Path targetDir) { Objects.requireNonNull(targetDir, "targetDir"); this.targetDir = targetDir; } public Groovy2CompilerHelper withParentClassloader(ClassLoader parentClassLoader) { this.parentClassLoader = parentClassLoader; return this; } public Groovy2CompilerHelper addSourceFile(Path groovyFile) { if (groovyFile != null) { sourceFiles.add(groovyFile); } return this; } public Groovy2CompilerHelper addScriptArchive(ScriptArchive archive) { if (archive != null) { scriptArchives.add(archive); } return this; } public Groovy2CompilerHelper withConfiguration(CompilerConfiguration compilerConfig) { if (compilerConfig != null) { this.compileConfig = compilerConfig; } return this; } /** * Compile the given source and load the resultant classes into a new {@link ClassNotFoundException} * @return initialized and laoded classes * @throws ScriptCompilationException */ @SuppressWarnings("unchecked") public Set<GroovyClass> compile() throws ScriptCompilationException { final CompilerConfiguration conf = compileConfig != null ? compileConfig: CompilerConfiguration.DEFAULT; conf.setTolerance(0); conf.setVerbose(true); conf.setTargetDirectory(targetDir.toFile()); final ClassLoader buildParentClassloader = parentClassLoader != null ? parentClassLoader : Thread.currentThread().getContextClassLoader(); GroovyClassLoader groovyClassLoader = AccessController.doPrivileged(new PrivilegedAction<GroovyClassLoader>() { public GroovyClassLoader run() { return new GroovyClassLoader(buildParentClassloader, conf, false); } }); CompilationUnit unit = new CompilationUnit(conf, null, groovyClassLoader); Set<String> scriptExtensions = conf.getScriptExtensions(); try { for (ScriptArchive scriptArchive : scriptArchives) { Set<String> entryNames = scriptArchive.getArchiveEntryNames(); for (String entryName : entryNames) { for (String extension : scriptExtensions) { if (entryName.endsWith(extension)) { // identified groovy file unit.addSource(scriptArchive.getEntry(entryName)); } } } } } catch (IOException e) { throw new ScriptCompilationException("Exception loading source files", e); } for (Path sourceFile : sourceFiles) { unit.addSource(sourceFile.toFile()); } try { unit.compile(Phases.OUTPUT); } catch (CompilationFailedException e) { throw new ScriptCompilationException("Exception during script compilation", e); } return new HashSet<GroovyClass>(unit.getClasses()); } }
1,828
0
Create_ds/Nicobar/nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2
Create_ds/Nicobar/nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/utils/Groovy2PluginUtils.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.groovy2.utils; import java.nio.file.Path; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import com.netflix.nicobar.core.utils.ClassPathUtils; import com.netflix.nicobar.groovy2.plugin.Groovy2CompilerPlugin; /** * Utility class for working with nicobar-groovy2 * @author Vasanth Asokan */ public class Groovy2PluginUtils { /** * Helper method to orchestrate commonly required setup of nicobar-groovy2, and return a groovy2 compiler spec. * @return a {@link ScriptCompilerPluginSpec} that is instantiated for the Groovy2 language, and is specified to * depend on both the underyling groovy runtime, as well as nicobar-groov2. */ public static ScriptCompilerPluginSpec getCompilerSpec() { Path groovyRuntimePath = ClassPathUtils.findRootPathForResource("META-INF/groovy-release-info.properties", Groovy2PluginUtils.class.getClassLoader()); if (groovyRuntimePath == null) { throw new IllegalStateException("couldn't find groovy-all.n.n.n.jar in the classpath."); } String resourceName = ClassPathUtils.classNameToResourceName(Groovy2CompilerPlugin.class.getName()); Path nicobarGroovyPluginPath = ClassPathUtils.findRootPathForResource(resourceName, Groovy2PluginUtils.class.getClassLoader()); if (nicobarGroovyPluginPath == null) { throw new IllegalStateException("couldn't find nicobar-groovy2 in the classpath."); } // Create the compiler spec ScriptCompilerPluginSpec compilerSpec = new ScriptCompilerPluginSpec.Builder(Groovy2CompilerPlugin.PLUGIN_ID) .withPluginClassName(Groovy2CompilerPlugin.class.getName()) .addRuntimeResource(groovyRuntimePath) .addRuntimeResource(nicobarGroovyPluginPath) .build(); return compilerSpec; } }
1,829
0
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/interfaces-module/src/main/java
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/interfaces-module/src/main/java/interfaces/Manager.java
package interfaces; /** * @author Aaron Tull * */ public interface Manager { public String supervise(Helper worker); }
1,830
0
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/interfaces-module/src/main/java
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/interfaces-module/src/main/java/interfaces/Helper.java
package interfaces; /** * @author Aaron Tull * */ public interface Helper { public String doWork(); }
1,831
0
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/classpath-dependent-module/src/main
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/classpath-dependent-module/src/main/java/DependentClass.java
import org.jboss.modules.Module; public class DependentClass { /** * * Try to access a class from the application classpath * This will fail if app import filters block it, and pass * if it is allowed. * */ public DependentClass() { // We know Module is in the classpath of the test Module.forClass(Object.class); } }
1,832
0
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/service-module/src/main/java/com/netflix/nicobar
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/service-module/src/main/java/com/netflix/nicobar/test/Service.java
package com.netflix.nicobar.test; public class Service { public String service() { return "From Module"; } }
1,833
0
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/dependent-module/src/main/java/com/netflix/nicobar
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/dependent-module/src/main/java/com/netflix/nicobar/test/Dependent.java
package com.netflix.nicobar.test; import com.netflix.nicobar.test.Service; public class Dependent { public static String execute() { String result = new Service().service(); System.out.println("Execution result: " + result); return result; } }
1,834
0
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/impl-module/src/main/java
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/impl-module/src/main/java/impl/HelperImpl.java
package impl; /** * @author Aaron Tull * */ public class HelperImpl implements interfaces.Helper { public String doWork() { return "nothing"; } }
1,835
0
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/impl-module/src/main/java
Create_ds/Nicobar/nicobar-core/nicobar-test-classes/impl-module/src/main/java/impl/ManagerImpl.java
package impl; /** * @author Aaron Tull * */ public class ManagerImpl implements interfaces.Manager { public String supervise(interfaces.Helper worker) { return getClass().getName() + " supervising " + worker.getClass().getName() + " doing " + worker.doWork(); } }
1,836
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/archive/SingleFileScriptArchiveTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_SCRIPTS_PATH; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.io.InputStream; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Set; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.testng.annotations.Test; /** * Unit tests for {@link SingleFileScriptArchive} * */ public class SingleFileScriptArchiveTest { @Test public void testDefaultModuleSpec() throws Exception { URL rootPathUrl = getClass().getClassLoader().getResource(TEST_SCRIPTS_PATH.getResourcePath()); Path rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); Set<String> singleFileScripts = TEST_SCRIPTS_PATH.getContentPaths(); for (String script: singleFileScripts) { Path scriptPath = rootPath.resolve(script); SingleFileScriptArchive scriptArchive = new SingleFileScriptArchive.Builder(scriptPath) .build(); String moduleId = script.replaceAll("\\.", "_"); assertEquals(scriptArchive.getModuleSpec().getModuleId().toString(), moduleId); Set<String> archiveEntryNames = scriptArchive.getArchiveEntryNames(); assertEquals(archiveEntryNames.size(), 1); for (String entryName : archiveEntryNames) { URL entryUrl = scriptArchive.getEntry(entryName); assertNotNull(entryUrl); InputStream inputStream = entryUrl.openStream(); String content = IOUtils.toString(inputStream, Charsets.UTF_8); // We have stored the file name as the content of the file assertEquals(content, script + "\n"); } } } @Test public void testWithModuleSpec() throws Exception { URL rootPathUrl = getClass().getClassLoader().getResource(TEST_SCRIPTS_PATH.getResourcePath()); Path rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); Set<String> singleFileScripts = TEST_SCRIPTS_PATH.getContentPaths(); ModuleId moduleId = ModuleId.create("testModuleId"); for (String script: singleFileScripts) { Path scriptPath = rootPath.resolve(script); SingleFileScriptArchive scriptArchive = new SingleFileScriptArchive.Builder(scriptPath) .setModuleSpec(new ScriptModuleSpec.Builder(moduleId).build()) .build(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), moduleId); // We just need to test one script in the set break; } } }
1,837
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/archive/JarScriptArchiveTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_DEFAULT_MODULE_SPEC_JAR2; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_DEFAULT_MODULE_SPEC_JAR; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_MODULE_SPEC_JAR; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_TEXT_JAR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.io.InputStream; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; /** * Unit Tests for {@link JarScriptArchive} * * @author James Kojo * @author Vasanth Asokan */ public class JarScriptArchiveTest { @Test public void testLoadTextJar() throws Exception { URL testJarUrl = getClass().getClassLoader().getResource(TEST_TEXT_JAR.getResourcePath()); Path jarPath = Paths.get(testJarUrl.toURI()).toAbsolutePath(); JarScriptArchive scriptArchive = new JarScriptArchive.Builder(jarPath) .setModuleSpec(new ScriptModuleSpec.Builder(ModuleId.create("testModuleId")).build()) .build(); assertEquals(scriptArchive.getModuleSpec().getModuleId().toString(), "testModuleId"); Set<String> archiveEntryNames = scriptArchive.getArchiveEntryNames(); assertEquals(archiveEntryNames, TEST_TEXT_JAR.getContentPaths()); for (String entryName : archiveEntryNames) { URL entryUrl = scriptArchive.getEntry(entryName); assertNotNull(entryUrl); InputStream inputStream = entryUrl.openStream(); String content = IOUtils.toString(inputStream, Charsets.UTF_8); assertNotNull(content); } } @Test public void testDefaultModuleId() throws Exception { URL rootPathUrl = getClass().getClassLoader().getResource(TEST_DEFAULT_MODULE_SPEC_JAR.getResourcePath()); Path rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); JarScriptArchive scriptArchive = new JarScriptArchive.Builder(rootPath).build(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), TEST_DEFAULT_MODULE_SPEC_JAR.getModuleId()); rootPathUrl = getClass().getClassLoader().getResource(TEST_DEFAULT_MODULE_SPEC_JAR2.getResourcePath()); rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); scriptArchive = new JarScriptArchive.Builder(rootPath).build(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), TEST_DEFAULT_MODULE_SPEC_JAR2.getModuleId()); } @Test public void testLoadWithModuleSpec() throws Exception { URL rootPathUrl = getClass().getClassLoader().getResource(TEST_MODULE_SPEC_JAR.getResourcePath()); Path rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); // if the module spec isn't provided, it should be discovered in the jar JarScriptArchive scriptArchive = new JarScriptArchive.Builder(rootPath).build(); ScriptModuleSpec moduleSpec = scriptArchive.getModuleSpec(); assertEquals(moduleSpec.getModuleId(), TEST_MODULE_SPEC_JAR.getModuleId()); assertEquals(moduleSpec.getModuleDependencies(), Collections.emptySet()); Map<String, String> expectedMetadata = new HashMap<String, String>(); expectedMetadata.put("metadataName1", "metadataValue1"); expectedMetadata.put("metadataName2", "metadataValue2"); } }
1,838
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/archive/ModuleIdTest.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.archive; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import org.testng.annotations.Test; /** * Unit tests for {@link ModuleId} * * @author Vasanth Asokan * @author Aaron Tull */ public class ModuleIdTest { @Test public void testDefaultVersion() { ModuleId moduleId = ModuleId.create("/test/module"); assertEquals(moduleId.toString(), "/test/module"); } @Test public void testWithVersion() { ModuleId moduleId = ModuleId.create("test-Module", "v1"); assertEquals(moduleId.toString(), "test-Module" + ModuleId.MODULE_VERSION_SEPARATOR + "v1"); } @Test public void testFromStringDefaultVersion() { ModuleId moduleId = ModuleId.fromString("test-Module"); assertEquals(moduleId.toString(), "test-Module"); } @Test public void testFromStringWithVersion() { ModuleId moduleId = ModuleId.fromString("test-Module.v2"); assertEquals(moduleId.toString(), "test-Module.v2"); } @Test public void testBadModuleName() { // Just to make PMD happy about empty catch blocks, // We set a dummy operation. @SuppressWarnings("unused") boolean passed = false; try { ModuleId.fromString("test.Module.v2"); fail("Should disallow dots in module name"); } catch (IllegalArgumentException e) { passed = true; } try { ModuleId.create("test.Module", "v2"); fail("Should disallow dots in module name"); } catch (IllegalArgumentException e) { passed = true; } try { ModuleId.create("test.Module"); fail("Should disallow dots in module name"); } catch (IllegalArgumentException e) { passed = true; } try { ModuleId.create("", "v2"); fail("Should disallow empty module name"); } catch (IllegalArgumentException e) { passed = true; } char [] disallowedChars = { '#', '!', '(', ')', '.'}; for (char c: disallowedChars) { try { ModuleId.create("testModule" + Character.toString(c) + "suffix", "v1"); fail("Should disallow " + Character.toString(c) + " in module name"); } catch (IllegalArgumentException e) { passed = true; } } } @Test public void testModuleVersion() { ModuleId moduleId = ModuleId.create("test-Module", ""); assertEquals(moduleId.toString(), "test-Module"); } @Test public void testBadModuleVersion() { // Just to make PMD happy about empty catch blocks, // We set a dummy operation. @SuppressWarnings("unused") boolean passed = false; try { ModuleId.create("test-Module", ".v2"); fail("Should disallow dots in module version"); } catch (IllegalArgumentException e) { passed = true; } char [] disallowedChars = { '/', '\\', '#', '!', '(', ')', '.'}; for (char c: disallowedChars) { try { ModuleId.create("testModule", "v" + Character.toString(c) + "1"); fail("Should disallow " + Character.toString(c) + " in module version"); } catch (IllegalArgumentException e) { passed = true; } } } @Test public void testNegativeIntegerStringifiedName() { String name = String.valueOf(Integer.toHexString(Integer.MIN_VALUE)); ModuleId moduleId = ModuleId.create(name); assertEquals(moduleId.toString(), name); } }
1,839
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/archive/PathScriptArchiveTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_MODULE_SPEC_PATH; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_TEXT_PATH; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.io.InputStream; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.PathScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; /** * Unit tests for {@link PathScriptArchive} * * @author James Kojo */ public class PathScriptArchiveTest { @Test public void testLoadTextPath() throws Exception { URL rootPathUrl = getClass().getClassLoader().getResource(TEST_TEXT_PATH.getResourcePath()); Path rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); ModuleId moduleId = ModuleId.create("testModuleId"); PathScriptArchive scriptArchive = new PathScriptArchive.Builder(rootPath) .setModuleSpec(new ScriptModuleSpec.Builder(moduleId).build()) .build(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), moduleId); Set<String> archiveEntryNames = scriptArchive.getArchiveEntryNames(); assertEquals(archiveEntryNames, TEST_TEXT_PATH.getContentPaths()); for (String entryName : archiveEntryNames) { URL entryUrl = scriptArchive.getEntry(entryName); assertNotNull(entryUrl); InputStream inputStream = entryUrl.openStream(); String content = IOUtils.toString(inputStream, Charsets.UTF_8); assertNotNull(content); } } @Test public void testDefaultModuleId() throws Exception { URL rootPathUrl = getClass().getClassLoader().getResource(TEST_TEXT_PATH.getResourcePath()); Path rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); PathScriptArchive scriptArchive = new PathScriptArchive.Builder(rootPath).build(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), TEST_TEXT_PATH.getModuleId()); } @Test public void testLoadWithModuleSpec() throws Exception { URL rootPathUrl = getClass().getClassLoader().getResource(TEST_MODULE_SPEC_PATH.getResourcePath()); Path rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); // if the module spec isn't provided, it should be discovered in the path PathScriptArchive scriptArchive = new PathScriptArchive.Builder(rootPath).build(); ScriptModuleSpec moduleSpec = scriptArchive.getModuleSpec(); assertEquals(moduleSpec.getModuleId(), TEST_MODULE_SPEC_PATH.getModuleId()); assertEquals(moduleSpec.getModuleDependencies(), Collections.emptySet()); Map<String, Object> expectedMetadata = new HashMap<String, Object>(); Map<String, String> expectedMetadata1 = new HashMap<String, String>(); expectedMetadata1.put("nestedKey1", "metadataValue1"); expectedMetadata1.put("nestedKey2", "metadataValue2"); expectedMetadata.put("metadataName1", expectedMetadata1); expectedMetadata.put("metadataName2", 2.0); expectedMetadata.put("metadataName3", Arrays.asList(1.0, 2.0, 3.0)); Map<String, Object> somedata = moduleSpec.getMetadata(); assertEquals(somedata, expectedMetadata); } }
1,840
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/archive/ScriptModuleSpecSerializerTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.GsonScriptModuleSpecSerializer; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.archive.ScriptModuleSpecSerializer; /** * * @author James Kojo * @author Vasanth Asokan */ public class ScriptModuleSpecSerializerTest { @Test public void testRoundTrip() { ScriptModuleSpec expected = new ScriptModuleSpec.Builder(ModuleId.create("myModuleId")) .addModuleDependency("dependencyModuleId1") .addModuleDependency("dependencyModuleId2") .addMetadata("metadataName1", "metadataValue1") .addMetadata("metadataName2", "metadataValue2") .addMetadata("metadataName3", 4.0) .build(); ScriptModuleSpecSerializer serializer = new GsonScriptModuleSpecSerializer(); String json = serializer.serialize(expected); ScriptModuleSpec deserialized = serializer.deserialize(json); assertEquals(deserialized, expected); } }
1,841
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/module/ScriptModuleLoaderTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_MODULE_SPEC_JAR; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.hamcrest.Description; import org.jboss.modules.ModuleLoadException; import org.mockito.ArgumentMatcher; import org.mockito.InOrder; import org.mockito.Mockito; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.compile.ScriptCompilationException; import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; import com.netflix.nicobar.core.plugin.TestCompilerPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import com.netflix.nicobar.core.testutil.CoreTestResourceUtil; /** * Unit tests for {@link ScriptModuleLoader} * * @author James Kojo * @author Vasanth Asokan */ public class ScriptModuleLoaderTest { // shared mock compiler. THis is needed because of the indirect construction style of the compiler plugin. private final static ScriptArchiveCompiler MOCK_COMPILER = mock(ScriptArchiveCompiler.class); @BeforeMethod public void resetMocks() { reset(MOCK_COMPILER); } @Test public void testLoadArchive() throws Exception { Path jarPath = CoreTestResourceUtil.getResourceAsPath(TEST_MODULE_SPEC_JAR); ScriptArchive scriptArchive = new JarScriptArchive.Builder(jarPath).build(); when(MOCK_COMPILER.shouldCompile(Mockito.eq(scriptArchive))).thenReturn(true); when(MOCK_COMPILER.compile(Mockito.eq(scriptArchive), Mockito.any(JBossModuleClassLoader.class), Mockito.any(Path.class))).thenReturn(Collections.<Class<?>>emptySet()); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addPluginSpec(new ScriptCompilerPluginSpec.Builder(TestCompilerPlugin.PLUGIN_ID) .withPluginClassName(MockScriptCompilerPlugin.class.getName()).build()) .build(); moduleLoader.updateScriptArchives(Collections.singleton(scriptArchive)); ModuleId moduleId = scriptArchive.getModuleSpec().getModuleId(); ScriptModule scriptModule = moduleLoader.getScriptModule(moduleId); assertNotNull(scriptModule); assertEquals(scriptModule.getModuleId(), moduleId); JBossModuleClassLoader moduleClassLoader = scriptModule.getModuleClassLoader(); for (String entryName : scriptArchive.getArchiveEntryNames()) { URL resourceUrl = moduleClassLoader.findResource(entryName, true); assertNotNull(resourceUrl, "couldn't find entry in the classloader: " + entryName); } verify(MOCK_COMPILER).shouldCompile(Mockito.eq(scriptArchive)); verify(MOCK_COMPILER).compile(Mockito.eq(scriptArchive), Mockito.any(JBossModuleClassLoader.class), Mockito.any(Path.class)); verifyNoMoreInteractions(MOCK_COMPILER); } @Test public void testBadModuleSpec() throws Exception { final URL badJarUrl = new URL("file:///somepath/myMadJarName.jar"); ScriptArchive badScriptArchive = new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A").build(), 1) { @Override public URL getRootUrl() { return badJarUrl; } }; ScriptModuleListener mockListener = createMockListener(); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder().addListener(mockListener).build(); moduleLoader.updateScriptArchives(Collections.singleton(badScriptArchive)); verify(mockListener).archiveRejected(Mockito.same(badScriptArchive), Mockito.same(ArchiveRejectedReason.ARCHIVE_IO_EXCEPTION), Mockito.any(Exception.class)); verifyNoMoreInteractions(mockListener); } @Test public void testReloadWithUpdatedDepdencies() throws Exception { // original graph: A->B->C->D long originalCreateTime = 1000; Set<ScriptArchive> updateArchives = new HashSet<ScriptArchive>(); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A").addCompilerPluginId("mockPlugin").addModuleDependency("B").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("B").addCompilerPluginId("mockPlugin").addModuleDependency("C").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C").addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("D").addCompilerPluginId("mockPlugin").build(), originalCreateTime)); ScriptModuleListener mockListener = createMockListener(); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addListener(mockListener) .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin") .withPluginClassName(MockScriptCompilerPlugin.class.getName()).build()) .build(); when(MOCK_COMPILER.shouldCompile(Mockito.any(ScriptArchive.class))).thenReturn(true); when(MOCK_COMPILER.compile(Mockito.any(ScriptArchive.class), Mockito.any(JBossModuleClassLoader.class), Mockito.any(Path.class))).thenReturn(Collections.<Class<?>>emptySet()); moduleLoader.updateScriptArchives(updateArchives); // validate that they were compiled in reverse dependency order InOrder orderVerifier = inOrder(mockListener); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("D", originalCreateTime), (ScriptModule)Mockito.isNull()); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("C", originalCreateTime), (ScriptModule)Mockito.isNull()); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("B", originalCreateTime), (ScriptModule)Mockito.isNull()); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("A", originalCreateTime), (ScriptModule)Mockito.isNull()); orderVerifier.verifyNoMoreInteractions(); // updated graph: D->C->B->A updateArchives.clear(); long updatedCreateTime = 2000; updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("D").addCompilerPluginId("mockPlugin").addModuleDependency("C").build(), updatedCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C").addCompilerPluginId("mockPlugin").addModuleDependency("B").build(), updatedCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("B").addCompilerPluginId("mockPlugin").addModuleDependency("A").build(), updatedCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A").addCompilerPluginId("mockPlugin").build(), updatedCreateTime)); moduleLoader.updateScriptArchives(updateArchives); // validate that they were compiled in the updated reverse dependency order orderVerifier = inOrder(mockListener); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("A", updatedCreateTime), moduleEquals("A", originalCreateTime)); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("B", updatedCreateTime), moduleEquals("B", originalCreateTime)); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("C", updatedCreateTime), moduleEquals("C", originalCreateTime)); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("D", updatedCreateTime), moduleEquals("D", originalCreateTime)); orderVerifier.verifyNoMoreInteractions(); // validate the post-condition of the module database assertEquals(moduleLoader.getScriptModule("A").getCreateTime(), updatedCreateTime); assertEquals(moduleLoader.getScriptModule("B").getCreateTime(), updatedCreateTime); assertEquals(moduleLoader.getScriptModule("C").getCreateTime(), updatedCreateTime); assertEquals(moduleLoader.getScriptModule("D").getCreateTime(), updatedCreateTime); assertEquals(moduleLoader.getAllScriptModules().size(),4); } @Test public void testRelinkDependents() throws Exception { // original graph: A->B->C->D long originalCreateTime = 1000; Set<ScriptArchive> updateArchives = new HashSet<ScriptArchive>(); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A").addCompilerPluginId("mockPlugin").addModuleDependency("B").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("B").addCompilerPluginId("mockPlugin").addModuleDependency("C").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C").addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("D").addCompilerPluginId("mockPlugin").build(), originalCreateTime)); ScriptModuleListener mockListener = createMockListener(); when(MOCK_COMPILER.shouldCompile(Mockito.any(ScriptArchive.class))).thenReturn(true); when(MOCK_COMPILER.compile(Mockito.any(ScriptArchive.class), Mockito.any(JBossModuleClassLoader.class), Mockito.any(Path.class))).thenReturn(Collections.<Class<?>>emptySet()); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addListener(mockListener) .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin") .withPluginClassName(MockScriptCompilerPlugin.class.getName()).build()) .build(); moduleLoader.updateScriptArchives(updateArchives); // don't need to re-validate since already validated in testReloadWithUpdatedDepdencies reset(mockListener); // update C. should cause C,B,A to be compiled in order updateArchives.clear(); long updatedCreateTime = 2000; updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C").addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), updatedCreateTime)); moduleLoader.updateScriptArchives(updateArchives); // validate that they were compiled in the updated reverse dependency order InOrder orderVerifier = inOrder(mockListener); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("C", updatedCreateTime), moduleEquals("C", originalCreateTime)); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("B", originalCreateTime), moduleEquals("B", originalCreateTime)); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("A", originalCreateTime), moduleEquals("A", originalCreateTime)); orderVerifier.verifyNoMoreInteractions(); // validate the post-condition of the module database assertEquals(moduleLoader.getScriptModule("A").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getScriptModule("B").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getScriptModule("C").getCreateTime(), updatedCreateTime); assertEquals(moduleLoader.getScriptModule("D").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getAllScriptModules().size(),4); } @Test public void testCompileErrorAbortsRelink() throws Exception { // original graph: A->B->C->D long originalCreateTime = 1000; Set<ScriptArchive> updateArchives = new HashSet<ScriptArchive>(); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A").addCompilerPluginId("mockPlugin").addModuleDependency("B").build(), originalCreateTime)); ScriptArchive archiveB = new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("B").addCompilerPluginId("mockPlugin").addModuleDependency("C").build(), originalCreateTime); updateArchives.add(archiveB); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C").addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("D").addCompilerPluginId("mockPlugin").build(), originalCreateTime)); when(MOCK_COMPILER.shouldCompile(Mockito.any(ScriptArchive.class))).thenReturn(true); when(MOCK_COMPILER.compile(Mockito.any(ScriptArchive.class), Mockito.any(JBossModuleClassLoader.class), Mockito.any(Path.class))).thenReturn(Collections.<Class<?>>emptySet()); ScriptModuleListener mockListener = createMockListener(); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addListener(mockListener) .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin") .withPluginClassName(MockScriptCompilerPlugin.class.getName()) .build()) .build(); moduleLoader.updateScriptArchives(updateArchives); reset(mockListener); reset(MOCK_COMPILER); when(MOCK_COMPILER.shouldCompile(Mockito.any(ScriptArchive.class))).thenReturn(true); when(MOCK_COMPILER.compile(Mockito.eq(archiveB), Mockito.any(JBossModuleClassLoader.class), Mockito.any(Path.class))).thenThrow(new ScriptCompilationException("TestCompileException", null)); // update C. would normally cause C,B,A to be compiled in order, but B will fail, so A will be skipped updateArchives.clear(); long updatedCreateTime = 2000; updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C").addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), updatedCreateTime)); moduleLoader.updateScriptArchives(updateArchives); // validate that only C was compiled. InOrder orderVerifier = inOrder(mockListener); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("C", updatedCreateTime), moduleEquals("C", originalCreateTime)); orderVerifier.verifyNoMoreInteractions(); // validate the post-condition of the module database assertEquals(moduleLoader.getScriptModule("A").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getScriptModule("B").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getScriptModule("C").getCreateTime(), updatedCreateTime); assertEquals(moduleLoader.getScriptModule("D").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getAllScriptModules().size(),4); } @Test public void testCompileErrorSendsNotification() throws Exception { // original graph: A->B->C->D long originalCreateTime = 1000; Set<ScriptArchive> updateArchives = new HashSet<ScriptArchive>(); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A").addCompilerPluginId("mockPlugin").addModuleDependency("B").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("B").addCompilerPluginId("mockPlugin").addModuleDependency("C").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C").addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("D").addCompilerPluginId("mockPlugin").build(), originalCreateTime)); ScriptModuleListener mockListener = createMockListener(); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addListener(mockListener) .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin") .withPluginClassName(MockScriptCompilerPlugin.class.getName()) .build()) .build(); when(MOCK_COMPILER.shouldCompile(Mockito.any(ScriptArchive.class))).thenReturn(true); moduleLoader.updateScriptArchives(updateArchives); reset(mockListener); // update C, but set compilation to fail. updateArchives.clear(); long updatedCreateTime = 2000; TestDependecyScriptArchive updatedArchiveC = new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C").addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), updatedCreateTime); updateArchives.add(updatedArchiveC); reset(MOCK_COMPILER); when(MOCK_COMPILER.shouldCompile(Mockito.eq(updatedArchiveC))).thenReturn(true); ScriptCompilationException compilationException = new ScriptCompilationException("TestCompileException", null); when(MOCK_COMPILER.compile(Mockito.eq(updatedArchiveC), Mockito.any(JBossModuleClassLoader.class), Mockito.any(Path.class))).thenThrow(compilationException); moduleLoader.updateScriptArchives(updateArchives); // validate that they were compiled in the updated reverse dependency order verify(mockListener).archiveRejected(updatedArchiveC, ArchiveRejectedReason.COMPILE_FAILURE, compilationException); verifyNoMoreInteractions(mockListener); // validate the post-condition of the module database assertEquals(moduleLoader.getScriptModule("A").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getScriptModule("B").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getScriptModule("C").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getScriptModule("D").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getAllScriptModules().size(), 4); } @Test public void testOldArchiveRejected() throws Exception { long originalCreateTime = 2000; Set<ScriptArchive> updateArchives = new HashSet<ScriptArchive>(); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A").addCompilerPluginId("mockPlugin").build(), originalCreateTime)); when(MOCK_COMPILER.shouldCompile(Mockito.any(ScriptArchive.class))).thenReturn(true); when(MOCK_COMPILER.compile(Mockito.any(ScriptArchive.class), Mockito.any(JBossModuleClassLoader.class), Mockito.any(Path.class))).thenReturn(Collections.<Class<?>>emptySet()); ScriptModuleListener mockListener = createMockListener(); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin") .withPluginClassName(MockScriptCompilerPlugin.class.getName()).build()) .addListener(mockListener).build(); moduleLoader.updateScriptArchives(updateArchives); reset(mockListener); // updated graph: D->C->B->A updateArchives.clear(); long updatedCreateTime = 1000; TestDependecyScriptArchive updatedArchive = new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A").addCompilerPluginId("mockPlugin").build(), updatedCreateTime); updateArchives.add(updatedArchive); moduleLoader.updateScriptArchives(updateArchives); // validate that the update was rejected due to a old timestamp verify(mockListener).archiveRejected(updatedArchive, ArchiveRejectedReason.HIGHER_REVISION_AVAILABLE, null); verifyNoMoreInteractions(mockListener); // validate the post-condition of the module database assertEquals(moduleLoader.getScriptModule("A").getCreateTime(), originalCreateTime); } /** * Test that the compiler plugin classloader is available through the ScriptModuleLoader. * @throws IOException * @throws ModuleLoadException * @throws ClassNotFoundException */ @Test public void testCompilerPluginClassloader() throws ModuleLoadException, IOException, ClassNotFoundException { ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin") .withPluginClassName(MockScriptCompilerPlugin.class.getName()).build()) .build(); ClassLoader classLoader = moduleLoader.getCompilerPluginClassLoader("mockPlugin"); assertNotNull(classLoader); Class<?> pluginClass = classLoader.loadClass(MockScriptCompilerPlugin.class.getName()); assertNotNull(pluginClass); } /** * Custom mockito/hamcrest matcher which will inspect a ScriptModule and see if its moduleId * equals the input moduleId and likewise for the creation time */ private ScriptModule moduleEquals(final String scriptModuleId, final long createTime) { return Mockito.argThat(new ArgumentMatcher<ScriptModule>() { @Override public boolean matches(Object argument) { ScriptModule scriptModule = (ScriptModule)argument; return scriptModule != null && scriptModule.getModuleId().toString().equals(scriptModuleId) && scriptModule.getCreateTime() == createTime; } @Override public void describeTo(Description description) { description.appendText("ScriptModule.getModuleId().equals(\"" + scriptModuleId + "\")"); } }); } private ScriptModuleListener createMockListener() { ScriptModuleListener mockListener = mock(ScriptModuleListener.class); return mockListener; } private static class TestDependecyScriptArchive implements ScriptArchive { private final long createTime; private ScriptModuleSpec scriptModuleSpec; private TestDependecyScriptArchive(ScriptModuleSpec scriptModuleSpec, long createTime) { this.createTime = createTime; this.scriptModuleSpec = scriptModuleSpec; } @Override public ScriptModuleSpec getModuleSpec() { return scriptModuleSpec; } @Override public void setModuleSpec(ScriptModuleSpec spec) { this.scriptModuleSpec = spec; } @Override public URL getRootUrl() { return null; } @Override public Set<String> getArchiveEntryNames() { return Collections.emptySet(); } @Override public URL getEntry(String entryName) throws IOException { return null; } @Override public long getCreateTime() { return createTime; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("scriptModuleSpec", scriptModuleSpec) .append("createTime", createTime) .toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ScriptModuleLoaderTest.TestDependecyScriptArchive other = (ScriptModuleLoaderTest.TestDependecyScriptArchive) o; return Objects.equals(this.createTime, other.createTime) && Objects.equals(this.scriptModuleSpec, other.scriptModuleSpec); } @Override public int hashCode() { return Objects.hash(createTime, createTime); } } /** trivial compiler plugin implementation which returns the static mock */ public static class MockScriptCompilerPlugin implements ScriptCompilerPlugin { @Override public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) { return Collections.singleton(MOCK_COMPILER); } } }
1,842
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/module/ScriptModuleLoaderDependenciesTest.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.module; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_CLASSPATH_DEPENDENT; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_DEPENDENCIES_DEPENDENT; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_DEPENDENCIES_PRIMARY; import static org.testng.AssertJUnit.assertNotNull; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoadException; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; import com.netflix.nicobar.core.plugin.BytecodeLoadingPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import com.netflix.nicobar.core.testutil.CoreTestResourceUtil; /** * Tests different conditions of interdependent modules. * @author Aaron Tull * */ public class ScriptModuleLoaderDependenciesTest { @Test(expectedExceptions=java.lang.LinkageError.class) public void testDependenciesExportFilterExcludesNonMatching() throws Exception { ScriptModuleLoader moduleLoader = setupDependentModulesWithFilters("path.to.public.interface", null); exerciseDependentModules(moduleLoader); ScriptModule primaryModule = moduleLoader.getScriptModule(TEST_DEPENDENCIES_DEPENDENT.getModuleId()); JBossModuleClassLoader primaryModuleLoader = primaryModule.getModuleClassLoader(); primaryModuleLoader.loadClass("impl.ManagerImpl"); } @Test(expectedExceptions=java.lang.LinkageError.class) public void testDependenciesImportFilterExcludesNonMatching() throws Exception { ScriptModuleLoader moduleLoader = setupDependentModulesWithFilters(null, "path.to.public.interface"); ScriptModule primaryModule = moduleLoader.getScriptModule(TEST_DEPENDENCIES_DEPENDENT.getModuleId()); JBossModuleClassLoader primaryModuleLoader = primaryModule.getModuleClassLoader(); primaryModuleLoader.loadClass("impl.ManagerImpl"); } @Test public void testDependenciesImportFilterIncludesMatching() throws Exception { ScriptModuleLoader moduleLoader = setupDependentModulesWithFilters(null, "interfaces"); exerciseDependentModules(moduleLoader); } @Test public void testDependenciesExportFilterIncludesMatching() throws Exception { ScriptModuleLoader moduleLoader = setupDependentModulesWithFilters("interfaces", null); exerciseDependentModules(moduleLoader); } @Test public void testDependenciesBothFiltersIncludeMatching() throws Exception { ScriptModuleLoader moduleLoader = setupDependentModulesWithFilters("interfaces", "interfaces"); exerciseDependentModules(moduleLoader); } @Test(expectedExceptions=java.lang.LinkageError.class) public void testDependenciesImportCanOverrideExport() throws Exception { ScriptModuleLoader moduleLoader = setupDependentModulesWithFilters("interfaces", "public.interface"); exerciseDependentModules(moduleLoader); } @Test(expectedExceptions=java.lang.LinkageError.class) public void testDependenciesExportCanOverrideImport() throws Exception { ScriptModuleLoader moduleLoader = setupDependentModulesWithFilters("public.interface", "interfaces"); exerciseDependentModules(moduleLoader); } @Test public void testDependentModules() throws Exception { ScriptModuleLoader moduleLoader = setupDependentModulesWithFilters(null, null); exerciseDependentModules(moduleLoader); } private void exerciseDependentModules(ScriptModuleLoader moduleLoader) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { ScriptModule primaryModule = moduleLoader.getScriptModule(TEST_DEPENDENCIES_DEPENDENT.getModuleId()); JBossModuleClassLoader primaryModuleLoader = primaryModule.getModuleClassLoader(); Class<?> helperClass = primaryModuleLoader.loadClass("impl.HelperImpl"); Class<?> helperInterface = primaryModuleLoader.loadClass("interfaces.Helper"); Object helper = helperClass.newInstance(); Method doWorkmethod = helperClass.getMethod("doWork"); Object doWorkResult = doWorkmethod.invoke(helper); Assert.assertTrue(doWorkResult instanceof String); Assert.assertEquals(doWorkResult, "nothing"); Class<?> managerClass = primaryModuleLoader.loadClass("impl.ManagerImpl"); Object manager = managerClass.newInstance(); Method superviseMethod = managerClass.getMethod("supervise", helperInterface); Object superviseResult = superviseMethod.invoke(manager, helper); Assert.assertTrue(superviseResult instanceof String); Assert.assertEquals(superviseResult, "impl.ManagerImpl supervising impl.HelperImpl doing nothing"); } private ScriptModuleLoader setupDependentModulesWithFilters(String exportFilter, String importFilter) throws ModuleLoadException, IOException, Exception { ScriptCompilerPluginSpec pluginSpec = new ScriptCompilerPluginSpec.Builder(BytecodeLoadingPlugin.PLUGIN_ID) .withPluginClassName(BytecodeLoadingPlugin.class.getName()) .build(); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addPluginSpec(pluginSpec) .build(); Path primaryJarPath = CoreTestResourceUtil.getResourceAsPath(TEST_DEPENDENCIES_PRIMARY); ScriptModuleSpec.Builder primarySpecBuilder = new ScriptModuleSpec.Builder(TEST_DEPENDENCIES_PRIMARY.getModuleId()) .addModuleExportFilter(exportFilter) .addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID); final ScriptArchive primaryJarArchive = new JarScriptArchive.Builder(primaryJarPath) .setModuleSpec(primarySpecBuilder.build()) .build(); Path dependentJarPath = CoreTestResourceUtil.getResourceAsPath(TEST_DEPENDENCIES_DEPENDENT); ScriptModuleSpec.Builder dependentSpecBuilder = new ScriptModuleSpec.Builder(TEST_DEPENDENCIES_DEPENDENT.getModuleId()) .addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID) .addModuleImportFilter(importFilter) .addModuleDependency(TEST_DEPENDENCIES_PRIMARY.getModuleId()); final ScriptArchive dependentJarArchive = new JarScriptArchive.Builder(dependentJarPath) .setModuleSpec(dependentSpecBuilder.build()) .build(); moduleLoader.updateScriptArchives(Collections.unmodifiableSet(new HashSet<ScriptArchive>() { private static final long serialVersionUID = -5461608508917035441L; { add(primaryJarArchive); add(dependentJarArchive); } })); return moduleLoader; } private ScriptModuleLoader setupClassPathDependentWithFilter(String importFilter) throws ModuleLoadException, IOException, Exception { ScriptCompilerPluginSpec pluginSpec = new ScriptCompilerPluginSpec.Builder(BytecodeLoadingPlugin.PLUGIN_ID) .withPluginClassName(BytecodeLoadingPlugin.class.getName()) .build(); Set<String> packages = new HashSet<String>(); packages.add("org/jboss/modules"); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder() .addPluginSpec(pluginSpec) .addAppPackages(packages ) .build(); Path primaryJarPath = CoreTestResourceUtil.getResourceAsPath(TEST_CLASSPATH_DEPENDENT); ScriptModuleSpec.Builder primarySpecBuilder = new ScriptModuleSpec.Builder(TEST_CLASSPATH_DEPENDENT.getModuleId()) .addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID) .addAppImportFilter(importFilter); final ScriptArchive primaryJarArchive = new JarScriptArchive.Builder(primaryJarPath) .setModuleSpec(primarySpecBuilder.build()) .build(); moduleLoader.updateScriptArchives(Collections.unmodifiableSet(new HashSet<ScriptArchive>() { private static final long serialVersionUID = -5461608508917035441L; { add(primaryJarArchive); } })); return moduleLoader; } private void exerciseClasspathDependentModule(ScriptModuleLoader moduleLoader) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { ScriptModule module = moduleLoader.getScriptModule(TEST_CLASSPATH_DEPENDENT.getModuleId()); JBossModuleClassLoader primaryModuleLoader = module.getModuleClassLoader(); Class<?> dependentClass = primaryModuleLoader.loadClass("DependentClass"); Object helper = dependentClass.newInstance(); assertNotNull(helper); } @Test public void failsIfImportFilterExcludesNecessaryPathFromAppPackage() throws ModuleLoadException, IOException, Exception { ScriptModuleLoader moduleLoader = setupClassPathDependentWithFilter("java"); boolean didFail = false; Module.forClass(Object.class); try { exerciseClasspathDependentModule(moduleLoader); } catch (java.lang.NoClassDefFoundError e) { Assert.assertTrue(e.getMessage().contains("org/jboss/modules/Module")); didFail = true; } Assert.assertTrue(didFail); } @Test public void passesIfImportFilterIncludesAllNecessaryPathsFromAppPackage() throws ModuleLoadException, IOException, Exception { ScriptModuleLoader moduleLoader = setupClassPathDependentWithFilter("org/jboss/modules"); exerciseClasspathDependentModule(moduleLoader); } }
1,843
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/module/ResolutionOrderTests.java
package com.netflix.nicobar.core.module; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_DEPENDENT; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_SERVICE; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import java.lang.reflect.Method; import java.nio.file.Path; import java.util.Collections; import java.util.Set; import org.jboss.modules.ModuleLoadException; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.plugin.BytecodeLoadingPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import com.netflix.nicobar.core.testutil.CoreTestResourceUtil; /** * Unit tests to test classloader resolution order * * @author Vasanth Asokan */ public class ResolutionOrderTests { private ScriptModuleLoader moduleLoader; /** * This test will test that a class found in the application classpath, * will override a class defined in a downstream module. * * In other words, if the module dependency is like this * * A -> B -> [App Classpath] * * and if both B, and [App Classpath] contain a class Foo, * a reference to Foo in module A, will be resolved from the [App Classpath] * and not from its immediate parent module. * * This is standard java classloader resolution. A class is resolved as far up * as possible, in the classloader hierarchy. * * @throws Exception */ @Test public void testAppClasspathPrecedence() throws Exception { setupModuleLoader(Collections.singleton("com/netflix/nicobar/test")); setupDependentModules(); ScriptModule dependentModule = moduleLoader.getScriptModule("dependent"); Class<?> dependentClass = ScriptModuleUtils.findClass(dependentModule, "com.netflix.nicobar.test.Dependent"); Method m = dependentClass.getMethod("execute"); String result = (String)m.invoke(null); assertEquals("From App Classpath", result); } /** * This test shows, that the only way to resolve a class from a module * instead of the application classpath is to black list it from * the script module loader's application package list. * * @throws Exception */ @Test public void testAppClasspathBlacklist() throws Exception { // Blacklist all packages from application classpath setupModuleLoader(Collections.<String>emptySet()); setupDependentModules(); ScriptModule dependentModule = moduleLoader.getScriptModule("dependent"); Class<?> dependentClass = ScriptModuleUtils.findClass(dependentModule, "com.netflix.nicobar.test.Dependent"); Method m = dependentClass.getMethod("execute"); String result = (String)m.invoke(null); assertEquals("From Module", result); } private void setupDependentModules() throws Exception { Path dependentPath = CoreTestResourceUtil.getResourceAsPath(TEST_DEPENDENT); Path servicePath = CoreTestResourceUtil.getResourceAsPath(TEST_SERVICE); ScriptArchive serviceArchive = new JarScriptArchive.Builder(servicePath) .setModuleSpec(new ScriptModuleSpec.Builder("service") .addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID) .build()) .build(); ScriptArchive dependentArchive = new JarScriptArchive.Builder(dependentPath) .setModuleSpec(new ScriptModuleSpec.Builder("dependent") .addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID) .addModuleDependency("service") .build()) .build(); moduleLoader.updateScriptArchives(Collections.singleton(serviceArchive)); moduleLoader.updateScriptArchives(Collections.singleton(dependentArchive)); } private void setupModuleLoader(Set<String> appPackages) throws ModuleLoadException, IOException { moduleLoader = new ScriptModuleLoader.Builder() .addPluginSpec(new ScriptCompilerPluginSpec.Builder(BytecodeLoadingPlugin.PLUGIN_ID) .withPluginClassName(BytecodeLoadingPlugin.class.getName()).build()) .addAppPackages(appPackages) .build(); } }
1,844
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/module
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/module/jboss/JBossModuleUtilsTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module.jboss; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_TEXT_JAR; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_TEXT_PATH; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.jboss.modules.Module; import org.jboss.modules.ModuleClassLoader; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleSpec; import org.jboss.modules.Resource; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.PathScriptArchive; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.plugin.ScriptCompilerPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import com.netflix.nicobar.core.testutil.CoreTestResourceUtil; /** * Unit tests for {@link JBossModuleUtils} * * @author James Kojo */ public class JBossModuleUtilsTest { private static final String METADATA_NAME = "TestMetadataName"; private static final String METADATA_VALUE = "TestMetadataValue"; @BeforeClass public void setup() { //Module.setModuleLogger(new StreamModuleLogger(System.err)); } /** * Verify that the module creates the expected set of dependencies for a {@link ScriptCompilerPlugin} */ @Test public void testExpectedPluginDependencies() throws Exception { ScriptCompilerPluginSpec pluginSpec = new ScriptCompilerPluginSpec.Builder("TestPlugin") .addMetatdata(METADATA_NAME, METADATA_VALUE) .build(); ModuleIdentifier pluginId = JBossModuleUtils.getPluginModuleId(pluginSpec); ModuleSpec.Builder moduleSpecBuilder = ModuleSpec.build(pluginId); JBossModuleUtils.populateCompilerModuleSpec(moduleSpecBuilder, pluginSpec, Collections.<ModuleId, ModuleIdentifier>emptyMap()); JBossModuleLoader moduleLoader = new JBossModuleLoader(); moduleLoader.addModuleSpec(moduleSpecBuilder.create()); Module module = moduleLoader.loadModule(pluginId); assertNotNull(module); ModuleClassLoader moduleClassLoader = module.getClassLoader(); // verify the metadata was transfered assertEquals(module.getProperty(METADATA_NAME), METADATA_VALUE); // verify the module can import the core classes assertNotNull(moduleClassLoader.loadClass(ScriptCompilerPlugin.class.getName())); // verify the module can find the JDK classes assertNotNull(moduleClassLoader.loadClass("org.w3c.dom.Element")); // verify that nothing else from the classpath leaked through assertClassNotFound(TestNG.class.getName(), moduleClassLoader); } /** * Verify that the module creates the expected set of dependencies for a {@link JarScriptArchive} */ @Test public void testJarResources() throws Exception { Path jarPath = CoreTestResourceUtil.getResourceAsPath(TEST_TEXT_JAR); ScriptArchive jarScriptArchive = new JarScriptArchive.Builder(jarPath) .setModuleSpec(new ScriptModuleSpec.Builder(ModuleId.create("testModuleId")) .addMetadata(METADATA_NAME, METADATA_VALUE) .build()) .build(); ModuleIdentifier revisionId = JBossModuleUtils.createRevisionId(TEST_TEXT_JAR.getModuleId(), 1); ModuleSpec.Builder moduleSpecBuilder = ModuleSpec.build(revisionId); JBossModuleLoader moduleLoader = new JBossModuleLoader(); JBossModuleUtils.populateModuleSpecWithCoreDependencies(moduleSpecBuilder, jarScriptArchive); JBossModuleUtils.populateModuleSpecWithResources(moduleSpecBuilder, jarScriptArchive); moduleLoader.addModuleSpec(moduleSpecBuilder.create()); Module module = moduleLoader.loadModule(revisionId); ModuleClassLoader moduleClassLoader = module.getClassLoader(); // verify the metadata was transfered assertEquals(module.getProperty(METADATA_NAME), METADATA_VALUE); // verify that the archive resource match exactly the module resources Set<String> actualPaths = getResourcePaths(moduleClassLoader); assertEquals(actualPaths, TEST_TEXT_JAR.getContentPaths()); } /** * Verify that the module creates the expected set of dependencies for a {@link PathScriptArchive} */ @Test public void testPathResources() throws Exception { Path jarPath = CoreTestResourceUtil.getResourceAsPath(TEST_TEXT_PATH); ScriptArchive jarScriptArchive = new PathScriptArchive.Builder(jarPath) .setModuleSpec(new ScriptModuleSpec.Builder(ModuleId.create("testModuleId")) .addMetadata(METADATA_NAME, METADATA_VALUE) .build()) .build(); ModuleIdentifier revisionId = JBossModuleUtils.createRevisionId(TEST_TEXT_PATH.getModuleId(), 1); ModuleSpec.Builder moduleSpecBuilder = ModuleSpec.build(revisionId); JBossModuleLoader moduleLoader = new JBossModuleLoader(); JBossModuleUtils.populateModuleSpecWithCoreDependencies(moduleSpecBuilder, jarScriptArchive); JBossModuleUtils.populateModuleSpecWithResources(moduleSpecBuilder, jarScriptArchive); moduleLoader.addModuleSpec(moduleSpecBuilder.create()); Module module = moduleLoader.loadModule(revisionId); ModuleClassLoader moduleClassLoader = module.getClassLoader(); // verify the metadata was transfered assertEquals(module.getProperty(METADATA_NAME), METADATA_VALUE); // verify that the archive resource match exactly the module resources Set<String> actualPaths = getResourcePaths(moduleClassLoader); assertEquals(actualPaths, TEST_TEXT_PATH.getContentPaths()); } private void assertClassNotFound(String className, ModuleClassLoader moduleClassLoader) { Class<?> foundClass; try { foundClass = moduleClassLoader.loadClass(className); } catch (ClassNotFoundException e) { foundClass = null; } assertNull(foundClass); } private Set<String> getResourcePaths(ModuleClassLoader moduleClassLoader) { Set<String> result = new HashSet<String>(); Iterator<Resource> resources = moduleClassLoader.iterateResources("", true); while (resources.hasNext()) { Resource resource = resources.next(); result.add(resource.getName()); } return result; } }
1,845
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/plugin/ScriptCompilerPluginSpecTest.java
package com.netflix.nicobar.core.plugin; import com.google.common.collect.ImmutableSet; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * Test for {@link ScriptCompilerPluginSpec} */ public class ScriptCompilerPluginSpecTest { final static String PLUGIN_ID = "ANY_PLUGIN_ID"; Path rootPath; final String directories = "sublevel2/sublevel3/sublevel4"; String[] files = { "rootPackage.jar", "file0.txt", "sublevel2/package2.jar", "sublevel2/file.txt", "sublevel2/sublevel3/package3.jar", "sublevel2/sublevel3/file.json", "sublevel2/sublevel3/sublevel4/package4.jar", "sublevel2/sublevel3/sublevel4/file.txt", }; @BeforeTest public void setup() throws IOException { rootPath = Files.createTempDirectory("rootPath"); Files.createDirectories(Paths.get(rootPath.toString(), directories)); for (String fileName : files) { Files.createFile(Paths.get(rootPath.toString(), fileName)); } } @AfterTest public void cleanup() throws IOException { Files.walkFileTree(rootPath.toAbsolutePath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult postVisitDirectory(Path directory, IOException exc) throws IOException { Files.delete(directory); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } }); } /** * Tests for adding multiple runtime resources * * @throws IOException */ @Test public void testAddRuntimeResources() throws IOException { ScriptCompilerPluginSpec pluginSpec = new ScriptCompilerPluginSpec.Builder(PLUGIN_ID) .addRuntimeResources(ImmutableSet.of( Paths.get(rootPath.toString(), files[0]), Paths.get(rootPath.toString(), files[1]), Paths.get(rootPath.toString(), files[2]) )) .build(); assertEquals(3, pluginSpec.getRuntimeResources().size()); // pure jars + recursively = true pluginSpec = new ScriptCompilerPluginSpec.Builder(PLUGIN_ID) .addRuntimeResources(rootPath, Collections.singleton("jar"), true) .build(); assertEquals(4, pluginSpec.getRuntimeResources().size()); // files "txt" + recursively = false pluginSpec = new ScriptCompilerPluginSpec.Builder(PLUGIN_ID) .addRuntimeResources(rootPath, Collections.singleton("txt"), false) .build(); assertEquals(1, pluginSpec.getRuntimeResources().size()); assertTrue(pluginSpec.getRuntimeResources().iterator().next().endsWith("file0.txt")); // files "txt", "json" + recursively = true pluginSpec = new ScriptCompilerPluginSpec.Builder(PLUGIN_ID) .addRuntimeResources(rootPath, ImmutableSet.of("txt", "json"), true) .build(); assertEquals(4, pluginSpec.getRuntimeResources().size()); } }
1,846
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/plugin/BytecodeLoadingPluginTest.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.plugin; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.lang.reflect.Method; import java.net.URL; import java.nio.file.Paths; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.module.ScriptModule; import com.netflix.nicobar.core.module.ScriptModuleLoader; import com.netflix.nicobar.core.module.ScriptModuleUtils; import com.netflix.nicobar.core.utils.ClassPathUtils; /** * Tests for the Bytecode language plugin. * @author Vasanth Asokan */ public class BytecodeLoadingPluginTest { private ScriptModuleLoader moduleLoader; @BeforeTest public void setup() throws Exception { ScriptCompilerPluginSpec pluginSpec = getCompilerSpec(); // Create a set of app packages to allow access by the compilers, as well as the scripts. // We take a hammer approach and just exclude all com/netflix from the set of app packages exposed. Set<String> excludes = new HashSet<String>(); Collections.addAll(excludes, "com/netflix"); Set<String> pathSet = ClassPathUtils.scanClassPathWithExcludes(System.getProperty("java.class.path"), Collections.<String> emptySet(), excludes); moduleLoader = new ScriptModuleLoader.Builder() .addPluginSpec(pluginSpec) // TODO: The BytecodeLoadingPlugin seems to work without the app package filter // that we add below. This is likely something in our system, allowing packages to leak. // Need to follow up and see how IOUtils resolves correctly in the BytecodeLoadingPlugin // without an app package filter as below. .addAppPackages(pathSet) .build(); } /** * Test a plain archive with no dependencies. * @throws Exception */ @Test public void testHelloHelperJar() throws Exception { URL jarPath = getClass().getClassLoader().getResource("testmodules/hellohelper.jar"); JarScriptArchive jarArchive = new JarScriptArchive.Builder(Paths.get(jarPath.getFile())) .build(); moduleLoader.updateScriptArchives(Collections.singleton((ScriptArchive)jarArchive)); ScriptModule module = moduleLoader.getScriptModule(ModuleId.create("hellohelper")); assertNotNull(module); Class<?> targetClass = ScriptModuleUtils.findClass(module, "com.netflix.nicobar.test.HelloHelper"); assertNotNull(targetClass); Object instance = targetClass.newInstance(); Method method = targetClass.getMethod("execute"); String message = (String)method.invoke(instance); assertEquals(message, "Hello Nicobar World!"); } /** * Test an archive with module dependencies. * @throws Exception */ @Test public void testHelloworldWithDeps() throws Exception { URL jarPath = getClass().getClassLoader().getResource("testmodules/helloworld.jar"); JarScriptArchive jarArchive = new JarScriptArchive.Builder(Paths.get(jarPath.getFile())) .build(); URL depJarPath = getClass().getClassLoader().getResource("testmodules/hellohelper.jar"); JarScriptArchive depArchive = new JarScriptArchive.Builder(Paths.get(depJarPath.getFile())) .build(); Set<ScriptArchive> archives = new HashSet<ScriptArchive>(); Collections.<ScriptArchive>addAll(archives, depArchive, jarArchive); moduleLoader.updateScriptArchives(archives); ScriptModule module = moduleLoader.getScriptModule(ModuleId.create("helloworld")); assertNotNull(module); Class<?> targetClass = ScriptModuleUtils.findClass(module, "com.netflix.nicobar.test.Helloworld"); assertNotNull(targetClass); Object instance = targetClass.newInstance(); Method method = targetClass.getMethod("execute"); String message = (String)method.invoke(instance); assertEquals(message, "Hello Nicobar World!"); } private ScriptCompilerPluginSpec getCompilerSpec() { // Create a compiler spec for the bytecode loading plugin ScriptCompilerPluginSpec compilerSpec = new ScriptCompilerPluginSpec.Builder(BytecodeLoadingPlugin.PLUGIN_ID) .withPluginClassName(BytecodeLoadingPlugin.class.getName()) .build(); return compilerSpec; } }
1,847
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/utils/ClassPathUtilsTest.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.utils; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.netflix.nicobar.core.testutil.CoreTestResourceUtil; import com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource; /** * Unit tests for {@link ClassPathUtils} * * @author Vasanth Asokan */ public class ClassPathUtilsTest { private String classPathStr = ""; @BeforeTest public void testSetup() throws Exception { String rootDir = CoreTestResourceUtil.getResourceAsPath(TestResource.TEST_CLASSPATHDIR_PATH).toString(); String classesDir = rootDir + File.separator + "classes"; String jarPath = rootDir + File.separator + "libs" + File.separator + "nicobar-test-v1.0.jar"; classPathStr = classesDir + File.pathSeparator + jarPath; } @Test public void testScanClassPath() throws Exception { Set<String> pkgPaths = ClassPathUtils.scanClassPath(classPathStr, Collections.<String>emptySet()); Set<String> expected = new HashSet<String>(); Collections.addAll(expected, "com/netflix/nicobar/hello", "com/netflix/nicobar/test/ui", "com/netflix/foo", "com/netflix/foo/bar", "com/netflix/baz/internal", "com/netflix/nicobar/test/ui/internal", "com/netflix/nicobar/test", "com/netflix/nicobar/hello/internal"); assertTrue(pkgPaths.containsAll(expected)); } @Test public void testScanClassPathWithExcludes() throws Exception { Set<String> excludePrefixes = new HashSet<String>(); Collections.addAll(excludePrefixes, "com/netflix/foo/bar"); Set<String> pkgPaths = ClassPathUtils.scanClassPathWithExcludes(classPathStr, Collections.<String>emptySet(), excludePrefixes); Set<String> notExpected = new HashSet<String>(); Collections.addAll(notExpected, "com/netflix/foo/bar"); Set<String> expected = new HashSet<String>(); Collections.addAll(expected, "com/netflix/nicobar/hello", "com/netflix/nicobar/test/ui", "com/netflix/foo", "com/netflix/baz/internal", "com/netflix/nicobar/test/ui/internal", "com/netflix/nicobar/test", "com/netflix/nicobar/hello/internal"); assertTrue(pkgPaths.containsAll(expected)); for (String excluded: notExpected) { assertTrue(!pkgPaths.contains(excluded)); } } @Test public void testScanClassPathWithIncludes() throws Exception { Set<String> includePrefixes = new HashSet<String>(); Collections.addAll(includePrefixes, "com/netflix/foo"); Set<String> pkgPaths = ClassPathUtils.scanClassPathWithIncludes(classPathStr, Collections.<String>emptySet(), includePrefixes); Set<String> expected = new HashSet<String>(); Collections.addAll(expected, "com/netflix/foo", "com/netflix/foo/bar"); assertTrue(pkgPaths.equals(expected)); } @Test public void testScanClassPathWithIncludesAndExcludes() throws Exception { Set<String> includePrefixes = new HashSet<String>(); Collections.addAll(includePrefixes, "com/netflix/nicobar"); Set<String> excludePrefixes = new HashSet<String>(); Collections.addAll(excludePrefixes, "com/netflix/foo/bar"); Set<String> pkgPaths = ClassPathUtils.scanClassPath(classPathStr, Collections.<String>emptySet(), excludePrefixes, includePrefixes); Set<String> expected = new HashSet<String>(); Collections.addAll(expected, "com/netflix/nicobar/hello", "com/netflix/nicobar/test/ui", "com/netflix/nicobar/test/ui/internal", "com/netflix/nicobar/test", "com/netflix/nicobar/hello/internal"); assertTrue(pkgPaths.equals(expected)); } }
1,848
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/utils/ScriptModuleUtilsTest.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.utils; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.jboss.modules.ModuleLoadException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.Sets; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.module.ScriptModule; import com.netflix.nicobar.core.module.ScriptModuleLoader; import com.netflix.nicobar.core.module.ScriptModuleUtils; import com.netflix.nicobar.core.plugin.BytecodeLoadingPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; /** * Unit tests for {@link ScriptModuleUtils} * * @author Vasanth Asokan */ public class ScriptModuleUtilsTest { private ScriptModuleLoader moduleLoader; @BeforeClass public void setup() throws ModuleLoadException, IOException { ScriptCompilerPluginSpec pluginSpec = getCompilerSpec(); // Create a set of app packages to allow access by the compilers, as well as the scripts. // We take a hammer approach and just exclude all com/netflix from the set of app packages exposed. Set<String> excludes = new HashSet<String>(); Collections.addAll(excludes, "com/netflix"); Set<String> pathSet = ClassPathUtils.scanClassPathWithExcludes(System.getProperty("java.class.path"), Collections.<String> emptySet(), excludes); moduleLoader = new ScriptModuleLoader.Builder() .addPluginSpec(pluginSpec) // TODO: The BytecodeLoadingPlugin seems to work without the app package filter // that we add below. This is likely something in our system, allowing packages to leak. // Need to follow up and see how IOUtils resolves correctly in the BytecodeLoadingPlugin // without an app package filter as below. .addAppPackages(pathSet) .build(); } @Test public void testScriptModuleConversion() throws Exception { URL jarPath = getClass().getClassLoader().getResource("testmodules/hellohelper.jar"); JarScriptArchive jarArchive = new JarScriptArchive.Builder(Paths.get(jarPath.getFile())) .build(); ModuleId moduleId = ModuleId.create("hellohelper"); moduleLoader.updateScriptArchives(Collections.singleton((ScriptArchive)jarArchive)); ScriptModule module = moduleLoader.getScriptModule(moduleId); assertNotNull(module); Path tmpDir = Files.createTempDirectory("ScriptModuleUtilsTest"); Path convertedJarPath = tmpDir.resolve("converted.jar"); ScriptModuleUtils.toCompiledScriptArchive(module, convertedJarPath, Sets.newHashSet(".class", ".java")); moduleLoader.removeScriptModule(moduleId); // Ensure that the converted archive works just as well as the new archive JarScriptArchive convertedJarArchive = new JarScriptArchive.Builder(convertedJarPath).build(); moduleLoader.updateScriptArchives(Collections.singleton(convertedJarArchive)); module = moduleLoader.getScriptModule(moduleId); assertNotNull(module); Class<?> targetClass = ScriptModuleUtils.findClass(module, "com.netflix.nicobar.test.HelloHelper"); Object instance = targetClass.newInstance(); Method method = targetClass.getMethod("execute"); String message = (String)method.invoke(instance); assertEquals(message, "Hello Nicobar World!"); } private ScriptCompilerPluginSpec getCompilerSpec() { // Create a compiler spec for the bytecode loading plugin ScriptCompilerPluginSpec compilerSpec = new ScriptCompilerPluginSpec.Builder(BytecodeLoadingPlugin.PLUGIN_ID) .withPluginClassName(BytecodeLoadingPlugin.class.getName()) .build(); return compilerSpec; } }
1,849
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/compile/BytecodeLoaderTest.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.compile; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.AssertJUnit.assertEquals; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Iterator; import java.util.Set; import org.mockito.Mockito; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.internal.compile.BytecodeLoader; import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; /** * Tests for the BytecodeLoader. * @author Vasanth Asokan */ public class BytecodeLoaderTest { @SuppressWarnings("rawtypes") private Class compiledClass; @BeforeMethod public void setup() { // Randomly assign some class compiledClass = this.getClass(); } @SuppressWarnings("unchecked") @Test public void testHelloworldArchive() throws Exception { URL jarPath = getClass().getClassLoader().getResource("testmodules/testmodule.jar"); JarScriptArchive scriptArchive = new JarScriptArchive.Builder(Paths.get(jarPath.getFile())) .build(); JBossModuleClassLoader moduleClassLoader = mock(JBossModuleClassLoader.class); BytecodeLoader loader = new BytecodeLoader(); when(moduleClassLoader.loadClassLocal(Mockito.anyString(), anyBoolean())).thenReturn(compiledClass); Set<Class<?>> compiledClasses = loader.compile(scriptArchive, moduleClassLoader, Files.createTempDirectory("BytecodeLoaderTest")); verify(moduleClassLoader).addClasses(compiledClasses); assertEquals(compiledClasses.size(), 1); Iterator<Class<?>> iterator = compiledClasses.iterator(); assertEquals(compiledClass, iterator.next()); } }
1,850
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/persistence/JarRepositoryPollerTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import java.nio.file.Path; import org.testng.annotations.Test; import com.netflix.nicobar.core.persistence.ArchiveRepository; import com.netflix.nicobar.core.persistence.ArchiveRepositoryPoller; import com.netflix.nicobar.core.persistence.JarArchiveRepository; /** * Integration tests for {@link JarArchiveRepository} and {@link ArchiveRepositoryPoller} * * @author James Kojo */ @Test public class JarRepositoryPollerTest extends ArchiveRepositoryPollerTest { @Override public ArchiveRepository createArchiveRepository(Path rootArchiveDirectory) { return new JarArchiveRepository.Builder(rootArchiveDirectory).build(); } }
1,851
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/persistence/PathRepositoryPollerTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import java.nio.file.Path; import org.testng.annotations.Test; import com.netflix.nicobar.core.persistence.ArchiveRepository; import com.netflix.nicobar.core.persistence.ArchiveRepositoryPoller; import com.netflix.nicobar.core.persistence.PathArchiveRepository; /** * Integration tests for {@link PathArchiveRepository} and {@link ArchiveRepositoryPoller} * * @author James Kojo */ @Test public class PathRepositoryPollerTest extends ArchiveRepositoryPollerTest { @Override public ArchiveRepository createArchiveRepository(Path rootArchiveDirectory) { return new PathArchiveRepository.Builder(rootArchiveDirectory).build(); } }
1,852
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/persistence/JarArchiveRepositoryTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.io.FileUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.netflix.nicobar.core.persistence.ArchiveRepository; import com.netflix.nicobar.core.persistence.JarArchiveRepository; /** * Unit tests for {@link JarArchiveRepository} * * @author James Kojo */ @Test public class JarArchiveRepositoryTest extends ArchiveRepositoryTest { private Path rootArchiveDirectory; @Override @BeforeClass public void setup() throws Exception { rootArchiveDirectory = Files.createTempDirectory(JarArchiveRepositoryTest.class.getSimpleName()+"_"); FileUtils.forceDeleteOnExit(rootArchiveDirectory.toFile()); super.setup(); } @Override public ArchiveRepository createRepository() { JarArchiveRepository archiveRepository = new JarArchiveRepository.Builder(rootArchiveDirectory).build(); return archiveRepository; } }
1,853
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/persistence/ArchiveRepositoryTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_MODULE_SPEC_JAR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.FileTime; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.IOUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.persistence.ArchiveRepository; import com.netflix.nicobar.core.persistence.ArchiveSummary; import com.netflix.nicobar.core.persistence.RepositorySummary; /** * Base Tests for {@link ArchiveRepository} implementations * * @author James Kojo */ public abstract class ArchiveRepositoryTest { private Path testArchiveJarFile; @BeforeClass public void setup() throws Exception { URL testJarUrl = getClass().getClassLoader().getResource(TEST_MODULE_SPEC_JAR.getResourcePath()); if (testJarUrl == null) { fail("Couldn't locate " + TEST_MODULE_SPEC_JAR.getResourcePath()); } testArchiveJarFile = Files.createTempFile(TEST_MODULE_SPEC_JAR.getModuleId().toString(), ".jar"); InputStream inputStream = testJarUrl.openStream(); Files.copy(inputStream, testArchiveJarFile, StandardCopyOption.REPLACE_EXISTING); IOUtils.closeQuietly(inputStream); } /** * Create an instance to be test */ public abstract ArchiveRepository createRepository(); /** * Test insert, update, delete */ @Test public void testRoundTrip() throws Exception { ArchiveRepository repository = createRepository(); JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(testArchiveJarFile).build(); ModuleId testModuleId = TEST_MODULE_SPEC_JAR.getModuleId(); repository.insertArchive(jarScriptArchive); Map<ModuleId, Long> archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes(); long expectedUpdateTime = Files.getLastModifiedTime(testArchiveJarFile).toMillis(); assertEquals(archiveUpdateTimes, Collections.singletonMap(testModuleId, expectedUpdateTime)); // assert getScriptArchives Set<ScriptArchive> scriptArchives = repository.getScriptArchives(archiveUpdateTimes.keySet()); assertEquals(scriptArchives.size(), 1, scriptArchives.toString()); ScriptArchive scriptArchive = scriptArchives.iterator().next(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), testModuleId); assertEquals(scriptArchive.getCreateTime(), expectedUpdateTime); // assert getArchiveSummaries List<ArchiveSummary> archiveSummaries = repository.getDefaultView().getArchiveSummaries(); assertEquals(archiveSummaries.size(), 1); ArchiveSummary archiveSummary = archiveSummaries.get(0); assertEquals(archiveSummary.getModuleId(), testModuleId); assertEquals(archiveSummary.getLastUpdateTime(), expectedUpdateTime); // assert getRepositorySummary RepositorySummary repositorySummary = repository.getDefaultView().getRepositorySummary(); assertNotNull(repositorySummary); assertEquals(repositorySummary.getArchiveCount(), 1); assertEquals(repositorySummary.getLastUpdated(), expectedUpdateTime); // advance the timestamp by 10 seconds and update expectedUpdateTime = expectedUpdateTime + 10000; Files.setLastModifiedTime(testArchiveJarFile, FileTime.fromMillis(expectedUpdateTime)); jarScriptArchive = new JarScriptArchive.Builder(testArchiveJarFile).build(); repository.insertArchive(jarScriptArchive); archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes(); assertEquals(archiveUpdateTimes, Collections.singletonMap(testModuleId, expectedUpdateTime)); // assert getScriptArchives scriptArchives = repository.getScriptArchives(archiveUpdateTimes.keySet()); assertEquals(scriptArchives.size(), 1, scriptArchives.toString()); scriptArchive = scriptArchives.iterator().next(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), testModuleId); assertEquals(scriptArchive.getCreateTime(), expectedUpdateTime); // assert getArchiveSummaries archiveSummaries = repository.getDefaultView().getArchiveSummaries(); assertEquals(archiveSummaries.size(), 1); archiveSummary = archiveSummaries.get(0); assertEquals(archiveSummary.getModuleId(), testModuleId); assertEquals(archiveSummary.getLastUpdateTime(), expectedUpdateTime); // assert getRepositorySummary repositorySummary = repository.getDefaultView().getRepositorySummary(); assertNotNull(repositorySummary); assertEquals(repositorySummary.getArchiveCount(), 1); assertEquals(repositorySummary.getLastUpdated(), expectedUpdateTime); // delete module repository.deleteArchive(testModuleId); archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes(); assertTrue(archiveUpdateTimes.isEmpty(), archiveUpdateTimes.toString()); } @Test public void testExternalizedModuleSpec() throws Exception { ArchiveRepository repository = createRepository(); ModuleId testModuleId = TEST_MODULE_SPEC_JAR.getModuleId(); ScriptModuleSpec expectedModuleSpec = new ScriptModuleSpec.Builder(testModuleId) .addMetadata("externalizedMetaDataName1", "externalizedMetaDataValue1") .build(); JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(testArchiveJarFile) .setModuleSpec(expectedModuleSpec) .build(); repository.insertArchive(jarScriptArchive); Set<ScriptArchive> scriptArchives = repository.getScriptArchives(Collections.singleton(testModuleId)); assertEquals(scriptArchives.size(), 1, scriptArchives.toString()); ScriptModuleSpec actualModuleSpec = scriptArchives.iterator().next().getModuleSpec(); assertEquals(actualModuleSpec, expectedModuleSpec); } }
1,854
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/persistence/PathArchiveRepositoryTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.io.FileUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.netflix.nicobar.core.persistence.ArchiveRepository; import com.netflix.nicobar.core.persistence.PathArchiveRepository; /** * Unit tests for {@link PathArchiveRepository} * * @author James Kojo */ @Test public class PathArchiveRepositoryTest extends ArchiveRepositoryTest { private Path rootArchiveDirectory; @Override @BeforeClass public void setup() throws Exception { rootArchiveDirectory = Files.createTempDirectory(PathRepositoryPollerTest.class.getSimpleName()+"_"); FileUtils.forceDeleteOnExit(rootArchiveDirectory.toFile()); super.setup(); } @Override public ArchiveRepository createRepository() { PathArchiveRepository archiveRepository = new PathArchiveRepository.Builder(rootArchiveDirectory).build(); return archiveRepository; } }
1,855
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/persistence/ArchiveRepositoryPollerTest.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_MODULE_SPEC_JAR; import static com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource.TEST_TEXT_JAR; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.module.ScriptModule; import com.netflix.nicobar.core.module.ScriptModuleListener; import com.netflix.nicobar.core.module.ScriptModuleLoader; import com.netflix.nicobar.core.plugin.TestCompilerPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import com.netflix.nicobar.core.testutil.CoreTestResourceUtil.TestResource; /** * Base integration tests for {@link PathArchiveRepository} * * @author James Kojo * @author Vasanth Asokan */ public abstract class ArchiveRepositoryPollerTest { private final static Logger logger = LoggerFactory.getLogger(ScriptModuleLoader.class); protected ArchiveRepository archiveRepository; protected ScriptModuleLoader moduleLoader; /** * Create the repository to plug in to the integration gets * @return */ public abstract ArchiveRepository createArchiveRepository(Path rootArchiveDirectory); @BeforeClass public void classSetup() throws Exception { Path rootArchiveDirectory = Files.createTempDirectory(ArchiveRepositoryPollerTest.class.getSimpleName()+"_"); logger.info("rootArchiveDirectory: {}", rootArchiveDirectory); FileUtils.forceDeleteOnExit(rootArchiveDirectory.toFile()); archiveRepository = createArchiveRepository(rootArchiveDirectory); long now = System.currentTimeMillis(); deployJarArchive(TEST_TEXT_JAR, now); deployJarArchive(TEST_MODULE_SPEC_JAR, now); } @BeforeMethod public void testSetup() throws Exception { ScriptCompilerPluginSpec pluginSpec = new ScriptCompilerPluginSpec.Builder(TestCompilerPlugin.PLUGIN_ID) .withPluginClassName(TestCompilerPlugin.class.getName()) .build(); moduleLoader = new ScriptModuleLoader.Builder().addPluginSpec(pluginSpec).build(); } /** * Simulate what a client might do at startup */ @Test public void testInitialLoad() throws Exception { ArchiveRepositoryPoller poller = new ArchiveRepositoryPoller.Builder(moduleLoader).build(); poller.addRepository(archiveRepository, 10, TimeUnit.SECONDS, true); Map<ModuleId, ScriptModule> scriptModules = moduleLoader.getAllScriptModules(); assertEquals(scriptModules.keySet(), new HashSet<ModuleId>(Arrays.asList(TEST_TEXT_JAR.getModuleId(), TEST_MODULE_SPEC_JAR.getModuleId()))); List<ArchiveSummary> archiveSummaries = archiveRepository.getDefaultView().getArchiveSummaries(); for (ArchiveSummary archiveSummary : archiveSummaries) { ScriptModule scriptModule = moduleLoader.getScriptModule(archiveSummary.getModuleId()); assertNotNull(scriptModule); assertEquals(scriptModule.getCreateTime(), archiveSummary.getLastUpdateTime()); } poller.shutdown(); } /** * Simulate what a client might do on an on-going bases */ @Test public void testPolling() throws Exception { ScriptModuleListener mockListener = mock(ScriptModuleListener.class); moduleLoader.addListeners(Collections.singleton(mockListener)); // initial startup phase ArchiveRepositoryPoller poller = new ArchiveRepositoryPoller.Builder(moduleLoader).build(); poller.addRepository(archiveRepository, Integer.MAX_VALUE, TimeUnit.MILLISECONDS, true); Map<ModuleId, Long> origUpdateTimes = archiveRepository.getDefaultView().getArchiveUpdateTimes(); verify(mockListener, times(2)).moduleUpdated(any(ScriptModule.class), eq((ScriptModule)null)); verifyNoMoreInteractions(mockListener); // poll for changes poller.pollRepository(archiveRepository); verifyNoMoreInteractions(mockListener); // touch a file to force a reload then poll. some filesystems only have 1 second granularity, so advance by at least that much long updateTime = origUpdateTimes.get(TEST_MODULE_SPEC_JAR.getModuleId()) + 1000; deployJarArchive(TEST_MODULE_SPEC_JAR, updateTime); poller.pollRepository(archiveRepository); verify(mockListener).moduleUpdated(any(ScriptModule.class), (ScriptModule)Mockito.notNull()); verifyNoMoreInteractions(mockListener); // poll one more time to make sure the state has been reset properly poller.pollRepository(archiveRepository); verifyNoMoreInteractions(mockListener); } /** * Simulate a deletion */ @Test(priority=Integer.MAX_VALUE) // run this last public void testDelete() throws Exception { ScriptModuleListener mockListener = mock(ScriptModuleListener.class); moduleLoader.addListeners(Collections.singleton(mockListener)); // initial startup phase ArchiveRepositoryPoller poller = new ArchiveRepositoryPoller.Builder(moduleLoader).build(); poller.addRepository(archiveRepository, Integer.MAX_VALUE, TimeUnit.MILLISECONDS, true); verify(mockListener, times(2)).moduleUpdated(any(ScriptModule.class), eq((ScriptModule)null)); verifyNoMoreInteractions(mockListener); // delete a module archiveRepository.deleteArchive(TEST_MODULE_SPEC_JAR.getModuleId()); poller.pollRepository(archiveRepository); verify(mockListener).moduleUpdated(eq((ScriptModule)null), any(ScriptModule.class)); verifyNoMoreInteractions(mockListener); // poll one more time to make sure the state has been reset properly poller.pollRepository(archiveRepository); verifyNoMoreInteractions(mockListener); // restore the module and reload reset(mockListener); deployJarArchive(TEST_MODULE_SPEC_JAR, System.currentTimeMillis()); poller.pollRepository(archiveRepository); verify(mockListener).moduleUpdated(any(ScriptModule.class), eq((ScriptModule)null)); verifyNoMoreInteractions(mockListener); } /** * inert the given archive resource to the test archive repository */ protected void deployJarArchive(TestResource testResource, long updateTime) throws Exception { String testResourcePath = testResource.getResourcePath(); URL archiveUrl = getClass().getClassLoader().getResource(testResourcePath); assertNotNull(archiveUrl, "couldn't find test resource with path " + testResourcePath); Path archiveJarPath = Paths.get(archiveUrl.toURI()); JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(archiveJarPath) .setCreateTime(updateTime) .build(); archiveRepository.insertArchive(jarScriptArchive); } }
1,856
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/core/testutil/CoreTestResourceUtil.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.testutil; import static org.testng.Assert.fail; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import com.netflix.nicobar.core.archive.ModuleId; /** * Utility class to locate test resources * * @author James Kojo * @author Vasanth Asokan * @author Aaron Tull */ public class CoreTestResourceUtil { /** * Metadata for test resources found in test/resource */ public static enum TestResource { TEST_TEXT_PATH("test-text", "paths/test-text", "sub1/sub1.txt", "sub2/sub2.txt", "root.txt", "META-INF/MANIFEST.MF"), TEST_TEXT_JAR("test-text", "jars/test-text.jar", "sub1/sub1.txt", "sub2/sub2.txt", "root.txt", "moduleSpec.json", "META-INF/MANIFEST.MF"), TEST_MODULE_SPEC_PATH("test-modulespec-moduleId", "paths/test-modulespec", "root.txt", "META-INF/MANIFEST.MF"), TEST_DEFAULT_MODULE_SPEC_JAR("test-default-modulespec", "jars/test-default-modulespec.jar", "root.txt", "META-INF/MANIFEST.MF"), TEST_DEFAULT_MODULE_SPEC_JAR2("moduleName.moduleVersion", "testmodules/moduleName.moduleVersion.jar"), TEST_MODULE_SPEC_JAR("test-modulespec-moduleId", "jars/test-modulespec.jar", "root.txt", "META-INF/MANIFEST.MF"), TEST_SCRIPTS_PATH("test-scripts-moduleId", "scripts", "script1.txt", "script2.txt", "script3.txt"), TEST_CLASSPATHDIR_PATH("test-classpath", "classpathdir"), TEST_DEPENDENCIES_PRIMARY("interdependent-primary", "jars/interfaces-module.jar"), TEST_DEPENDENCIES_DEPENDENT("interdependent-dependent", "jars/impl-module.jar"), TEST_CLASSPATH_DEPENDENT("classpath-dependent", "jars/classpath-dependent-module.jar"), TEST_DEPENDENT("classpath-dependent", "jars/dependent-module.jar"), TEST_SERVICE("classpath-dependent", "jars/service-module.jar"); private final ModuleId moduleId; private final String resourcePath; private final Set<String> contentPaths; private TestResource(String moduleId, String resourcePath, String... contentPaths) { this.moduleId = ModuleId.fromString(moduleId); this.resourcePath = resourcePath; this.contentPaths = new LinkedHashSet<String>(Arrays.asList(contentPaths)); } /** * @return the expected moduleId after this is converted to a archive */ public ModuleId getModuleId() { return moduleId; } /** * @return path name suitable for passing to {@link ClassLoader#getResource(String)} */ public String getResourcePath() { return resourcePath; } /** * @return the relative path names found in the resource */ public Set<String> getContentPaths() { return contentPaths; } } /** * Locate the given script in the class path * @param script script identifier * @return absolute path to the test script */ public static Path getResourceAsPath(TestResource script) throws Exception { URL scriptUrl = Thread.currentThread().getContextClassLoader().getResource(script.getResourcePath()); if (scriptUrl == null) { fail("couldn't load resource " + script.getResourcePath()); } return Paths.get(scriptUrl.toURI()); } }
1,857
0
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar
Create_ds/Nicobar/nicobar-core/src/test/java/com/netflix/nicobar/test/Service.java
package com.netflix.nicobar.test; public class Service { public String service() { return "From App Classpath"; } }
1,858
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/archive/ScriptArchive.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.Set; import javax.annotation.Nullable; /** * Data object which represents a bundle of scripts and associated resources. * Also contains a {@link ScriptModuleSpec} to describe how this archive * is to be converted into a module, and optionally, a set of deploy specs that * describes deploy data useful in operating the module. * * @author James Kojo * @author Vasanth Asokan */ public interface ScriptArchive { /** * @return the module spec for this archive */ public ScriptModuleSpec getModuleSpec(); /** * Set the module spec for this archive. * This will override an already set module spec. * @param spec the module spec to set to. */ public void setModuleSpec(ScriptModuleSpec spec); /** * @return {@link URL}s representing the contents of this archive. should be * suitable for passing to a {@link URLClassLoader} */ @Nullable public URL getRootUrl(); /** * @return relative path names of all the entries in the script archive. */ public Set<String> getArchiveEntryNames(); /** * @return a URL to the resource. * @throws IOException */ @Nullable public URL getEntry(String entryName) throws IOException; /** * Timestamp used to resolve multiple revisions of the archive. If multiple archives * are submitted with the same moduleId, only the one with the highest timestamp will be used. */ public long getCreateTime(); }
1,859
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/archive/SingleFileScriptArchive.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Objects; import java.util.Set; import javax.annotation.Nullable; /** * Script archive backed by a single file in a given {@link Path}. * */ public class SingleFileScriptArchive implements ScriptArchive { /** * Used to Construct a {@link PathScriptArchive}. * <pre> * Default settings: * * generate a moduleId using the last element of the {@link Path} * * all files under the root path will be included in the archive. * * searches for a module spec file under the root directory called "moduleSpec.json" and * uses the {@link GsonScriptModuleSpecSerializer} to deserialize it. * </pre> */ public static class Builder { private final Path filePath; private ScriptModuleSpec moduleSpec; private long createTime; /** * Start a builder with required parameters. * @param filePath absolute path to the script file */ public Builder(Path filePath) { this.filePath = filePath; } /** Set the module spec for this archive */ public Builder setModuleSpec(ScriptModuleSpec moduleSpec) { this.moduleSpec = moduleSpec; return this; } /** Set the creation time */ public Builder setCreateTime(long createTime) { this.createTime = createTime; return this; } /** Build the {@link PathScriptArchive}. */ public SingleFileScriptArchive build() throws IOException { long buildCreateTime = createTime; if (buildCreateTime <= 0) { buildCreateTime = Files.getLastModifiedTime(filePath).toMillis(); } ScriptModuleSpec buildModuleSpec = moduleSpec; // Define moduleId canonically as the file name with '.'s replaced by '_'. if (buildModuleSpec == null) { ModuleId moduleId = ModuleId.create(this.filePath.getFileName().toString().replaceAll("\\.", "_")); buildModuleSpec = new ScriptModuleSpec.Builder(moduleId).build(); } Path rootDir = filePath.normalize().getParent(); String fileName = rootDir.relativize(filePath).toString(); return new SingleFileScriptArchive(buildModuleSpec, rootDir, fileName, buildCreateTime); } } private final Set<String> entryNames; private final Path rootDirPath; private final URL rootUrl; private final long createTime; private ScriptModuleSpec moduleSpec; protected SingleFileScriptArchive(ScriptModuleSpec moduleSpec, Path rootDirPath, String fileName, long createTime) throws IOException { this.moduleSpec = Objects.requireNonNull(moduleSpec, "moduleSpec"); this.rootDirPath = Objects.requireNonNull(rootDirPath, "rootDirPath"); if (!this.rootDirPath.isAbsolute()) throw new IllegalArgumentException("rootPath must be absolute."); this.entryNames = Collections.singleton(Objects.requireNonNull(fileName, "fileName")); this.rootUrl = this.rootDirPath.toUri().toURL(); this.createTime = createTime; } @Override public ScriptModuleSpec getModuleSpec() { return moduleSpec; } @Override public void setModuleSpec(ScriptModuleSpec spec) { this.moduleSpec = spec; } @Override public URL getRootUrl() { return rootUrl; } @Override public Set<String> getArchiveEntryNames() { return entryNames; } @Override @Nullable public URL getEntry(String entryName) throws IOException { if (!entryNames.contains(entryName)) { return null; } return rootDirPath.resolve(entryName).toUri().toURL(); } @Override public long getCreateTime() { return createTime; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SingleFileScriptArchive other = (SingleFileScriptArchive) o; return Objects.equals(this.moduleSpec, other.moduleSpec) && Objects.equals(this.entryNames, other.entryNames) && Objects.equals(this.rootDirPath, other.rootDirPath) && Objects.equals(this.rootUrl, other.rootUrl) && Objects.equals(this.createTime, other.createTime); } @Override public int hashCode() { return Objects.hash(moduleSpec, entryNames,rootDirPath, rootUrl, createTime); } }
1,860
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/archive/PathScriptArchive.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import java.io.IOException; import java.net.URL; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import javax.annotation.Nullable; import org.apache.commons.io.Charsets; /** * Script archive backed by a files in a {@link Path}. * * @author James Kojo */ public class PathScriptArchive implements ScriptArchive { private final static ScriptModuleSpecSerializer DEFAULT_SPEC_SERIALIZER = new GsonScriptModuleSpecSerializer(); /** * Used to Construct a {@link PathScriptArchive}. * <pre> * Default settings: * * generate a moduleId using the last element of the {@link Path} * * all files under the root path will be included in the archive. * * searches for a module spec file under the root directory called "moduleSpec.json" and * uses the {@link GsonScriptModuleSpecSerializer} to deserialize it. * </pre> */ public static class Builder { private final Path rootDirPath; private final Set<Path> addedFiles = new LinkedHashSet<Path>(); private ScriptModuleSpec moduleSpec; boolean recurseRoot = true; private ScriptModuleSpecSerializer specSerializer = DEFAULT_SPEC_SERIALIZER; private long createTime; /** * Start a builder with required parameters. * @param rootDirPath absolute path to the root directory to recursively add */ public Builder(Path rootDirPath) { this.rootDirPath = rootDirPath; } /** If true, then add all of the files underneath the root path. default is true */ public Builder setRecurseRoot(boolean recurseRoot) { this.recurseRoot = recurseRoot; return this; } /** Set the module spec for this archive */ public Builder setModuleSpec(ScriptModuleSpec moduleSpec) { this.moduleSpec = moduleSpec; return this; } /** override the default module spec file name */ public Builder setModuleSpecSerializer(ScriptModuleSpecSerializer specSerializer) { this.specSerializer = specSerializer; return this; } /** * Append a single file to the archive * @param file relative path from the root */ public Builder addFile(Path file) { if (file != null) { addedFiles.add(file); } return this; } /** Set the creation time */ public Builder setCreateTime(long createTime) { this.createTime = createTime; return this; } /** Build the {@link PathScriptArchive}. */ public PathScriptArchive build() throws IOException { ScriptModuleSpec buildModuleSpec = moduleSpec; if (buildModuleSpec == null) { // attempt to find a module spec in the root directory Path moduleSpecLocation = rootDirPath.resolve(specSerializer.getModuleSpecFileName()); if (Files.exists(moduleSpecLocation)) { byte[] bytes = Files.readAllBytes(moduleSpecLocation); if (bytes != null && bytes.length > 0) { String json = new String(bytes, Charsets.UTF_8); buildModuleSpec = specSerializer.deserialize(json); } } // create a default spec if (buildModuleSpec == null) { ModuleId moduleId = ModuleId.create(this.rootDirPath.getFileName().toString()); buildModuleSpec = new ScriptModuleSpec.Builder(moduleId).build(); } } final LinkedHashSet<String> buildEntries = new LinkedHashSet<String>(); if (recurseRoot) { Files.walkFileTree(this.rootDirPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path relativePath = rootDirPath.relativize(file); buildEntries.add(relativePath.toString()); return FileVisitResult.CONTINUE; }; }); } for (Path file : addedFiles) { if (file.isAbsolute()) { file = rootDirPath.relativize(file); } buildEntries.add(file.toString()); } long buildCreateTime = createTime; if (buildCreateTime <= 0) { buildCreateTime = Files.getLastModifiedTime(rootDirPath).toMillis(); } return new PathScriptArchive(buildModuleSpec, rootDirPath, buildEntries, buildCreateTime); } } private final Set<String> entryNames; private final Path rootDirPath; private final URL rootUrl; private final long createTime; private ScriptModuleSpec moduleSpec; protected PathScriptArchive(ScriptModuleSpec moduleSpec, Path rootDirPath, Set<String> entries, long createTime) throws IOException { this.moduleSpec = Objects.requireNonNull(moduleSpec, "moduleSpec"); this.rootDirPath = Objects.requireNonNull(rootDirPath, "rootDirPath"); if (!this.rootDirPath.isAbsolute()) throw new IllegalArgumentException("rootPath must be absolute."); this.entryNames = Collections.unmodifiableSet(Objects.requireNonNull(entries, "entries")); this.rootUrl = this.rootDirPath.toUri().toURL(); this.createTime = createTime; } @Override public ScriptModuleSpec getModuleSpec() { return moduleSpec; } @Override public void setModuleSpec(ScriptModuleSpec spec) { this.moduleSpec = spec; } @Override public URL getRootUrl() { return rootUrl; } @Override public Set<String> getArchiveEntryNames() { return entryNames; } @Override @Nullable public URL getEntry(String entryName) throws IOException { if (!entryNames.contains(entryName)) { return null; } return rootDirPath.resolve(entryName).toUri().toURL(); } @Override public long getCreateTime() { return createTime; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PathScriptArchive other = (PathScriptArchive) o; return Objects.equals(this.moduleSpec, other.moduleSpec) && Objects.equals(this.entryNames, other.entryNames) && Objects.equals(this.rootDirPath, other.rootDirPath) && Objects.equals(this.rootUrl, other.rootUrl) && Objects.equals(this.createTime, other.createTime); } @Override public int hashCode() { return Objects.hash(moduleSpec, entryNames,rootDirPath, rootUrl, createTime); } }
1,861
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/archive/ScriptModuleSpecSerializer.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; /** * Serializer for the {@link ScriptModuleSpec} * * @author James Kojo */ public interface ScriptModuleSpecSerializer { /** * Convert the {@link ScriptModuleSpec} to a JSON String */ public String serialize(ScriptModuleSpec moduleSpec); /** * Convert the input JSON String to a {@link ScriptModuleSpec} */ public ScriptModuleSpec deserialize(String json); /** * Filename to use when outputting a serialized module spec */ public String getModuleSpecFileName(); }
1,862
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/archive/ScriptModuleSpec.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * Common configuration elements for converting a {@link ScriptArchive} to a module. * @author James Kojo * @author Vasanth Asokan * @author Aaron Tull */ public class ScriptModuleSpec { /** * Used to Construct a {@link ScriptModuleSpec}. */ public static class Builder { private final ModuleId moduleId; private final Set<String> compilerPluginIds = new LinkedHashSet<String>(); private final Map<String, Object> archiveMetadata = new LinkedHashMap<String, Object>(); private final Set<ModuleId> moduleDependencies = new LinkedHashSet<ModuleId>(); private Set<String> appImportFilters = null; private Set<String> moduleImportFilters = null; private Set<String> moduleExportFilters = null; public Builder(String moduleId) { this.moduleId = ModuleId.fromString(moduleId); } public Builder(ModuleId moduleId) { this.moduleId = moduleId; } /** Add a dependency on the named compiler plugin */ public Builder addCompilerPluginId(String pluginId) { if (pluginId != null) { compilerPluginIds.add(pluginId); } return this; } /** Add a dependency on the named compiler plugin */ public Builder addCompilerPluginIds(Set<String> pluginIds) { if (pluginIds != null) { compilerPluginIds.addAll(pluginIds); } return this; } /** Append all of the given metadata. */ public Builder addMetadata(Map<String, Object> metadata) { if (metadata != null) { archiveMetadata.putAll(metadata); } return this; } /** Append the given metadata. */ public Builder addMetadata(String property, Object value) { if (property != null && value != null) { archiveMetadata.put(property, value); } return this; } /** Add Module dependency. */ public Builder addModuleDependency(String dependencyName) { if (dependencyName != null) { moduleDependencies.add(ModuleId.fromString(dependencyName)); } return this; } /** Add Module dependency. */ public Builder addModuleDependency(ModuleId dependency) { if (dependency != null) { moduleDependencies.add(dependency); } return this; } /** Add Module dependencies. */ public Builder addModuleDependencies(Set<ModuleId> dependencies) { if (dependencies != null) { for (ModuleId dependency: dependencies) { addModuleDependency(dependency); } } return this; } /** Add Module app import filter paths. */ public Builder addAppImportFilters(Set<String> filterPaths) { if (filterPaths != null) { for (String path: filterPaths) { addAppImportFilter(path); } } return this; } /** Add a Module app import filter path. */ public Builder addAppImportFilter(String filterPath) { if (filterPath != null) { if (appImportFilters == null) { appImportFilters = new LinkedHashSet<String>(); } appImportFilters.add(filterPath); } return this; } /** Add Module import filter paths. */ public Builder addModuleImportFilters(Set<String> filterPaths) { if (filterPaths != null) { for (String path: filterPaths) { addModuleImportFilter(path); } } return this; } /** Add a Module import filter path. */ public Builder addModuleImportFilter(String filterPath) { if (filterPath != null) { if (moduleImportFilters== null) { moduleImportFilters = new LinkedHashSet<String>(); } moduleImportFilters.add(filterPath); } return this; } /** Add Module export filter paths. */ public Builder addModuleExportFilters(Set<String> filterPaths) { if (filterPaths != null) { for (String path: filterPaths) { addModuleExportFilter(path); } } return this; } /** Add a Module export filter path. */ public Builder addModuleExportFilter(String filterPath) { if (filterPath != null) { if (moduleExportFilters== null) { moduleExportFilters = new LinkedHashSet<String>(); } moduleExportFilters.add(filterPath); } return this; } /** Build the {@link PathScriptArchive}. */ public ScriptModuleSpec build() { return new ScriptModuleSpec(moduleId, Collections.unmodifiableMap(new HashMap<String, Object>(archiveMetadata)), Collections.unmodifiableSet(new LinkedHashSet<ModuleId>(moduleDependencies)), Collections.unmodifiableSet(new LinkedHashSet<String>(compilerPluginIds)), appImportFilters != null ? Collections.unmodifiableSet(appImportFilters) : null, moduleImportFilters != null ? Collections.unmodifiableSet(moduleImportFilters) : null, moduleExportFilters != null ? Collections.unmodifiableSet(moduleExportFilters) : null); } } private final ModuleId moduleId; private final Map<String, Object> archiveMetadata; private final Set<ModuleId> moduleDependencies; private final Set<String> compilerPluginIds; private final Set<String> appImportFilters; private final Set<String> importFilters; private final Set<String> exportFilters; protected ScriptModuleSpec(ModuleId moduleId, Map<String, Object> archiveMetadata, Set<ModuleId> moduleDependencies, Set<String> pluginIds, @Nullable Set<String> appImportFilters, @Nullable Set<String> importFilters, @Nullable Set<String> exportFilters) { this.moduleId = Objects.requireNonNull(moduleId, "moduleId"); this.compilerPluginIds = Objects.requireNonNull(pluginIds, "compilerPluginIds"); this.archiveMetadata = Objects.requireNonNull(archiveMetadata, "archiveMetadata"); this.moduleDependencies = Objects.requireNonNull(moduleDependencies, "dependencies"); this.appImportFilters = appImportFilters; this.importFilters = importFilters; this.exportFilters = exportFilters; } /** * @return id of the archive and the subsequently created module */ public ModuleId getModuleId() { return moduleId; } /** * @return Application specific metadata about this archive. This metadata will * be transferred to the Module after it's been created */ public Map<String, Object> getMetadata() { return archiveMetadata; } /** * @return the names of the modules that this archive depends on */ public Set<ModuleId> getModuleDependencies() { return moduleDependencies; } /** * @return the string IDs of the compiler plugins that should process this archive */ public Set<String> getCompilerPluginIds() { return compilerPluginIds; } /** * @return the paths imported into the module from the app classloader. * If this is null, it indicates that no filter is to be applied (accepts all). */ @Nullable public Set<String> getAppImportFilterPaths() { return appImportFilters; } /** * @return the paths imported into the module from dependencies * If this is null, it indicates that no filter is to be applied (accepts all). */ @Nullable public Set<String> getModuleImportFilterPaths() { return importFilters; } /** * @return the paths exported to all modules from dependencies of this module * If this is null, it indicates that no filter is to be applied (accepts all). */ @Nullable public Set<String> getModuleExportFilterPaths() { return exportFilters; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ScriptModuleSpec other = (ScriptModuleSpec) o; return Objects.equals(this.moduleId, other.moduleId) && Objects.equals(this.archiveMetadata, other.archiveMetadata) && Objects.equals(this.compilerPluginIds, other.compilerPluginIds) && Objects.equals(this.moduleDependencies, other.moduleDependencies); } @Override public int hashCode() { return Objects.hash(moduleId, moduleId, compilerPluginIds, moduleDependencies); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("moduleId", moduleId) .append("archiveMetadata", archiveMetadata) .append("compilerPlugins", compilerPluginIds) .append("dependencies", moduleDependencies) .toString(); } }
1,863
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/archive/GsonScriptModuleSpecSerializer.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import java.lang.reflect.Type; import java.util.Objects; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; /** * Gson based implementation of the {@link ScriptModuleSpecSerializer} * * @author James Kojo * @author Vasanth Asokan */ public class GsonScriptModuleSpecSerializer implements ScriptModuleSpecSerializer { /** Default file name of the optional {@link ScriptModuleSpec} in the archive */ public final static String DEFAULT_MODULE_SPEC_FILE_NAME = "moduleSpec.json"; private static Gson SERIALIZER = new GsonBuilder() .registerTypeAdapter(ModuleId.class, new ModuleIdGsonTransformer()) .registerTypeAdapter(Double.class, new DoubleGsonTransformer()) .create(); private final String moduleSpecFileName; public GsonScriptModuleSpecSerializer() { this(DEFAULT_MODULE_SPEC_FILE_NAME); } /** * @param moduleSpecFileName file name to use when outputting a serialized moduleSpec */ public GsonScriptModuleSpecSerializer(String moduleSpecFileName) { this.moduleSpecFileName = Objects.requireNonNull(moduleSpecFileName, "moduleSpecFileName"); } /** * Convert the {@link ScriptModuleSpec} to a JSON String */ @Override public String serialize(ScriptModuleSpec moduleSpec) { Objects.requireNonNull(moduleSpec, "moduleSpec"); String json = SERIALIZER.toJson(moduleSpec); return json; } /** * Convert the input JSON String to a {@link ScriptModuleSpec} */ @Override public ScriptModuleSpec deserialize(String json) { Objects.requireNonNull(json, "json"); ScriptModuleSpec moduleSpec = SERIALIZER.fromJson(json, ScriptModuleSpec.class); return moduleSpec; } @Override public String getModuleSpecFileName() { return moduleSpecFileName; } /** * @return the serializer. Override this to customize the serialization logic */ protected Gson getSerializer() { return SERIALIZER; } /** * Custom GSON serializer and deserializer for ModuleId */ private static class ModuleIdGsonTransformer implements JsonSerializer<ModuleId>, JsonDeserializer<ModuleId> { @Override public JsonElement serialize(ModuleId src, Type typeOfSrc, JsonSerializationContext context) { return context.serialize(src.toString()); } @Override public ModuleId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException { String moduleId = json.getAsString(); return ModuleId.fromString(moduleId); } } /** * Custom GSON Double serializer * This overrides default Gson behavior, which converts integers and longs into * floats and doubles before writing out as JSON numbers. */ private static class DoubleGsonTransformer implements JsonSerializer<Double> { @Override public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { if (src == src.longValue()) return new JsonPrimitive(src.longValue()); return new JsonPrimitive(src); } } }
1,864
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/archive/ModuleId.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.archive; import java.util.Objects; import java.util.regex.Pattern; /** * A unique identifier for a script module, composed out of a name and a * version identifier. * * @author Vasanth Asokan, based on ModuleIdentifier.java in org.jboss.modules. */ public final class ModuleId { private static final String MODULE_NAME_PATTERN_STR = "^[a-zA-Z0-9_/][a-zA-Z0-9_\\-{}\\\\@$:<>/]*$"; private static final String MODULE_VERSION_PATTERN_STR = "^[a-zA-Z0-9_\\-]*$"; private static Pattern MODULE_NAME_PATTERN = Pattern.compile(MODULE_NAME_PATTERN_STR); private static Pattern MODULE_VERSION_PATTERN = Pattern.compile(MODULE_VERSION_PATTERN_STR); public static final String DEFAULT_VERSION = ""; public static final String MODULE_VERSION_SEPARATOR = "."; private final String name; private final String version; private final int hashCode; private ModuleId(final String name, final String version) { if (name == null || name.equals("")) { throw new IllegalArgumentException("Module name can not be null or empty."); } if (!MODULE_NAME_PATTERN.matcher(name).matches()) { throw new IllegalArgumentException("Module name must match " + MODULE_NAME_PATTERN_STR); } this.name = name; if (version == null) { this.version = DEFAULT_VERSION; } else { if (!MODULE_VERSION_PATTERN.matcher(version).matches()) { throw new IllegalArgumentException("Module version must match " + MODULE_VERSION_PATTERN_STR); } this.version = version; } hashCode = Objects.hash(name, version); } /** * Get the module name. * * @return the module name */ public String getName() { return name; } /** * Get the module version. * * @return the version string */ public String getVersion() { return version; } /** * Determine the hash code of this module identifier. * * @return the hash code */ @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ModuleId other = (ModuleId) o; return Objects.equals(this.name, other.name) && Objects.equals(this.version, other.version); } /** * Get the string representation of this module identifier. * If version != DEFAULT_VERSION, this is constructed as "{@code name.version}" * Else, this is constructed as "{@code name}". * * @return the string representation */ @Override public String toString() { if (version.equals(DEFAULT_VERSION)) return name; else return name + MODULE_VERSION_SEPARATOR + version; } /** * Parse a module id from a string. * If a version identifier cannot be extracted, the version identifier will * be set to "" (empty string). * * @param moduleId the id string * @return the module identifier * @throws IllegalArgumentException if the format of the module specification is invalid or it is {@code null} */ public static ModuleId fromString(String moduleId) throws IllegalArgumentException { if (moduleId == null) { throw new IllegalArgumentException("Module Id String is null"); } if (moduleId.length() == 0) { throw new IllegalArgumentException("Empty Module Id String"); } final int c1 = moduleId.lastIndexOf(MODULE_VERSION_SEPARATOR); final String name; final String version; if (c1 != -1) { name = moduleId.substring(0, c1); version = moduleId.substring(c1 + 1); } else { name = moduleId; version = DEFAULT_VERSION; } return new ModuleId(name, version); } /** * Creates a new module identifier using the specified name and version. * An unspecified or empty version ("") can be treated as the * canonical, latest version of the module, though the ultimate treatment * is upto the integration code using modules. * * @param name the name of the module * @param version the version string * @return the identifier */ public static ModuleId create(final String name, final String version) { return new ModuleId(name, version); } /** * Creates a new module identifier using the specified name. * * @param name the name of the module * @return the identifier */ public static ModuleId create(final String name) { return create(name, null); } }
1,865
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/archive/JarScriptArchive.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.archive; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import javax.annotation.Nullable; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * Script archive backed by a {@link JarFile}. * * The jar file may optionally contain a module specification. If it does, then the module specification * is deserialized and used to construct the archive. Otherwise, a module specification with default values * is created. * * @author James Kojo * @author Vasanth Asokan */ public class JarScriptArchive implements ScriptArchive { /** Default file name of the optional {@link ScriptModuleSpec} in the archive */ public final static String DEFAULT_MODULE_SPEC_FILE_NAME = "moduleSpec.json"; private final static String JAR_FILE_SUFFIX = ".jar"; private final static ScriptModuleSpecSerializer DEFAULT_SPEC_SERIALIZER = new GsonScriptModuleSpecSerializer(); /** * Used to Construct a {@link JarScriptArchive}. * By default, this will generate a moduleId using the name of the jarfile, minus the ".jar" suffix. */ public static class Builder { private final Path jarPath; private ScriptModuleSpec moduleSpec; private String specFileName; private ScriptModuleSpecSerializer specSerializer; private long createTime; /** * Start a builder with required parameters. * @param jarPath absolute path to the jarfile that this will represent */ public Builder(Path jarPath) { this.jarPath = jarPath; } /** Set the module spec for this archive */ public Builder setModuleSpec(ScriptModuleSpec moduleSpec) { this.moduleSpec = moduleSpec; return this; } /** override the default module spec file name */ public Builder setModuleSpecFileName(String specFileName) { this.specFileName = specFileName; return this; } /** override the default module spec file name */ public Builder setModuleSpecSerializer(ScriptModuleSpecSerializer specSerializer) { this.specSerializer = specSerializer; return this; } /** Set the creation time */ public Builder setCreateTime(long createTime) { this.createTime = createTime; return this; } /** Build the {@link JarScriptArchive}. */ public JarScriptArchive build() throws IOException { ScriptModuleSpec buildModuleSpec = moduleSpec; String moduleSpecEntry = null; if (buildModuleSpec == null){ String buildSpecFileName = specFileName != null ? specFileName : DEFAULT_MODULE_SPEC_FILE_NAME; // attempt to find a module spec in the jar file JarFile jarFile = new JarFile(jarPath.toFile()); try { ZipEntry zipEntry = jarFile.getEntry(buildSpecFileName); if (zipEntry != null) { moduleSpecEntry = buildSpecFileName; InputStream inputStream = jarFile.getInputStream(zipEntry); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(inputStream, outputStream); byte[] bytes = outputStream.toByteArray(); if (bytes != null && bytes.length > 0) { String json = new String(bytes, Charsets.UTF_8); ScriptModuleSpecSerializer buildSpecSerializer = specSerializer != null ? specSerializer : DEFAULT_SPEC_SERIALIZER; buildModuleSpec = buildSpecSerializer.deserialize(json); } } } finally { IOUtils.closeQuietly(jarFile); } // create a default module spec if (buildModuleSpec == null) { String jarFileName = this.jarPath.getFileName().toString(); if (jarFileName.endsWith(JAR_FILE_SUFFIX)) { jarFileName = jarFileName.substring(0, jarFileName.lastIndexOf(JAR_FILE_SUFFIX)); } ModuleId moduleId = ModuleId.fromString(jarFileName); buildModuleSpec = new ScriptModuleSpec.Builder(moduleId).build(); } } long buildCreateTime = createTime; if (buildCreateTime <= 0) { buildCreateTime = Files.getLastModifiedTime(jarPath).toMillis(); } return new JarScriptArchive(buildModuleSpec, jarPath, moduleSpecEntry, buildCreateTime); } } private final Set<String> entryNames; private final URL rootUrl; private final long createTime; private ScriptModuleSpec moduleSpec; protected JarScriptArchive(ScriptModuleSpec moduleSpec, Path jarPath, long createTime) throws IOException { this(moduleSpec, jarPath, null, createTime); } protected JarScriptArchive(ScriptModuleSpec moduleSpec, Path jarPath, String moduleSpecEntry, long createTime) throws IOException { this.createTime = createTime; this.moduleSpec = Objects.requireNonNull(moduleSpec, "moduleSpec"); Objects.requireNonNull(jarPath, "jarFile"); if (!jarPath.isAbsolute()) throw new IllegalArgumentException("jarPath must be absolute."); // initialize the index JarFile jarFile = new JarFile(jarPath.toFile()); Set<String> indexBuilder; try { Enumeration<JarEntry> jarEntries = jarFile.entries(); indexBuilder = new HashSet<String>(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); // Skip adding moduleSpec to archive entries if (jarEntry.getName().equals(moduleSpecEntry)) { continue; } if (!jarEntry.isDirectory()) { indexBuilder.add(jarEntry.getName()); } } } finally { jarFile.close(); } entryNames = Collections.unmodifiableSet(indexBuilder); rootUrl = jarPath.toUri().toURL(); } @Override public ScriptModuleSpec getModuleSpec() { return moduleSpec; } @Override public void setModuleSpec(ScriptModuleSpec spec) { this.moduleSpec = spec; } /** * Gets the root path in the form of 'file://path/to/jarfile/jarfile.jar". */ @Override public URL getRootUrl() { return rootUrl; } @Override public Set<String> getArchiveEntryNames() { return entryNames; } @Override @Nullable public URL getEntry(String entryName) throws IOException { if (!entryNames.contains(entryName)) { return null; } String spec = new StringBuilder() .append("jar:").append(rootUrl.toString()).append("!/").append(entryName).toString(); return new URL(spec); } @Override public long getCreateTime() { return createTime; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JarScriptArchive other = (JarScriptArchive) o; return Objects.equals(this.moduleSpec, other.moduleSpec) && Objects.equals(this.entryNames, other.entryNames) && Objects.equals(this.rootUrl, other.rootUrl) && Objects.equals(this.createTime, other.createTime); } @Override public int hashCode() { return Objects.hash(moduleSpec, entryNames, rootUrl, createTime); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("moduleSpec", moduleSpec) .append("entryNames", entryNames) .append("rootUrl", rootUrl) .append("createTime", createTime) .toString(); } }
1,866
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/ScriptModuleLoader.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nullable; import org.apache.commons.io.FileUtils; import org.jboss.modules.Module; import org.jboss.modules.ModuleClassLoader; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleSpec; import org.jgrapht.DirectedGraph; import org.jgrapht.graph.DefaultEdge; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.compile.ScriptCompilationException; import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; import com.netflix.nicobar.core.module.jboss.JBossModuleLoader; import com.netflix.nicobar.core.module.jboss.JBossModuleUtils; import com.netflix.nicobar.core.module.jboss.JBossScriptModule; import com.netflix.nicobar.core.plugin.ScriptCompilerPlugin; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import static com.netflix.nicobar.core.module.ScriptModuleUtils.createModulePath; /** * Top level API for loading and accessing scripts. * Builds and maintains interdependent script modules. * Performs coordination between components neccessary for * finding, compiling and loading scripts and notifying event listeners. * * Listeners can be added at any time during the repositories lifecycle, but if they are * added at construction time, they are guaranteed to receive the events associate with the loading * of archives, while those that are added later will only get events generated after the listener was added. * * Support pluggable compilers via the {@link ScriptCompilerPluginSpec}. * * @author James Kojo * @author Vasanth Asokan * @author Aaron Tull */ public class ScriptModuleLoader { private final static Logger logger = LoggerFactory.getLogger(ScriptModuleLoader.class); /** * Builder used to constract a {@link ScriptModuleLoader} */ public static class Builder { private final Set<ScriptCompilerPluginSpec> pluginSpecs= new LinkedHashSet<ScriptCompilerPluginSpec>(); private final Set<ScriptModuleListener> listeners = new LinkedHashSet<ScriptModuleListener>(); private final Set<String> paths = new LinkedHashSet<String>(); private Path compilationRootDir; private ClassLoader appClassLoader = ScriptModuleLoader.class.getClassLoader(); public Builder() { } /** Add a language compiler plugin specification to the loader */ public Builder addPluginSpec(ScriptCompilerPluginSpec pluginSpec) { if (pluginSpec != null) { pluginSpecs.add(pluginSpec); } return this; } /** * Use a specific classloader as the application classloader. * @param loader the application classloader */ public Builder withAppClassLoader(ClassLoader loader) { Objects.requireNonNull(loader); this.appClassLoader = loader; return this; } /** * Use a specific compilation root directory * @param compilationRootDir the compilation directory root. */ public Builder withCompilationRootDir(Path compilationRootDir) { this.compilationRootDir = compilationRootDir; return this; } /** * Specify a set of packages to make available from the application classloader * as runtime dependencies for all scripts loaded by this script module. * @param incomingPaths a set of / separated package paths. No wildcards. * e.g. Specifying com/foo/bar/baz implies that all classes in packages * named com.foo.bar.baz.* will be visible to loaded modules. */ public Builder addAppPackages(Set<String> incomingPaths) { if (incomingPaths != null) { paths.addAll(incomingPaths); } return this; } /** Add a archive poller which will be polled at the given interval */ public Builder addListener(ScriptModuleListener listener) { if (listener != null) { listeners.add(listener); } return this; } public ScriptModuleLoader build() throws ModuleLoadException, IOException { if (compilationRootDir == null) { compilationRootDir = Files.createTempDirectory("ScriptModuleLoader"); } return new ScriptModuleLoader(pluginSpecs, appClassLoader, paths, listeners, compilationRootDir); } } /** Map of script ModuleId to the loaded ScriptModules */ protected final Map<ModuleId, ScriptModule> loadedScriptModules = new ConcurrentHashMap<ModuleId, ScriptModule>(); protected final Map<String, ClassLoader> compilerClassLoaders = new ConcurrentHashMap<String, ClassLoader>(); protected final Set<ScriptCompilerPluginSpec> pluginSpecs; protected final ClassLoader appClassLoader; protected final Set<String> appPackagePaths; protected final List<ScriptArchiveCompiler> compilers = new ArrayList<ScriptArchiveCompiler>(); protected final Path compilationRootDir; protected final Set<ScriptModuleListener> listeners = Collections.newSetFromMap(new ConcurrentHashMap<ScriptModuleListener, Boolean>()); protected final JBossModuleLoader jbossModuleLoader; protected ScriptModuleLoader(final Set<ScriptCompilerPluginSpec> pluginSpecs, final ClassLoader appClassLoader, final Set<String> appPackagePaths, final Set<ScriptModuleListener> listeners, final Path compilationRootDir) throws ModuleLoadException { this.pluginSpecs = Objects.requireNonNull(pluginSpecs); this.appClassLoader = Objects.requireNonNull(appClassLoader); this.appPackagePaths = Objects.requireNonNull(appPackagePaths); this.jbossModuleLoader = new JBossModuleLoader(); for (ScriptCompilerPluginSpec pluginSpec : pluginSpecs) { addCompilerPlugin(pluginSpec); } addListeners(Objects.requireNonNull(listeners)); this.compilationRootDir = compilationRootDir; } /** * Add or update the existing {@link ScriptModule}s with the given script archives. * This method will convert the archives to modules and then compile + link them in to the * dependency graph. It will then recursively re-link any modules depending on the new modules. * If this loader already contains an old version of the module, it will be unloaded on * successful compile of the new module. * * @param candidateArchives archives to load or update */ public synchronized void updateScriptArchives(Set<? extends ScriptArchive> candidateArchives) { Objects.requireNonNull(candidateArchives); long updateNumber = System.currentTimeMillis(); // map script module id to archive to be compiled Map<ModuleId, ScriptArchive> archivesToCompile = new HashMap<ModuleId, ScriptArchive>(candidateArchives.size()*2); // create an updated mapping of the scriptModuleId to latest revisionId including the yet-to-be-compiled archives Map<ModuleId, ModuleIdentifier> oldRevisionIdMap = jbossModuleLoader.getLatestRevisionIds(); Map<ModuleId, ModuleIdentifier> updatedRevisionIdMap = new HashMap<ModuleId, ModuleIdentifier>((oldRevisionIdMap.size()+candidateArchives.size())*2); updatedRevisionIdMap.putAll(oldRevisionIdMap); // Map of the scriptModuleId to it's updated set of dependencies Map<ModuleId, Set<ModuleId>> archiveDependencies = new HashMap<ModuleId, Set<ModuleId>>(); for (ScriptArchive scriptArchive : candidateArchives) { ModuleId scriptModuleId = scriptArchive.getModuleSpec().getModuleId(); // filter out archives that have a newer module already loaded long createTime = scriptArchive.getCreateTime(); ScriptModule scriptModule = loadedScriptModules.get(scriptModuleId); long latestCreateTime = scriptModule != null ? scriptModule.getCreateTime() : 0; if (createTime < latestCreateTime) { notifyArchiveRejected(scriptArchive, ArchiveRejectedReason.HIGHER_REVISION_AVAILABLE, null); continue; } // create the new revisionIds that should be used for the linkages when the new modules // are defined. ModuleIdentifier newRevisionId = JBossModuleUtils.createRevisionId(scriptModuleId, updateNumber); updatedRevisionIdMap.put(scriptModuleId, newRevisionId); archivesToCompile.put(scriptModuleId, scriptArchive); // create a dependency map of the incoming archives so that we can later build a candidate graph archiveDependencies.put(scriptModuleId, scriptArchive.getModuleSpec().getModuleDependencies()); } // create a dependency graph with the candidates swapped in in order to figure out the // order in which the candidates should be loaded DirectedGraph<ModuleId, DefaultEdge> candidateGraph = jbossModuleLoader.getModuleNameGraph(); GraphUtils.swapVertices(candidateGraph, archiveDependencies); // iterate over the graph in reverse dependency order Set<ModuleId> leaves = GraphUtils.getLeafVertices(candidateGraph); while (!leaves.isEmpty()) { for (ModuleId scriptModuleId : leaves) { ScriptArchive scriptArchive = archivesToCompile.get(scriptModuleId); if (scriptArchive == null) { continue; } ModuleSpec moduleSpec; ModuleIdentifier candidateRevisionId = updatedRevisionIdMap.get(scriptModuleId); Path modulePath = createModulePath(candidateRevisionId); final Path moduleCompilationRoot = compilationRootDir.resolve(modulePath); FileUtils.deleteQuietly(moduleCompilationRoot.toFile()); try { Files.createDirectories(moduleCompilationRoot); } catch (IOException ioe) { notifyArchiveRejected(scriptArchive, ArchiveRejectedReason.ARCHIVE_IO_EXCEPTION, ioe); } try { moduleSpec = createModuleSpec(scriptArchive, candidateRevisionId, updatedRevisionIdMap, moduleCompilationRoot); } catch (ModuleLoadException e) { logger.error("Exception loading archive " + scriptArchive.getModuleSpec().getModuleId(), e); notifyArchiveRejected(scriptArchive, ArchiveRejectedReason.ARCHIVE_IO_EXCEPTION, e); continue; } // load and compile the module jbossModuleLoader.addModuleSpec(moduleSpec); Module jbossModule = null; try { jbossModule = jbossModuleLoader.loadModule(candidateRevisionId); compileModule(jbossModule, moduleCompilationRoot); // Now refresh the resource loaders for this module, and load the set of // compiled classes and populate into the module's local class cache. jbossModuleLoader.rescanModule(jbossModule); final Set<String> classesToLoad = new LinkedHashSet<String>(); Files.walkFileTree(moduleCompilationRoot, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String relativePath = moduleCompilationRoot.relativize(file).toString(); if (relativePath.endsWith(".class")) { String className = relativePath.replaceAll(".class", "").replace("/", "."); classesToLoad.add(className); } return FileVisitResult.CONTINUE; }; }); for (String loadClass: classesToLoad) { Class<?> loadedClass = jbossModule.getClassLoader().loadClassLocal(loadClass, true); if (loadedClass == null) throw new ScriptCompilationException("Unable to load compiled class: " + loadClass); } } catch (Exception e) { // rollback logger.error("Exception loading module " + candidateRevisionId, e); if (candidateArchives.contains(scriptArchive)) { // this spec came from a candidate archive. Send reject notification notifyArchiveRejected(scriptArchive, ArchiveRejectedReason.COMPILE_FAILURE, e); } if (jbossModule != null) { jbossModuleLoader.unloadModule(jbossModule); } continue; } // commit the change by removing the old module ModuleIdentifier oldRevisionId = oldRevisionIdMap.get(scriptModuleId); if (oldRevisionId != null) { jbossModuleLoader.unloadModule(oldRevisionId); } JBossScriptModule scriptModule = new JBossScriptModule(scriptModuleId, jbossModule, scriptArchive); ScriptModule oldModule = loadedScriptModules.put(scriptModuleId, scriptModule); notifyModuleUpdate(scriptModule, oldModule); // find dependents and add them to the to be compiled set Set<ModuleId> dependents = GraphUtils.getIncomingVertices(candidateGraph, scriptModuleId); for (ModuleId dependentScriptModuleId : dependents) { if (!archivesToCompile.containsKey(dependentScriptModuleId)) { ScriptModule dependentScriptModule = loadedScriptModules.get(dependentScriptModuleId); if (dependentScriptModule != null) { archivesToCompile.put(dependentScriptModuleId, dependentScriptModule.getSourceArchive()); ModuleIdentifier dependentRevisionId = JBossModuleUtils.createRevisionId(dependentScriptModuleId, updateNumber); updatedRevisionIdMap.put(dependentScriptModuleId, dependentRevisionId); } } } } GraphUtils.removeVertices(candidateGraph, leaves); leaves = GraphUtils.getLeafVertices(candidateGraph); } } /** * Create a JBoss module spec for an about to be created script module. * @param archive the script archive being converted to a module. * @param moduleId the JBoss module identifier. * @param moduleIdMap a map of loaded script module IDs to jboss module identifiers * @param moduleCompilationRoot a path to a directory that will hold compiled classes for this module. * @throws ModuleLoadException */ protected ModuleSpec createModuleSpec(ScriptArchive archive, ModuleIdentifier moduleId, Map<ModuleId, ModuleIdentifier> moduleIdMap, Path moduleCompilationRoot) throws ModuleLoadException { ScriptModuleSpec archiveSpec = archive.getModuleSpec(); // create the jboss module pre-cursor artifact ModuleSpec.Builder moduleSpecBuilder = ModuleSpec.build(moduleId); JBossModuleUtils.populateModuleSpecWithResources(moduleSpecBuilder, archive); JBossModuleUtils.populateModuleSpecWithCoreDependencies(moduleSpecBuilder, archive); JBossModuleUtils.populateModuleSpecWithAppImports(moduleSpecBuilder, appClassLoader, archiveSpec.getAppImportFilterPaths() == null ? appPackagePaths : archiveSpec.getAppImportFilterPaths()); // Allow compiled class files to fetched as resources later on. JBossModuleUtils.populateModuleSpecWithCompilationRoot(moduleSpecBuilder, moduleCompilationRoot); // Populate the modulespec with the scriptArchive dependencies for (ModuleId dependencyModuleId : archiveSpec.getModuleDependencies()) { ScriptModule dependencyModule = getScriptModule(dependencyModuleId); Set<String> exportPaths = dependencyModule.getSourceArchive().getModuleSpec().getModuleExportFilterPaths(); JBossModuleUtils.populateModuleSpecWithModuleDependency(moduleSpecBuilder, archiveSpec.getModuleImportFilterPaths(), exportPaths, moduleIdMap.get(dependencyModuleId)); } return moduleSpecBuilder.create(); } /** * Compiles and links the scripts within the module by locating the correct compiler * and delegating the compilation. the classes will be loaded into the module's classloader * upon completion. * @param module module to be compiled * @param moduleCompilationRoot the directory to store compiled classes in. */ protected void compileModule(Module module, Path moduleCompilationRoot) throws ScriptCompilationException, IOException { // compile the script archive for the module, and inject the resultant classes into // the ModuleClassLoader ModuleClassLoader moduleClassLoader = module.getClassLoader(); if (moduleClassLoader instanceof JBossModuleClassLoader) { JBossModuleClassLoader jBossModuleClassLoader = (JBossModuleClassLoader)moduleClassLoader; ScriptArchive scriptArchive = jBossModuleClassLoader.getScriptArchive(); List<ScriptArchiveCompiler> candidateCompilers = findCompilers(scriptArchive); if (candidateCompilers.size() == 0) { throw new ScriptCompilationException("Could not find a suitable compiler for this archive."); } // Compile iteratively for (ScriptArchiveCompiler compiler: candidateCompilers) { compiler.compile(scriptArchive, jBossModuleClassLoader, moduleCompilationRoot); } } } /** * Add a language plugin to this module * @param pluginSpec * @throws ModuleLoadException */ public synchronized void addCompilerPlugin(ScriptCompilerPluginSpec pluginSpec) throws ModuleLoadException { Objects.requireNonNull(pluginSpec, "pluginSpec"); ModuleIdentifier pluginModuleId = JBossModuleUtils.getPluginModuleId(pluginSpec); ModuleSpec.Builder moduleSpecBuilder = ModuleSpec.build(pluginModuleId); Map<ModuleId, ModuleIdentifier> latestRevisionIds = jbossModuleLoader.getLatestRevisionIds(); JBossModuleUtils.populateCompilerModuleSpec(moduleSpecBuilder, pluginSpec, latestRevisionIds); // Add app package dependencies, while blocking them from leaking (being exported) to downstream modules // TODO: We expose the full set of app packages to the compiler too. // Maybe more control over what is exposed is needed here. JBossModuleUtils.populateModuleSpecWithAppImports(moduleSpecBuilder, appClassLoader, appPackagePaths); ModuleSpec moduleSpec = moduleSpecBuilder.create(); // spin up the module, and get the compiled classes from it's classloader String providerClassName = pluginSpec.getPluginClassName(); if (providerClassName != null) { jbossModuleLoader.addModuleSpec(moduleSpec); Module pluginModule = jbossModuleLoader.loadModule(pluginModuleId); ModuleClassLoader pluginClassLoader = pluginModule.getClassLoader(); Class<?> compilerProviderClass; try { compilerProviderClass = pluginClassLoader.loadClass(providerClassName); ScriptCompilerPlugin pluginBootstrap = (ScriptCompilerPlugin) compilerProviderClass.newInstance(); Set<? extends ScriptArchiveCompiler> pluginCompilers = pluginBootstrap.getCompilers(pluginSpec.getCompilerParams()); compilers.addAll(pluginCompilers); } catch (Exception e) { throw new ModuleLoadException(e); } // Save classloader away, in case clients would like access to compiler plugin's classes. compilerClassLoaders.put(pluginSpec.getPluginId(), pluginModule.getClassLoader()); } } /** * Remove a module from being served by this instance. Note that any * instances of the module cached outside of this module loader will remain * un-effected and will continue to operate. */ public synchronized void removeScriptModule(ModuleId scriptModuleId) { jbossModuleLoader.unloadAllModuleRevision(scriptModuleId.toString()); ScriptModule oldScriptModule = loadedScriptModules.remove(scriptModuleId); if (oldScriptModule != null) { notifyModuleUpdate(null, oldScriptModule); } } @Nullable public ScriptModule getScriptModule(String scriptModuleId) { return loadedScriptModules.get(ModuleId.fromString(scriptModuleId)); } @Nullable public ClassLoader getCompilerPluginClassLoader(String pluginModuleId) { return compilerClassLoaders.get(pluginModuleId); } @Nullable public ScriptModule getScriptModule(ModuleId scriptModuleId) { return loadedScriptModules.get(scriptModuleId); } /** * Get a view of the loaded script modules * @return immutable view of the Map that retains the script modules. Map ModuleId the loaded ScriptModule */ public Map<ModuleId, ScriptModule> getAllScriptModules() { return Collections.unmodifiableMap(loadedScriptModules); } /** * Add listeners to this module loader. Listeners will only be notified of events that occurred after they * were added. * @param listeners listeners to add */ public void addListeners(Set<ScriptModuleListener> listeners) { Objects.requireNonNull(listeners); this.listeners.addAll(listeners); } /** * Select a set of compilers to compile this archive. */ protected List<ScriptArchiveCompiler> findCompilers(ScriptArchive archive) { List<ScriptArchiveCompiler> candidateCompilers = new ArrayList<ScriptArchiveCompiler>(); for (ScriptArchiveCompiler compiler : compilers) { if (compiler.shouldCompile(archive)) { candidateCompilers.add(compiler); } } return candidateCompilers; } /** * Convenience method to notify the listeners that there was an update to the script module * @param newModule newly loaded module * @param oldModule module that was displaced by the new module */ protected void notifyModuleUpdate(@Nullable ScriptModule newModule, @Nullable ScriptModule oldModule) { for (ScriptModuleListener listener : listeners) { listener.moduleUpdated(newModule, oldModule); } } /** * Notify listeners that a script archive was rejected by this loader * @param scriptArchive archive that was rejected * @param reason reason it was rejected * @param cause underlying exception which triggered the rejection */ protected void notifyArchiveRejected(ScriptArchive scriptArchive, ArchiveRejectedReason reason, @Nullable Throwable cause) { for (ScriptModuleListener listener : listeners) { listener.archiveRejected(scriptArchive, reason, cause); } } }
1,867
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/BaseScriptModuleListener.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module; import javax.annotation.Nullable; import com.netflix.nicobar.core.archive.ScriptArchive; /** * Default implementation of the {@link ScriptModuleListener} * * @author James Kojo */ public class BaseScriptModuleListener implements ScriptModuleListener { @Override public void moduleUpdated(@Nullable ScriptModule newScriptModule, @Nullable ScriptModule oldScriptModule) { } @Override public void archiveRejected(ScriptArchive scriptArchive, ArchiveRejectedReason reason, @Nullable Throwable cause) { } }
1,868
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/ArchiveRejectedReason.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module; /** * Reason why an Archive was rejected loader * * @author James Kojo */ public enum ArchiveRejectedReason { HIGHER_REVISION_AVAILABLE, ARCHIVE_IO_EXCEPTION, COMPILE_FAILURE }
1,869
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/GraphUtils.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import org.jgrapht.DirectedGraph; import org.jgrapht.graph.DefaultEdge; /** * Utilities for managing graphs. Leverages the JGraphT library. * * @author James Kojo */ public class GraphUtils { /** * replace the vertices in the graph with an alternate set of vertices. * @param graph graph to be mutated * @param alternates alternate vertices to insert into the graph. map of vertices to their direct dependents. */ public static <V> void swapVertices(DirectedGraph<V, DefaultEdge> graph, Map<V, Set<V>> alternates) { Objects.requireNonNull(graph,"graph"); Objects.requireNonNull(alternates, "alternates"); // add all of the new vertices to prep for linking addAllVertices(graph, alternates.keySet()); for (Entry<V, Set<V>> entry : alternates.entrySet()) { V alternateVertex = entry.getKey(); Set<V> dependencies = entry.getValue(); // make sure we can satisfy all dependencies before continuing // TODO: this should probably done outside so it can be handled better. if (!graph.vertexSet().containsAll(dependencies)) { continue; } // figure out which vertices depend on the incumbent vertex Set<V> dependents = Collections.emptySet(); if (graph.containsVertex(alternateVertex)) { dependents = getIncomingVertices(graph, alternateVertex); graph.removeVertex(alternateVertex); } // (re)insert the vertex and re-link the dependents graph.addVertex(alternateVertex); addIncomingEdges(graph, alternateVertex, dependents); // create the dependencies addOutgoingEdges(graph, alternateVertex, dependencies); } } /** * Add all of the vertices to the graph without any edges. If the the graph * already contains any one of the vertices, that vertex is not added. * @param graph graph to be mutated * @param vertices vertices to add */ public static <V> void addAllVertices(DirectedGraph<V, DefaultEdge> graph, Set<V> vertices) { // add all of the new vertices to prep for linking for (V vertex : vertices) { graph.addVertex(vertex); } } /** * Add dependencies to the given source vertex. Whether duplicates are created is dependent * on the underlying {@link DirectedGraph} implementation. * @param graph graph to be mutated * @param source source vertex of the new edges * @param targets target vertices for the new edges */ public static <V> void addOutgoingEdges(DirectedGraph<V, DefaultEdge> graph, V source, Set<V> targets) { if (!graph.containsVertex(source)) { graph.addVertex(source); } for (V target : targets) { if (!graph.containsVertex(target)) { graph.addVertex(target); } graph.addEdge(source, target); } } /** * Add dependents on the give target vertex. Whether duplicates are created is dependent * on the underlying {@link DirectedGraph} implementation. * @param graph graph to be mutated * @param target target vertex for the new edges * @param sources source vertices for the new edges */ public static <N> void addIncomingEdges(DirectedGraph<N, DefaultEdge> graph, N target, Set<N> sources) { if (!graph.containsVertex(target)) { graph.addVertex(target); } for (N source : sources) { if (!graph.containsVertex(source)) { graph.addVertex(source); } graph.addEdge(source, target); } } /** * Fetch all of the dependents of the given target vertex * @return mutable snapshot of the source vertices of all incoming edges */ public static <V> Set<V> getIncomingVertices(DirectedGraph<V, DefaultEdge> graph, V target) { Set<DefaultEdge> edges = graph.incomingEdgesOf(target); Set<V> sources = new LinkedHashSet<V>(); for (DefaultEdge edge : edges) { sources.add(graph.getEdgeSource(edge)); } return sources; } /** * Fetch all of the dependencies of the given source vertex * @return mutable snapshot of the target vertices of all outgoing edges */ public static <V> Set<V> getOutgoingVertices(DirectedGraph<V, DefaultEdge> graph, V source) { Set<DefaultEdge> edges = graph.outgoingEdgesOf(source); Set<V> targets = new LinkedHashSet<V>(); for (DefaultEdge edge : edges) { targets.add(graph.getEdgeTarget(edge)); } return targets; } /** * Copy the source graph into the target graph */ public static <V> void copyGraph(DirectedGraph<V, DefaultEdge> sourceGraph, DirectedGraph<V, DefaultEdge> targetGraph) { addAllVertices(targetGraph, sourceGraph.vertexSet()); for (DefaultEdge edge : sourceGraph.edgeSet()) { targetGraph.addEdge(sourceGraph.getEdgeSource(edge), sourceGraph.getEdgeTarget(edge)); } } /** * Find the leave vertices in the graph. I.E. Vertices that have no outgoing edges * @param graph graph to search * @return mutable snapshot of all leaf vertices. */ public static <V> Set<V> getLeafVertices(DirectedGraph<V, DefaultEdge> graph) { Set<V> vertexSet = graph.vertexSet(); Set<V> leaves = new HashSet<V>(vertexSet.size()*2); for (V vertex : vertexSet) { if (graph.outgoingEdgesOf(vertex).isEmpty()) { leaves.add(vertex); } } return leaves; } /** * Removes vertices from graph * @param graph raph to mutate * @param vertices vertices to remove */ public static <V> void removeVertices(DirectedGraph<V, DefaultEdge> graph, Set<V> vertices) { for (V vertex : vertices) { if (graph.containsVertex(vertex)) { graph.removeVertex(vertex); } } } }
1,870
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/ScriptModule.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module; import java.util.Set; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; /** * Encapsulates a the compiled classes and the resources in a {@link ScriptArchive} * * @author James Kojo */ public interface ScriptModule { /** * @return module identifier */ public ModuleId getModuleId(); /** * @return the classes that were compiled and loaded from the scripts */ public Set<Class<?>> getLoadedClasses(); /** * Get the module classloader that is currently plugged into the graph * of classloaders per the module specificaiton. note that this classloader * was not necessarily the one used to load the classes in getLoadedClasses(), * since thos may have been injected. */ public JBossModuleClassLoader getModuleClassLoader(); /** * Timestamp used to resolve multiple revisions of a {@link ScriptModule}. This is usually * copied from the {@link ScriptArchive} which sourced this {@link ScriptModule} */ public long getCreateTime(); /** * @return the original archive this module was produced from */ ScriptArchive getSourceArchive(); }
1,871
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/ScriptModuleUtils.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import javax.annotation.Nullable; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import com.netflix.nicobar.core.archive.GsonScriptModuleSpecSerializer; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.archive.ScriptModuleSpecSerializer; import com.netflix.nicobar.core.plugin.BytecodeLoadingPlugin; import org.jboss.modules.ModuleIdentifier; /** * Utility classes for ScriptModule processing * * @author James Kojo * @author Vasanth Asokan */ public class ScriptModuleUtils { /** * Create module path from module moduleIdentifier. * @param moduleIdentifier module identifier to create path for * @return path to module for given moduleIdentifier */ public static Path createModulePath(ModuleIdentifier moduleIdentifier){ return Paths.get(moduleIdentifier.getName() + "-" + moduleIdentifier.getSlot()); } /** * Find all of the classes in the module that are subclasses or equal to the target class * @param module module to search * @param targetClass target type to search for * @return first instance that matches the given type */ public static Set<Class<?>> findAssignableClasses(ScriptModule module, Class<?> targetClass) { Set<Class<?>> result = new LinkedHashSet<Class<?>>(); for (Class<?> candidateClass : module.getLoadedClasses()) { if (targetClass.isAssignableFrom(candidateClass)) { result.add(candidateClass); } } return result; } /** * Find the first class in the module that is a subclasses or equal to the target class * @param module module to search * @param targetClass target type to search for * @return first instance that matches the given type */ @Nullable public static Class<?> findAssignableClass(ScriptModule module, Class<?> targetClass) { for (Class<?> candidateClass : module.getLoadedClasses()) { if (targetClass.isAssignableFrom(candidateClass)) { return candidateClass; } } return null; } /** * Find a class in the module that matches the given className * * @param module the script module to search * @param className the class name in dotted form. * @return the found class, or null. */ @Nullable public static Class<?> findClass(ScriptModule module, String className) { Set<Class<?>> classes = module.getLoadedClasses(); Class<?> targetClass = null; for (Class<?> clazz : classes) { if (clazz.getName().equals(className)) { targetClass = clazz; break; } } return targetClass; } /** * Convert a ScriptModule to its compiled equivalent ScriptArchive. * <p> * A jar script archive is created containing compiled bytecode * from a script module, as well as resources and other metadata from * the source script archive. * <p> * This involves serializing the class bytes of all the loaded classes in * the script module, as well as copying over all entries in the original * script archive, minus any that have excluded extensions. The module spec * of the source script archive is transferred as is to the target bytecode * archive. * * @param module the input script module containing loaded classes * @param jarPath the path to a destination JarScriptArchive. * @param excludeExtensions a set of extensions with which * source script archive entries can be excluded. * * @throws Exception */ public static void toCompiledScriptArchive(ScriptModule module, Path jarPath, Set<String> excludeExtensions) throws Exception { ScriptArchive sourceArchive = module.getSourceArchive(); JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jarPath.toFile())); try { // First copy all resources (excluding those with excluded extensions) // from the source script archive, into the target script archive for (String archiveEntry : sourceArchive.getArchiveEntryNames()) { URL entryUrl = sourceArchive.getEntry(archiveEntry); boolean skip = false; for (String extension: excludeExtensions) { if (entryUrl.toString().endsWith(extension)) { skip = true; break; } } if (skip) continue; InputStream entryStream = entryUrl.openStream(); byte[] entryBytes = IOUtils.toByteArray(entryStream); entryStream.close(); jarStream.putNextEntry(new ZipEntry(archiveEntry)); jarStream.write(entryBytes); jarStream.closeEntry(); } // Now copy all compiled / loaded classes from the script module. Set<Class<?>> loadedClasses = module.getModuleClassLoader().getLoadedClasses(); Iterator<Class<?>> iterator = loadedClasses.iterator(); while (iterator.hasNext()) { Class<?> clazz = iterator.next(); String classPath = clazz.getName().replace(".", "/") + ".class"; URL resourceURL = module.getModuleClassLoader().getResource(classPath); if (resourceURL == null) { throw new Exception("Unable to find class resource for: " + clazz.getName()); } InputStream resourceStream = resourceURL.openStream(); jarStream.putNextEntry(new ZipEntry(classPath)); byte[] classBytes = IOUtils.toByteArray(resourceStream); resourceStream.close(); jarStream.write(classBytes); jarStream.closeEntry(); } // Copy the source moduleSpec, but tweak it to specify the bytecode compiler in the // compiler plugin IDs list. ScriptModuleSpec moduleSpec = sourceArchive.getModuleSpec(); ScriptModuleSpec.Builder newModuleSpecBuilder = new ScriptModuleSpec.Builder(moduleSpec.getModuleId()); newModuleSpecBuilder.addCompilerPluginIds(moduleSpec.getCompilerPluginIds()); newModuleSpecBuilder.addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID); newModuleSpecBuilder.addMetadata(moduleSpec.getMetadata()); newModuleSpecBuilder.addModuleDependencies(moduleSpec.getModuleDependencies()); // Serialize the modulespec with GSON and its default spec file name ScriptModuleSpecSerializer specSerializer = new GsonScriptModuleSpecSerializer(); String json = specSerializer.serialize(newModuleSpecBuilder.build()); jarStream.putNextEntry(new ZipEntry(specSerializer.getModuleSpecFileName())); jarStream.write(json.getBytes(Charsets.UTF_8)); jarStream.closeEntry(); } finally { if (jarStream != null) { jarStream.close(); } } } }
1,872
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/ScriptModuleListener.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module; import javax.annotation.Nullable; import com.netflix.nicobar.core.archive.ScriptArchive; /** * Listener for new/updated or deleted modules. * * @author James Kojo */ public interface ScriptModuleListener { /** * Notification that a module was newly created or updated. * @param newScriptModule newly loaded version of the module. NULL if the module has been deleted. * @param oldScriptModule old version of the module that will be unloaded. NULL if this is a new module. */ void moduleUpdated(@Nullable ScriptModule newScriptModule, @Nullable ScriptModule oldScriptModule); /** * Notification that a script archive was rejected by the module loader * @param scriptArchive archive that was rejected * @param reason reason it was rejected * @param cause underlying exception which triggered the rejection */ void archiveRejected(ScriptArchive scriptArchive, ArchiveRejectedReason reason, @Nullable Throwable cause); }
1,873
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleClassLoader.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module.jboss; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.jboss.modules.ModuleClassLoader; import org.jboss.modules.ModuleClassLoaderFactory; import org.jboss.modules.ModuleSpec; import com.netflix.nicobar.core.archive.ScriptArchive; /** * base implementation of {@link ModuleClassLoader}s for this library * Holds a {@link ScriptArchive} and adds simple life-cycle hooks * adds a post-construction hook to inject classes into the classloader * @author James Kojo * @author Vasanth Asokan */ public class JBossModuleClassLoader extends ModuleClassLoader { private final ScriptArchive scriptArchive; private final Map<String, Class<?>> localClassCache; static { try { ClassLoader.registerAsParallelCapable(); } catch (Throwable ignored) { } } public JBossModuleClassLoader(Configuration moduleClassLoaderContext, ScriptArchive scriptArchive) { super(moduleClassLoaderContext); this.scriptArchive = scriptArchive; this.localClassCache = new ConcurrentHashMap<String, Class<?>>(scriptArchive.getArchiveEntryNames().size()); } /** * Creates a ModuleClassLoaderFactory that produces a {@link JBossModuleClassLoader}. * This method is necessary to inject our custom {@link ModuleClassLoader} into * the {@link ModuleSpec} */ protected static ModuleClassLoaderFactory createFactory(final ScriptArchive scriptArchive) { return new ModuleClassLoaderFactory() { public ModuleClassLoader create(final Configuration configuration) { return AccessController.doPrivileged( new PrivilegedAction<JBossModuleClassLoader>() { public JBossModuleClassLoader run() { return new JBossModuleClassLoader(configuration, scriptArchive); } }); } }; } /** * Manually add the compiled classes to this classloader. * This method will not redefine the class, so that the class's * classloader will continue to be compiler's classloader. */ public void addClasses(Set<Class<?>> classes) { for (Class<?> classToAdd: classes) { localClassCache.put(classToAdd.getName(), classToAdd); } } /** * Manually add the compiled classes to this classloader. This method will * define and resolve the class, binding this classloader to the class. * @return the loaded class */ public Class<?> addClassBytes(String name, byte[] classBytes) { Class<?> newClass = defineClass(name, classBytes, 0, classBytes.length); resolveClass(newClass); localClassCache.put(newClass.getName(), newClass); return newClass; } @Override public Class<?> loadClassLocal(String className, boolean resolve) throws ClassNotFoundException { Class<?> local = localClassCache.get(className); if (local != null) { return local; } local = super.loadClassLocal(className, resolve); if (local != null) localClassCache.put(className, local); return local; } public ScriptArchive getScriptArchive() { return scriptArchive; } public Set<Class<?>> getLoadedClasses() { return Collections.unmodifiableSet(new HashSet<Class<?>>(localClassCache.values())); } }
1,874
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossScriptModule.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module.jboss; import java.util.Objects; import java.util.Set; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.jboss.modules.Module; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.module.ScriptModule; /** * Encapsulates a the compiled classes and the resources in a {@link ScriptArchive} * * @author James Kojo */ public class JBossScriptModule implements ScriptModule { private final ModuleId moduleId; private final Module jbossModule; private final long createTime; private final ScriptArchive sourceArchive; public JBossScriptModule(ModuleId moduleId, Module jbossModule, ScriptArchive sourceArchive) { this.moduleId = Objects.requireNonNull(moduleId, "moduleId"); this.jbossModule = Objects.requireNonNull(jbossModule, "jbossModule"); this.createTime = sourceArchive.getCreateTime(); this.sourceArchive = Objects.requireNonNull(sourceArchive, "sourceArchive"); } /** * @return module identifier */ @Override public ModuleId getModuleId() { return moduleId; } /** * @return the classes that were compiled and loaded from the scripts */ @Override public Set<Class<?>> getLoadedClasses() { return getModuleClassLoader().getLoadedClasses(); } @Override public JBossModuleClassLoader getModuleClassLoader() { return (JBossModuleClassLoader)jbossModule.getClassLoader(); } @Override public long getCreateTime() { return createTime; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("moduleId", moduleId) .append("jbossModule", jbossModule) .append("createTime", createTime) .append("sourceArchive", sourceArchive) .toString(); } public ScriptArchive getSourceArchive() { return sourceArchive; } }
1,875
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleLoader.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module.jboss; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.SortedMap; import java.util.concurrent.ConcurrentSkipListMap; import javax.annotation.Nullable; import org.jboss.modules.ConcreteModuleSpec; import org.jboss.modules.DependencySpec; import org.jboss.modules.Module; import org.jboss.modules.ModuleDependencySpec; import org.jboss.modules.ModuleFinder; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.jboss.modules.ModuleSpec; import org.jgrapht.DirectedGraph; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleDirectedGraph; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.module.GraphUtils; /** * Specialization of the {@link ModuleLoader} class which exposes * many of the protected methods for convenience. * * The {@link ModuleSpec} repository is backed by a Map contained within * this class so that ModuleSpecs can be directly injected instead of * located via a {@link ModuleFinder}. * * This class exposes operations for different revisions of a given module * using the {@link ModuleIdentifier} "slot" as a revision holder. * * @author James Kojo * @author Vasanth Asokan */ public class JBossModuleLoader extends ModuleLoader { /** Comparator used for the module revision sorting */ protected final static Comparator<ModuleIdentifier> MODULE_ID_COMPARATOR = new Comparator<ModuleIdentifier>() { @Override public int compare(ModuleIdentifier id1, ModuleIdentifier id2) { if (id1 == null && id2 == null || id1 == id2) { return 0; } else if (id1 == null) { return -1; } else if (id2 == null) { return 1; } int result = id1.getName().compareTo(id2.getName()); if (result == 0) { // descending order result = (int)(Long.parseLong(id2.getSlot()) - Long.parseLong(id1.getSlot())); } return result; } }; /** Module Spec repo. Map of the revisionId to the Module specifications. */ protected final SortedMap<ModuleIdentifier, ModuleSpec> moduleSpecs; /** * Construct a instance with an empty module spec repository. */ public JBossModuleLoader() { this(new ConcurrentSkipListMap<ModuleIdentifier, ModuleSpec>(MODULE_ID_COMPARATOR)); } private JBossModuleLoader(final SortedMap<ModuleIdentifier, ModuleSpec> moduleSpecs) { // create a finder that is backed by the local module spec map super(new ModuleFinder[] { new ModuleFinder() { @Override public ModuleSpec findModule(ModuleIdentifier revisionId, ModuleLoader delegateLoader) throws ModuleLoadException { return moduleSpecs.get(revisionId); } }}); this.moduleSpecs = Objects.requireNonNull(moduleSpecs); } /** * Unload all module revisions with the give script module id */ public void unloadAllModuleRevision(String scriptModuleId) { for (ModuleIdentifier revisionId : getAllRevisionIds(scriptModuleId)) { if (revisionId.getName().equals(scriptModuleId)) { unloadModule(revisionId); } } } /** * Unload the given revision of a module from the local repository. * @param revisionId {@link ModuleIdentifier} of the revision to unload */ public void unloadModule(ModuleIdentifier revisionId) { Objects.requireNonNull(revisionId, "revisionId"); Module module = findLoadedModule(revisionId); if (module != null) { unloadModule(module); } } /** * Unload a module from the local repository. Equivalent to * {@link #unloadModuleLocal(Module)}. * @param module the module to unload. */ public void unloadModule(Module module) { Objects.requireNonNull(module, "module"); unloadModuleLocal(module); moduleSpecs.remove(module.getIdentifier()); } /** * Find a module from the local repository. Equivalent to {@link #findLoadedModuleLocal(ModuleIdentifier)}. * @param revisionId revisionId of the module to find * @return the loaded module or null if it doesn't exist */ @Nullable public Module findLoadedModule(ModuleIdentifier revisionId) { Objects.requireNonNull(revisionId, "revisionId"); return findLoadedModuleLocal(revisionId); } /** * Add a {@link ModuleSpec} to the internal repository making it ready to load. Note, this doesn't * actually load the {@link Module}. * @see #loadModule(ModuleIdentifier) * * @param moduleSpec spec to add * @return true if the instance was added */ @Nullable public boolean addModuleSpec(ModuleSpec moduleSpec) { Objects.requireNonNull(moduleSpec, "moduleSpec"); ModuleIdentifier revisionId = moduleSpec.getModuleIdentifier(); boolean available = !moduleSpecs.containsKey(revisionId); if (available) { moduleSpecs.put(revisionId, moduleSpec); } return available; } /** * Get a {@link ModuleSpec} that was added to this instance * @param revisionId id to search for * @return the instance associated with the given revisionIds */ @Nullable public ModuleSpec getModuleSpec(ModuleIdentifier revisionId) { Objects.requireNonNull(revisionId, "revisionId"); return moduleSpecs.get(revisionId); } /** * Find the highest revision for the given scriptModuleId * @param scriptModuleId name to search for * @return the highest revision number or -1 if no revisions exist */ public long getLatestRevisionNumber(ModuleId scriptModuleId) { Objects.requireNonNull(scriptModuleId, "scriptModuleId"); ModuleIdentifier searchIdentifier = JBossModuleUtils.createRevisionId(scriptModuleId, 0); SortedMap<ModuleIdentifier,ModuleSpec> tailMap = moduleSpecs.tailMap(searchIdentifier); long revisionNumber = -1; for (ModuleIdentifier revisionId : tailMap.keySet()) { if (revisionId.getName().equals(scriptModuleId.toString())) { revisionNumber = getRevisionNumber(revisionId); } else { break; } } return revisionNumber; } /** * Find the highest revision for the given scriptModuleId * @param scriptModuleId name to search for * @return the revisionId for the highest revision number. Revision defaults to 0 if it doesn't exist. */ public ModuleIdentifier getLatestRevisionId(ModuleId scriptModuleId) { Objects.requireNonNull(scriptModuleId, "scriptModuleId"); long latestRevision = getLatestRevisionNumber(scriptModuleId); if (latestRevision < 0) { latestRevision = 0; } return JBossModuleUtils.createRevisionId(scriptModuleId,latestRevision); } /** * Find all module revisionIds with a common name */ public Set<ModuleIdentifier> getAllRevisionIds(String scriptModuleId) { Objects.requireNonNull(scriptModuleId, "scriptModuleId"); Set<ModuleIdentifier> revisionIds = new LinkedHashSet<ModuleIdentifier>(); for (ModuleIdentifier revisionId : moduleSpecs.keySet()) { if (revisionId.getName().equals(scriptModuleId)) { revisionIds.add(revisionId); } } return Collections.unmodifiableSet(revisionIds); } /** * Get a map of the the moduleId to {@link ModuleIdentifier} with the highest revision * @return immutable snapshot of the latest module revisionIds */ public Map<ModuleId, ModuleIdentifier> getLatestRevisionIds() { Map<ModuleId, ModuleIdentifier> nameToIdMap = new HashMap<ModuleId, ModuleIdentifier>(moduleSpecs.size()*2); for (Entry<ModuleIdentifier, ModuleSpec> entry : moduleSpecs.entrySet()) { ModuleId scriptModuleId = ModuleId.fromString(entry.getKey().getName()); ModuleSpec moduleSpec = entry.getValue(); nameToIdMap.put(scriptModuleId, moduleSpec.getModuleIdentifier()); } // reserve the ability to convert this to an immutable view later return Collections.unmodifiableMap(nameToIdMap); } /** * Helper method to parse out the revision number from a {@link ModuleIdentifier} * @return revision number or -1 if it couldn't be parsed */ public static long getRevisionNumber(ModuleIdentifier revisionId) { int revision; try { revision = Integer.parseInt(revisionId.getSlot()); } catch (NumberFormatException nf) { revision = -1; } return revision; } /** * Construct the Module dependency graph of a module loader where each vertex is the module name * @return a mutable snapshot of the underlying dependency */ public DirectedGraph<ModuleId, DefaultEdge> getModuleNameGraph() { SimpleDirectedGraph<ModuleId, DefaultEdge> graph = new SimpleDirectedGraph<ModuleId, DefaultEdge>(DefaultEdge.class); Map<ModuleId, ModuleIdentifier> moduleIdentifiers = getLatestRevisionIds(); GraphUtils.addAllVertices(graph, moduleIdentifiers.keySet()); for (Entry<ModuleId, ModuleIdentifier> entry : moduleIdentifiers.entrySet()) { ModuleId scriptModuleId = entry.getKey(); ModuleIdentifier revisionID = entry.getValue(); ModuleSpec moduleSpec = moduleSpecs.get(revisionID); Set<ModuleId> dependencyNames = getDependencyScriptModuleIds(moduleSpec); GraphUtils.addOutgoingEdges(graph, scriptModuleId, dependencyNames); } return graph; } /** * Extract the Module dependencies for the given module in the form * of ScriptModule ids. */ public static Set<ModuleId> getDependencyScriptModuleIds(ModuleSpec moduleSpec) { Objects.requireNonNull(moduleSpec, "moduleSpec"); if (!(moduleSpec instanceof ConcreteModuleSpec)) { throw new IllegalArgumentException("Unsupported ModuleSpec implementation: " + moduleSpec.getClass().getName()); } Set<ModuleId> dependencyNames = new LinkedHashSet<ModuleId>(); ConcreteModuleSpec concreteSpec = (ConcreteModuleSpec)moduleSpec; for (DependencySpec dependencSpec : concreteSpec.getDependencies()) { if (dependencSpec instanceof ModuleDependencySpec) { ModuleIdentifier revisionId = ((ModuleDependencySpec)dependencSpec).getIdentifier(); dependencyNames.add(ModuleId.fromString(revisionId.getName())); } } return dependencyNames; } /** * Rescan a module. * * Post-compilation, this method triggers a module to pick up * resources created from compilation. * * @param module a loaded module. * @throws ModuleLoadException */ public void rescanModule(Module module) throws ModuleLoadException { super.refreshResourceLoaders(module); super.relink(module); } }
1,876
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleUtils.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.module.jboss; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.jar.JarFile; import javax.annotation.Nullable; import org.jboss.modules.DependencySpec; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleSpec; import org.jboss.modules.ResourceLoader; import org.jboss.modules.ResourceLoaderSpec; import org.jboss.modules.ResourceLoaders; import org.jboss.modules.filter.MultiplePathFilterBuilder; import org.jboss.modules.filter.PathFilter; import org.jboss.modules.filter.PathFilters; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec; import com.netflix.nicobar.core.utils.ClassPathUtils; /** * Utility methods for working with {@link Module}s * * @author James Kojo * @author Vasanth Asokan * @author Aaron Tull */ public class JBossModuleUtils { /** Dependency specification which allows for importing the core library classes */ public static final DependencySpec NICOBAR_CORE_DEPENDENCY_SPEC; /** Dependency specification which allows for importing the core JRE classes */ public static final DependencySpec JRE_DEPENDENCY_SPEC; static { // TODO: find a maintainable way to get these values and a better place to store these constants Set<String> pathFilter = new HashSet<String>(); pathFilter.add("com/netflix/nicobar/core"); pathFilter.add("com/netflix/nicobar/core/archive"); pathFilter.add("com/netflix/nicobar/core/compile"); pathFilter.add("com/netflix/nicobar/core/module"); pathFilter.add("com/netflix/nicobar/core/module/jboss"); pathFilter.add("com/netflix/nicobar/core/plugin"); NICOBAR_CORE_DEPENDENCY_SPEC = DependencySpec.createClassLoaderDependencySpec(JBossModuleUtils.class.getClassLoader(), pathFilter); ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); JRE_DEPENDENCY_SPEC = DependencySpec.createClassLoaderDependencySpec(systemClassLoader, ClassPathUtils.getJdkPaths()); } /** * Populates a module spec builder with source files, resources and properties from the {@link ScriptArchive} * * @param moduleSpecBuilder builder to populate * @param scriptArchive {@link ScriptArchive} to copy from */ public static void populateModuleSpecWithResources(ModuleSpec.Builder moduleSpecBuilder, ScriptArchive scriptArchive) throws ModuleLoadException { Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder"); Objects.requireNonNull(scriptArchive, "scriptArchive"); MultiplePathFilterBuilder pathFilterBuilder = PathFilters.multiplePathFilterBuilder(true); Set<String> archiveEntryNames = scriptArchive.getArchiveEntryNames(); pathFilterBuilder.addFilter(PathFilters.in(archiveEntryNames), true); // add the root resources and classes to the module. If the root is a directory, all files under the tree // are added to the module. If it's a jar, then all files in the jar are added. URL url = scriptArchive.getRootUrl(); if (url != null) { try { File file = Paths.get(url.toURI()).toFile(); String filePath = file.getPath(); ResourceLoader rootResourceLoader = null; if (file.isDirectory()) { rootResourceLoader = ResourceLoaders.createFileResourceLoader(filePath, file); } else if (file.getPath().endsWith(".jar")) { try { rootResourceLoader = ResourceLoaders.createJarResourceLoader(filePath, new JarFile(file)); } catch (IOException e) { throw new ModuleLoadException(e); } } if (rootResourceLoader != null) { moduleSpecBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(rootResourceLoader, pathFilterBuilder.create())); } } catch (URISyntaxException e) { throw new ModuleLoadException("Unsupported URL syntax: " + url, e); } } // add dependencies to the module spec ScriptModuleSpec scriptModuleSpec = scriptArchive.getModuleSpec(); // add string based properties from module spec metadata to the module spec being created Map<String, Object> archiveMetadata = scriptModuleSpec.getMetadata(); Map<String, String> stringMetadata = new HashMap<String, String>(); for (Entry<String, Object> entry: archiveMetadata.entrySet()) { if (entry.getValue() instanceof String) { stringMetadata.put(entry.getKey(), (String)entry.getValue()); } } addPropertiesToSpec(moduleSpecBuilder, stringMetadata); // override the default ModuleClassLoader to use our customer classloader moduleSpecBuilder.setModuleClassLoaderFactory(JBossModuleClassLoader.createFactory(scriptArchive)); } /** * Populates a module spec builder with core dependencies on JRE, Nicobar, itself, and compiler plugins. * * @param moduleSpecBuilder builder to populate * @param scriptArchive {@link ScriptArchive} to copy from */ public static void populateModuleSpecWithCoreDependencies(ModuleSpec.Builder moduleSpecBuilder, ScriptArchive scriptArchive) throws ModuleLoadException { Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder"); Objects.requireNonNull(scriptArchive, "scriptArchive"); Set<String> compilerPlugins = scriptArchive.getModuleSpec().getCompilerPluginIds(); for (String compilerPluginId : compilerPlugins) { moduleSpecBuilder.addDependency(DependencySpec.createModuleDependencySpec(getPluginModuleId(compilerPluginId), false)); } moduleSpecBuilder.addDependency(JRE_DEPENDENCY_SPEC); // TODO: Why does a module need a dependency on Nicobar itself? moduleSpecBuilder.addDependency(NICOBAR_CORE_DEPENDENCY_SPEC); moduleSpecBuilder.addDependency(DependencySpec.createLocalDependencySpec()); } /** * Populate a module spec builder with a dependencies on other modules. * @param moduleSpecBuilder builder to populate * @param moduleImportFilterPaths paths valid for importing into the module being built. * Can be null or empty to indicate that no filters should be applied. * @param dependencyExportFilterPaths export paths for the dependency being linked * @param dependentModuleIdentifier used to lookup the latest dependencies. see {@link JBossModuleLoader#getLatestRevisionIds()} */ public static void populateModuleSpecWithModuleDependency(ModuleSpec.Builder moduleSpecBuilder, @Nullable Set<String> moduleImportFilterPaths, @Nullable Set<String> dependencyExportFilterPaths, ModuleIdentifier dependentModuleIdentifier) { Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder"); PathFilter moduleImportFilters = buildFilters(moduleImportFilterPaths, false); PathFilter dependencyExportFilters = buildFilters(dependencyExportFilterPaths, false); PathFilter importFilters = PathFilters.all(dependencyExportFilters, moduleImportFilters); moduleSpecBuilder.addDependency(DependencySpec.createModuleDependencySpec(importFilters, dependencyExportFilters, null, dependentModuleIdentifier, false)); } /** * Populates a builder with a {@link ResourceLoaderSpec} to a filesystem resource root. * {@link ScriptArchive} * @param moduleSpecBuilder builder to populate * @param compilationRoot a path to the compilation resource root directory */ public static void populateModuleSpecWithCompilationRoot(ModuleSpec.Builder moduleSpecBuilder, Path compilationRoot) { Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder"); Objects.requireNonNull(compilationRoot, "resourceRoot"); ResourceLoader resourceLoader = ResourceLoaders.createFileResourceLoader(compilationRoot.toString(), compilationRoot.toFile()); moduleSpecBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader)); } /** * Populates a {@link ModuleSpec} with a dependency on application runtime packages * specified as a set of package paths, loaded within the given classloader. This is the * primary way that a module gains access to packages defined in the application classloader. * This dependency is NOT rexported to downstream modules. * * @param moduleSpecBuilder builder to populate * @param appClassLoader a classloader the application classloader. * @param appPackages the global set of application package paths. */ public static void populateModuleSpecWithAppImports(ModuleSpec.Builder moduleSpecBuilder, ClassLoader appClassLoader, Set<String> appPackages) { Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder"); Objects.requireNonNull(appClassLoader, "classLoader"); moduleSpecBuilder.addDependency(DependencySpec.createClassLoaderDependencySpec(appClassLoader, appPackages, false)); } /** * Populates a {@link ModuleSpec} with runtime resources, dependencies and properties from the * {@link ScriptCompilerPluginSpec} * Helpful when creating a {@link ModuleSpec} from a ScriptLibPluginSpec * * @param moduleSpecBuilder builder to populate * @param pluginSpec {@link ScriptCompilerPluginSpec} to copy from * @param latestRevisionIds used to lookup the latest dependencies. see {@link JBossModuleLoader#getLatestRevisionIds()} */ public static void populateCompilerModuleSpec(ModuleSpec.Builder moduleSpecBuilder, ScriptCompilerPluginSpec pluginSpec, Map<ModuleId, ModuleIdentifier> latestRevisionIds) throws ModuleLoadException { Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder"); Objects.requireNonNull(pluginSpec, "pluginSpec"); Objects.requireNonNull(latestRevisionIds, "latestRevisionIds"); Set<Path> pluginRuntime = pluginSpec.getRuntimeResources(); for (Path resourcePath : pluginRuntime) { File file = resourcePath.toFile(); String pathString = resourcePath.toString(); ResourceLoader rootResourceLoader = null; if (file.isDirectory()) { rootResourceLoader = ResourceLoaders.createFileResourceLoader(pathString, file); } else if (pathString.endsWith(".jar")) { try { rootResourceLoader = ResourceLoaders.createJarResourceLoader(pathString, new JarFile(file)); } catch (IOException e) { throw new ModuleLoadException(e); } } if (rootResourceLoader != null) { moduleSpecBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(rootResourceLoader)); } } moduleSpecBuilder.addDependency(JRE_DEPENDENCY_SPEC); moduleSpecBuilder.addDependency(NICOBAR_CORE_DEPENDENCY_SPEC); moduleSpecBuilder.addDependency(DependencySpec.createLocalDependencySpec()); // add dependencies to the module spec Set<ModuleId> dependencies = pluginSpec.getModuleDependencies(); for (ModuleId scriptModuleId : dependencies) { ModuleIdentifier latestIdentifier = latestRevisionIds.get(scriptModuleId); if (latestIdentifier == null) { throw new ModuleLoadException("Cannot find dependent module: " + scriptModuleId); } moduleSpecBuilder.addDependency(DependencySpec.createModuleDependencySpec(latestIdentifier, true, false)); } Map<String, String> pluginMetadata = pluginSpec.getPluginMetadata(); addPropertiesToSpec(moduleSpecBuilder, pluginMetadata); } /** * Add properties to the {@link ModuleSpec} * * @param moduleSpecBuilder builder to populate * @param properties properties to add */ public static void addPropertiesToSpec(ModuleSpec.Builder moduleSpecBuilder, Map<String, String> properties) { for (Entry<String, String> entry : properties.entrySet()) { moduleSpecBuilder.addProperty(entry.getKey(), entry.getValue()); } } /** * Create the {@link ModuleIdentifier} for the given ScriptCompilerPluginSpec */ public static ModuleIdentifier getPluginModuleId(ScriptCompilerPluginSpec pluginSpec) { return getPluginModuleId(pluginSpec.getPluginId()); } /** * Create the {@link ModuleIdentifier} for the given ScriptCompilerPluginSpec ID */ public static ModuleIdentifier getPluginModuleId(String pluginId) { return ModuleIdentifier.create(pluginId); } /** * Helper method to create a revisionId in a consistent manner */ public static ModuleIdentifier createRevisionId(ModuleId scriptModuleId, long revisionNumber) { Objects.requireNonNull(scriptModuleId, "scriptModuleId"); return ModuleIdentifier.create(scriptModuleId.toString(), Long.toString(revisionNumber)); } /** * Build a PathFilter for a set of filter paths * * @param filterPaths the set of paths to filter on. * Can be null to indicate that no filters should be applied (accept all), * can be empty to indicate that everything should be filtered (reject all). * @param failedMatchValue the value the PathFilter returns when a path does not match. * @return a PathFilter. */ private static PathFilter buildFilters(Set<String> filterPaths, boolean failedMatchValue) { if (filterPaths == null) return PathFilters.acceptAll(); else if (filterPaths.isEmpty()) { return PathFilters.rejectAll(); } else { MultiplePathFilterBuilder builder = PathFilters.multiplePathFilterBuilder(failedMatchValue); for (String importPathGlob : filterPaths) builder.addFilter(PathFilters.match(importPathGlob), !failedMatchValue); return builder.create(); } } }
1,877
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/ScriptCompilerPluginSpec.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.plugin; import com.google.common.base.Joiner; import com.netflix.nicobar.core.archive.ModuleId; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; import static java.nio.file.FileVisitOption.FOLLOW_LINKS; /** * <p>This library supports pluggable language compilers. Compiler plugins will be loaded * into a separate class loader to provider extra isolation in case there are multiple * versions of them in the JVM. * </p> * This class provides the metadata required to locate a compiler plugin and load it. * * @author James Kojo */ public class ScriptCompilerPluginSpec { /** * Used to construct a {@link ScriptCompilerPluginSpec} */ public static class Builder { private final String pluginId; private Set<Path> runtimeResources = new LinkedHashSet<Path>(); private String providerClassName; private Map<String, String> pluginMetadata = new LinkedHashMap<String, String>(); private Map<String, Object> compilerParams = new LinkedHashMap<String, Object>(); private final Set<ModuleId> moduleDependencies = new LinkedHashSet<ModuleId>(); /** * Start a builder with the required parameters * @param pluginId name of this plugin. Will be used to construct the Module. */ public Builder(String pluginId) { this.pluginId = pluginId; } /** * @param className of the plugin class which implements {@link ScriptCompilerPlugin} */ public Builder withPluginClassName(String className) { providerClassName = className; return this; } /** * @param resourcePath Paths to jars and resources needed to create the language deploy module. This * includes the language deploy as well as the jar/path to the provider class project. */ public Builder addRuntimeResource(Path resourcePath) { if (resourcePath != null) { runtimeResources.add(resourcePath); } return this; } /** * @param resourcePaths Paths to jars and resources needed to create the language deploy module. This * includes the language deploy as well as the jar/path to the provider class project. */ public Builder addRuntimeResources(Set<Path> resourcePaths) { if (resourcePaths != null) { for (Path path : resourcePaths) { runtimeResources.add(path); } } return this; } /** * @param resourceRootPath Path to the root of resource directory * @param fileExtensions null or empty means to find any files, file extensions are case sensitive * @param recursively find files recursively starting from the resourceRootPath * @throws IOException */ public Builder addRuntimeResources(Path resourceRootPath, Set<String> fileExtensions, boolean recursively) throws IOException { if (resourceRootPath != null) { final int maxDepth = recursively ? Integer.MAX_VALUE : 1; final boolean isFileExtensionEmpty = fileExtensions == null || fileExtensions.isEmpty(); final String extensions = !isFileExtensionEmpty ? Joiner.on(",").skipNulls().join(fileExtensions) : null; final PathMatcher pathMatcher = !isFileExtensionEmpty ? FileSystems.getDefault().getPathMatcher("glob:*.{" + extensions + "}") : null; Files.walkFileTree(resourceRootPath, EnumSet.of(FOLLOW_LINKS), maxDepth, new SimpleFileVisitor<Path>() { private void addPath(Path filePath) { Path name = filePath.getFileName(); if (name != null) { if (isFileExtensionEmpty) { runtimeResources.add(filePath); } else if (pathMatcher.matches(name)) { runtimeResources.add(filePath); } } } @Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException { this.addPath(filePath); return FileVisitResult.CONTINUE; } } ); } return this; } /** Append metadata */ public Builder addMetatdata(String name, String value) { if (name != null && value != null) { pluginMetadata.put(name, value); } return this; } /** Append all metadata */ public Builder addMetatdata(Map<String, String> metadata) { if (metadata != null) { pluginMetadata.putAll(metadata); } return this; } /** * Adds one compiler parameter. Compiler parameters can be used to pass any random object to a compiler. * Plugin implementation should be aware of how to process any particular parameter, otherwise it will be ignored. */ public Builder addCompilerParams(String name, Object value) { if (name != null && value != null) { compilerParams.put(name, value); } return this; } /** * Appends all compiler parameters. Compiler parameters can be used to pass any random object to a compiler. * Plugin implementation should be aware of how to process any particular parameter, otherwise it will be ignored. */ public Builder addCompilerParams(Map<String, Object> params) { if (params != null) { compilerParams.putAll(params); } return this; } /** Add Module dependency. */ public Builder addModuleDependency(String dependencyName) { if (dependencyName != null) { moduleDependencies.add(ModuleId.fromString(dependencyName)); } return this; } /** Add Module dependencies. */ public Builder addModuleDependencies(Set<String> dependencies) { if (dependencies != null) { for (String dependency : dependencies) { addModuleDependency(dependency); } } return this; } /** Build the instance. */ public ScriptCompilerPluginSpec build() { return new ScriptCompilerPluginSpec(pluginId, moduleDependencies, runtimeResources, providerClassName, pluginMetadata, compilerParams); } } private final String pluginId; private final Set<Path> runtimeResources; private final String pluginClassName; private final Map<String, String> pluginMetadata; private final Map<String, Object> compilerParameters; private final Set<ModuleId> moduleDependencies; /** * @param pluginId language plugin id. will be used to create a module identifier. * @param runtimeResources Paths to jars and resources needed to create the language runtime module. This * includes the language runtime as well as the jar/path to the provider class project. * @param pluginClassName fully qualified classname of the implementation of the {@link ScriptCompilerPlugin} class */ protected ScriptCompilerPluginSpec(String pluginId, Set<ModuleId> moduleDependencies, Set<Path> runtimeResources, String pluginClassName, Map<String, String> pluginMetadata, Map<String, Object> compilerParams) { this.pluginId = Objects.requireNonNull(pluginId, "pluginName"); this.moduleDependencies = Collections.unmodifiableSet(Objects.requireNonNull(moduleDependencies, "moduleDependencies")); this.runtimeResources = Collections.unmodifiableSet(Objects.requireNonNull(runtimeResources, "runtimeResources")); this.pluginClassName = pluginClassName; this.pluginMetadata = Collections.unmodifiableMap(Objects.requireNonNull(pluginMetadata, "pluginMetadata")); this.compilerParameters = compilerParams; } public String getPluginId() { return pluginId; } /** * Get the language deploy resources (jars or directories.) */ public Set<Path> getRuntimeResources() { return runtimeResources; } /** * @return the names of the modules that this compiler plugin depends on */ public Set<ModuleId> getModuleDependencies() { return moduleDependencies; } /** * @return application specific metadata */ public Map<String, String> getPluginMetadata() { return pluginMetadata; } /** * @return application specific compiler params */ public Map<String, Object> getCompilerParams() { return compilerParameters; } /** * @return fully qualified classname for instance of {@link ScriptCompilerPlugin} implementation for this plugin */ public String getPluginClassName() { return pluginClassName; } }
1,878
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/BytecodeLoadingPlugin.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.plugin; import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.internal.compile.BytecodeLoader; /** * A {@link ScriptCompilerPlugin} for script archives that include java bytecode. * * @author Vasanth Asokan */ public class BytecodeLoadingPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "bytecode"; @Override public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) { return Collections.singleton(new BytecodeLoader()); } }
1,879
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/ScriptCompilerPlugin.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.plugin; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; /** * Language plugin bootstrapper. Factory/provider interfaces for exporting classes needed for * loading a language plugin * * @author James Kojo */ public interface ScriptCompilerPlugin { public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams); }
1,880
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/TestCompilerPlugin.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.plugin; import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.internal.compile.NoOpCompiler; /** * A {@link ScriptCompilerPlugin} for script archives with a no-op compiler included. * Intended for use during testing. * * @author Vasanth Asokan */ public class TestCompilerPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "nolang"; @Override public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) { return Collections.singleton(new NoOpCompiler()); } }
1,881
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/internal
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/NoOpCompiler.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.internal.compile; import java.nio.file.Path; import java.util.Collections; import java.util.Set; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; /** * A {@link ScriptArchiveCompiler} that does nothing. Intended for use during testing. * * @author Vasanth Asokan */ public class NoOpCompiler implements ScriptArchiveCompiler { @Override public boolean shouldCompile(ScriptArchive archive) { return true; } @Override public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) { return Collections.<Class<?>>emptySet(); } }
1,882
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/internal
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/BytecodeLoader.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.internal.compile; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.Set; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.compile.ScriptCompilationException; import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; /** * A {@link ScriptArchiveCompiler} that loads java bytecode from .class files in a {@link ScriptArchive}. * * @author Vasanth Asokan */ public class BytecodeLoader implements ScriptArchiveCompiler { /** * Compile (load from) an archive, if it contains any .class files. */ @Override public boolean shouldCompile(ScriptArchive archive) { Set<String> entries = archive.getArchiveEntryNames(); boolean shouldCompile = false; for (String entry: entries) { if (entry.endsWith(".class")) { shouldCompile = true; } } return shouldCompile; } @Override public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException { HashSet<Class<?>> addedClasses = new HashSet<Class<?>>(archive.getArchiveEntryNames().size()); for (String entry : archive.getArchiveEntryNames()) { if (!entry.endsWith(".class")) { continue; } // Load from the underlying archive class resource String entryName = entry.replace(".class", "").replace("/", "."); try { Class<?> addedClass = moduleClassLoader.loadClassLocal(entryName, true); addedClasses.add(addedClass); } catch (Exception e) { throw new ScriptCompilationException("Unable to load class: " + entryName, e); } } moduleClassLoader.addClasses(addedClasses); return Collections.unmodifiableSet(addedClasses); } }
1,883
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/utils/__JDKPaths.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.netflix.nicobar.core.utils; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.IOUtils; /** * cloned from jboss-modules. This is required because there doesn't seem to be a good way to get the contents * of the bootstrap classloader without getting the full application classpath, which may contain dependencies that * we don't wish to expose. * TODO: ask for an enhancement so we don't close this. * * A utility class which maintains the set of JDK paths. Makes certain assumptions about the disposition of the * class loader used to load JBoss Modules; thus this class should only be used when booted up via the "-jar" or "-cp" * switches. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ final class __JDKPaths { static final Set<String> JDK; static { final Set<String> pathSet = new HashSet<String>(1024); final Set<String> jarSet = new HashSet<String>(1024); final String sunBootClassPath = System.getProperty("sun.boot.class.path"); processClassPathItem(sunBootClassPath, jarSet, pathSet); JDK = Collections.unmodifiableSet(pathSet); } private __JDKPaths() { } static void processClassPathItem(final String classPath, final Set<String> jarSet, final Set<String> pathSet) { if (classPath == null) return; int s = 0, e; do { e = classPath.indexOf(File.pathSeparatorChar, s); String item = e == -1 ? classPath.substring(s) : classPath.substring(s, e); if (jarSet != null && !jarSet.contains(item)) { final File file = new File(item); if (file.isDirectory()) { processDirectory0(pathSet, file); } else { try { processJar(pathSet, file); } catch (IOException ex) { // NOPMD } } } s = e + 1; } while (e != -1); } static void processJar(final Set<String> pathSet, final File file) throws IOException { final ZipFile zipFile = new ZipFile(file); try { final Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); final String name = entry.getName(); final int lastSlash = name.lastIndexOf('/'); if (lastSlash != -1) { pathSet.add(name.substring(0, lastSlash)); } } zipFile.close(); } finally { IOUtils.closeQuietly(zipFile); } } static void processDirectory0(final Set<String> pathSet, final File file) { for (File entry : file.listFiles()) { if (entry.isDirectory()) { processDirectory1(pathSet, entry, file.getPath()); } else { final String parent = entry.getParent(); if (parent != null) pathSet.add(parent); } } } static void processDirectory1(final Set<String> pathSet, final File file, final String pathBase) { for (File entry : file.listFiles()) { if (entry.isDirectory()) { processDirectory1(pathSet, entry, pathBase); } else { String packagePath = entry.getParent(); if (packagePath != null) { packagePath = packagePath.substring(pathBase.length()).replace('\\', '/'); if(packagePath.startsWith("/")) { packagePath = packagePath.substring(1); } pathSet.add(packagePath); } } } } }
1,884
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/utils/ClassPathUtils.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.utils; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Objects; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.annotation.Nullable; import org.apache.commons.io.IOUtils; /** * Utility methods for dealing with classes and resources in a {@link ClassLoader} * * @author James Kojo */ public class ClassPathUtils { /** * Get a list of JDK packages in the classpath, by scanning the bootstrap classpath. * @return a set of package path strings (package paths separated by '/' and not '.'). */ public static Set<String> getJdkPaths() { return __JDKPaths.JDK; } /** * Find the root path for the given resource. If the resource is found in a Jar file, then the * result will be an absolute path to the jar file. If the resource is found in a directory, * then the result will be the parent path of the given resource. * * For example, if the resourceName is given as "scripts/myscript.groovy", and the path to the file is * "/root/sub1/script/myscript.groovy", then this method will return "/root/sub1" * * @param resourceName relative path of the resource to search for. E.G. "scripts/myscript.groovy" * @param classLoader the {@link ClassLoader} to search * @return absolute path of the root of the resource. */ @Nullable public static Path findRootPathForResource(String resourceName, ClassLoader classLoader) { Objects.requireNonNull(resourceName, "resourceName"); Objects.requireNonNull(classLoader, "classLoader"); URL resource = classLoader.getResource(resourceName); if (resource != null) { String protocol = resource.getProtocol(); if (protocol.equals("jar")) { return getJarPathFromUrl(resource); } else if (protocol.equals("file")) { return getRootPathFromDirectory(resourceName, resource); } else { throw new IllegalStateException("Unsupported URL protocol: " + protocol); } } return null; } private static Path getRootPathFromDirectory(String resourceName, URL resource) { try { Path result = Paths.get(resource.toURI()); int relativePathSize = Paths.get(resourceName).getNameCount(); for (int i = 0; i < relativePathSize; i++) { result = result.getParent(); } return result; } catch (URISyntaxException e){ throw new IllegalStateException("Unsupported URL syntax: " + resource, e); } } /** * Find the root path for the given class. If the class is found in a Jar file, then the * result will be an absolute path to the jar file. If the resource is found in a directory, * then the result will be the parent path of the given resource. * * @param clazz class to search for * @return absolute path of the root of the resource. */ @Nullable public static Path findRootPathForClass(Class<?> clazz) { Objects.requireNonNull(clazz, "resourceName"); String resourceName = classToResourceName(clazz); return findRootPathForResource(resourceName, clazz.getClassLoader()); } /** * Find the jar containing the given resource. * * @param jarUrl URL that came from a jar that needs to be parsed * @return {@link Path} to the Jar containing the resource. */ public static Path getJarPathFromUrl(URL jarUrl) { try { String pathString = jarUrl.getPath(); // for Jar URL, the path is in the form of: file:/path/to/groovy/myJar.jar!/path/to/resource/myResource.txt int endIndex = pathString.lastIndexOf("!"); return Paths.get(new URI(pathString.substring(0, endIndex))); } catch (URISyntaxException e) { throw new IllegalStateException("Unsupported URL syntax: " + jarUrl.getPath(), e); } } /** * Get all of the directory paths in a zip/jar file * @param pathToJarFile location of the jarfile. can also be a zipfile * @return set of directory paths relative to the root of the jar */ public static Set<Path> getDirectoriesFromJar(Path pathToJarFile) throws IOException { Set<Path> result = new HashSet<Path>(); ZipFile jarfile = new ZipFile(pathToJarFile.toFile()); try { final Enumeration<? extends ZipEntry> entries = jarfile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { result.add(Paths.get(entry.getName())); } } jarfile.close(); } finally { IOUtils.closeQuietly(jarfile); } return result; } /** * Get the resource name for the class file for the given class * @param clazz the class to convert * @return resource name appropriate for using with {@link ClassLoader#getResource(String)} */ public static String classToResourceName(Class<?> clazz) { return classNameToResourceName(clazz.getName()); } /** * Get the resource name for the class file for the given class name * @param className fully qualified classname to convert * @return resource name appropriate for using with {@link ClassLoader#getResource(String)} */ public static String classNameToResourceName(String className) { // from URLClassLoader.findClass() return className.replace('.', '/').concat(".class"); } /** * Scan the classpath string provided, and collect a set of package paths found in jars and classes on the path. * * @param classPath the classpath string * @param excludeJarSet a set of jars to exclude from scanning * @return the results of the scan, as a set of package paths (separated by '/'). */ public static Set<String> scanClassPath(final String classPath, final Set<String> excludeJarSet) { final Set<String> pathSet = new HashSet<String>(); // Defer to JDKPaths to do the actual classpath scanning. __JDKPaths.processClassPathItem(classPath, excludeJarSet, pathSet); return pathSet; } /** * Scan the classpath string provided, and collect a set of package paths found in jars and classes on the path. * On the resulting path set, first exclude those that match any exclude prefixes, and then include * those that match a set of include prefixes. * * @param classPath the classpath string * @param excludeJarSet a set of jars to exclude from scanning * @param excludePrefixes a set of path prefixes that determine what is excluded * @param includePrefixes a set of path prefixes that determine what is included * @return the results of the scan, as a set of package paths (separated by '/'). */ public static Set<String> scanClassPath(final String classPath, final Set<String> excludeJarSet, final Set<String> excludePrefixes, final Set<String> includePrefixes) { final Set<String> pathSet = new HashSet<String>(); // Defer to JDKPaths to do the actual classpath scanning. __JDKPaths.processClassPathItem(classPath, excludeJarSet, pathSet); return filterPathSet(pathSet, excludePrefixes, includePrefixes); } /** * Scan the classpath string provided, and collect a set of package paths found in jars and classes on the path, * excluding any that match a set of exclude prefixes. * * @param classPath the classpath string * @param excludeJarSet a set of jars to exclude from scanning * @param excludePrefixes a set of path prefixes that determine what is excluded * @return the results of the scan, as a set of package paths (separated by '/'). */ public static Set<String> scanClassPathWithExcludes(final String classPath, final Set<String> excludeJarSet, final Set<String> excludePrefixes) { final Set<String> pathSet = new HashSet<String>(); // Defer to JDKPaths to do the actual classpath scanning. __JDKPaths.processClassPathItem(classPath, excludeJarSet, pathSet); return filterPathSet(pathSet, excludePrefixes, Collections.<String>emptySet()); } /** * Scan the classpath string provided, and collect a set of package paths found in jars and classes on the path, * including only those that match a set of include prefixes. * * @param classPath the classpath string * @param excludeJarSet a set of jars to exclude from scanning * @param includePrefixes a set of path prefixes that determine what is included * @return the results of the scan, as a set of package paths (separated by '/'). */ public static Set<String> scanClassPathWithIncludes(final String classPath, final Set<String> excludeJarSet, final Set<String> includePrefixes) { final Set<String> pathSet = new HashSet<String>(); // Defer to JDKPaths to do the actual classpath scanning. __JDKPaths.processClassPathItem(classPath, excludeJarSet, pathSet); return filterPathSet(pathSet, Collections.<String>emptySet(), includePrefixes); } private static Set<String> filterPathSet(Set<String> pathSet, Set<String> excludePrefixes, Set<String> includePrefixes) { Set<String> filteredSet = new HashSet<String>(pathSet); // Ideally, we would use a trie, but we are talking ~100s of paths and a few excludes and includes, // not to mention these are throw away scans and not reused typically. // First process the excludes for (String exclude: excludePrefixes) { Iterator<String> setIterator = filteredSet.iterator(); while(setIterator.hasNext()) { String path = setIterator.next(); if (path.startsWith(exclude)) setIterator.remove(); } } // An empty set of includes indicates include everything if (includePrefixes.size() == 0) { return filteredSet; } // Now, create a filtered set based on the includes Iterator<String> setIterator = filteredSet.iterator(); while(setIterator.hasNext()) { String path = setIterator.next(); boolean shouldInclude = false; for (String include: includePrefixes) { if (path.startsWith(include)) { shouldInclude = true; break; } } // Remove if none of the includes specify this package path if (!shouldInclude) { setIterator.remove(); } } return filteredSet; } }
1,885
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptCompilationException.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.compile; /** * Indicates that there was a problem in the compilation step. * * @author James Kojo * @author Vasanth Asokan */ public class ScriptCompilationException extends Exception { private static final long serialVersionUID = 1L; /** * Create a generic compilation exception. * @param message the actual message. */ public ScriptCompilationException(String message) { super(message); } /** * A compilation exception with a specific underlying exception * that is compiler specific. */ public ScriptCompilationException(String message, Throwable cause) { super(message, cause); } }
1,886
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.compile; import java.io.IOException; import java.nio.file.Path; import java.util.Set; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; /** * Converts a Script Archive into a Set of classes * * @author James Kojo */ public interface ScriptArchiveCompiler { /** * Whether or not this compiler should be used to compile the archive */ public boolean shouldCompile(ScriptArchive archive); /** * Compile the archive into a ScriptModule * @param archive archive to generate class files for * @param moduleClassLoader class loader which can be used to find all classes and resources for modules. * The resultant classes of the compile operation should be injected into the classloader * for which the given archive has a declared dependency on * @param targetDir a directory in which to store compiled classes, if any. * @return The set of classes that were compiled * @throws ScriptCompilationException if there was a compilation issue in the archive. * @throws IOException if there was a problem reading/writing the archive */ public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; }
1,887
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/execution/HystrixScriptModuleExecutor.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.execution; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.module.ScriptModule; import com.netflix.nicobar.core.module.ScriptModuleLoader; /** * Hystrix based executor for {@link ScriptModuleExecutable}s. * * See {@link ScriptModuleExecutionCommand}. * * @author James Kojo * @author Vasanth Asokan */ public class HystrixScriptModuleExecutor<V> { private final static Logger logger = LoggerFactory.getLogger(HystrixScriptModuleExecutor.class); /** * Statistics holder for a given module's executions. */ public static class ExecutionStatistics { private final AtomicLong executionCount = new AtomicLong(); private final AtomicLong lastExecutionTime = new AtomicLong(); public long getExecutionCount() { return executionCount.get(); } public long getLastExecutionTime() { return lastExecutionTime.get(); } } private final ConcurrentMap<ModuleId, ExecutionStatistics> statistics = new ConcurrentHashMap<ModuleId, ExecutionStatistics>(); private final String executorId; /** * Construct an instance of the executor. * @param executorId descriptive name for this executor which will be used for reporting purposes. */ public HystrixScriptModuleExecutor(String executorId) { this.executorId = Objects.requireNonNull(executorId, "executorId"); } /** * Execute a collection of ScriptModules identified by moduleId. * * @param moduleIds moduleIds for modules to execute * @param executable execution logic to be performed for each module. * @param moduleLoader loader which manages the modules. * @return list of the outputs from the executable. */ public List<V> executeModules(List<String> moduleIds, ScriptModuleExecutable<V> executable, ScriptModuleLoader moduleLoader) { Objects.requireNonNull(moduleIds, "moduleIds"); Objects.requireNonNull(executable, "executable"); Objects.requireNonNull(moduleLoader, "moduleLoader"); List<ScriptModule> modules = new ArrayList<ScriptModule>(moduleIds.size()); for (String moduleId : moduleIds) { ScriptModule module = moduleLoader.getScriptModule(ModuleId.create(moduleId)); if (module != null) { modules.add(module); } } return executeModules(modules, executable); } /** * Execute a collection of modules. * * @param modules modules to execute. * @param executable execution logic to be performed for each module. * @return list of the outputs from the executable. */ public List<V> executeModules(List<ScriptModule> modules, ScriptModuleExecutable<V> executable) { Objects.requireNonNull(modules, "modules"); Objects.requireNonNull(executable, "executable"); List<Future<V>> futureResults = new ArrayList<Future<V>>(modules.size()); for (ScriptModule module : modules) { Future<V> future = new ScriptModuleExecutionCommand<V>(executorId, executable, module).queue(); futureResults.add(future); ExecutionStatistics moduleStats = getOrCreateModuleStatistics(module.getModuleId()); moduleStats.executionCount.incrementAndGet(); moduleStats.lastExecutionTime.set(System.currentTimeMillis()); } List<V> results = new ArrayList<V>(modules.size()); for (int i = 0; i < futureResults.size(); i++) { Future<V> futureResult = futureResults.get(i); try { V result = futureResult.get(); results.add(result); } catch (Exception e) { // the exception is already logged by the hystrix command, so just add some additional context ScriptModule failedModule = modules.get(i); logger.error("moduleId {} with creationTime: {} failed execution. see hystrix command log for deatils.", failedModule.getModuleId(), failedModule.getCreateTime()); continue; } } return results; } /** * Get the statistics for the given moduleId */ @Nullable public ExecutionStatistics getModuleStatistics(ModuleId moduleId) { ExecutionStatistics moduleStats = statistics.get(moduleId); return moduleStats; } /** * Helper method to get or create a ExecutionStatistics instance * @param moduleId * @return new or existing module statistics */ protected ExecutionStatistics getOrCreateModuleStatistics(ModuleId moduleId) { ExecutionStatistics moduleStats = statistics.get(moduleId); if (moduleStats == null) { moduleStats = new ExecutionStatistics(); ExecutionStatistics existing = statistics.put(moduleId, moduleStats); if (existing != null) { moduleStats = existing; } } return moduleStats; } }
1,888
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/execution/ScriptModuleExecutable.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.execution; import com.netflix.nicobar.core.module.ScriptModule; /** * Interface for executing a ScriptModule. * * @author James Kojo * @param <V> the result type of method */ public interface ScriptModuleExecutable<V> { /** * Execute the given ScriptModule. * @param scriptModule the module to be executed provided by the executor * @return the output of the script module execution * @throws Exception on any failures */ V execute(ScriptModule scriptModule) throws Exception; }
1,889
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/execution/ScriptModuleExecutionCommand.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.execution; import java.util.Objects; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.nicobar.core.module.ScriptModule; /** * Hystrix protected command to execute {@link ScriptModuleExecutable}s. * This provide limited sandboxing to script execution in terms of running time. It also provides basic statistics * about script execution counts and latencies. * * @author James Kojo * @author Vasanth Asokan * @param <R> Type of return value from the command */ public class ScriptModuleExecutionCommand<R> extends HystrixCommand<R>{ private final ScriptModuleExecutable<R> executable; private final ScriptModule module; public ScriptModuleExecutionCommand(String moduleExecutorId, ScriptModuleExecutable<R> executable, ScriptModule module) { super(HystrixCommand.Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey(moduleExecutorId)) .andCommandKey(HystrixCommandKey.Factory.asKey(module.getModuleId().toString())) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withFallbackEnabled(false))); Objects.requireNonNull(moduleExecutorId, "moduleExecutorId"); this.executable = Objects.requireNonNull(executable, "executable"); this.module = Objects.requireNonNull(module, "module"); } @Override protected R run() throws Exception { return executable.execute(module); } }
1,890
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/persistence/JarArchiveRepository.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import org.apache.commons.io.IOUtils; import com.netflix.nicobar.core.archive.GsonScriptModuleSpecSerializer; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.archive.ScriptModuleSpecSerializer; /** * {@link ArchiveRepository} implementation which stores {@link ScriptArchive}s in individual * jar files in a single root directory * * @author James Kojo */ public class JarArchiveRepository implements ArchiveRepository { private static final ScriptModuleSpecSerializer DEFAULT_SERIALIZER = new GsonScriptModuleSpecSerializer(); public static class Builder { private final Path rootDir; private String repositoryId ; private ScriptModuleSpecSerializer moduleSpecSerializer = DEFAULT_SERIALIZER; private String respositoryDescription; public Builder(Path rootDir){ this.rootDir = rootDir; } public Builder setRepostoryId(String repositoryId) { this.repositoryId = repositoryId; return this; } public Builder setRepositoryDescription(String respositoryDescription) { this.respositoryDescription = respositoryDescription; return this; } public Builder setModuleSpecSerializer(ScriptModuleSpecSerializer moduleSpecSerializer) { this.moduleSpecSerializer = moduleSpecSerializer; return this; } public JarArchiveRepository build() { String buildRepositoryId = repositoryId; if (buildRepositoryId == null) { buildRepositoryId = rootDir.toString(); } String buildDescription = respositoryDescription; if (buildDescription == null) { buildDescription = JarArchiveRepository.class.getSimpleName() + ": " + rootDir.toString(); } return new JarArchiveRepository(rootDir, buildRepositoryId, buildDescription, moduleSpecSerializer); } } /** * Directory filter which finds readable jar files */ protected final static DirectoryStream.Filter<Path> JAR_FILE_FILTER = new DirectoryStream.Filter<Path>() { public boolean accept(Path path) throws IOException { return (Files.isRegularFile(path) && Files.isReadable(path)) && path.toString().endsWith(".jar"); } }; private final Path rootDir; private final String repositoryId ; private final ScriptModuleSpecSerializer moduleSpecSerializer; private final String repositoryDescription; private final RepositoryView defaultView = new DefaultView(); protected JarArchiveRepository(Path rootDir, String repositoryId, String repositoryDescription, ScriptModuleSpecSerializer moduleSpecSerializer) { this.rootDir = Objects.requireNonNull(rootDir, "rootDir"); this.repositoryId = Objects.requireNonNull(repositoryId, "repositoryId"); this.moduleSpecSerializer = Objects.requireNonNull(moduleSpecSerializer, "moduleSpecSerializer"); this.repositoryDescription = Objects.requireNonNull(repositoryDescription, "repositoryDescription"); } @Override public String getRepositoryId() { return repositoryId; } /** * The default view reports all archives inserted into this repository. * @return the default view into all archives. */ @Override public RepositoryView getDefaultView() { return defaultView; } /** * No named views supported by this repository! * Throws UnsupportedOperationException. */ @Override public RepositoryView getView(String view) { throw new UnsupportedOperationException(); } @Override public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException { Objects.requireNonNull(jarScriptArchive, "jarScriptArchive"); ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec(); ModuleId moduleId = moduleSpec.getModuleId(); Path moduleJarPath = getModuleJarPath(moduleId); Files.deleteIfExists(moduleJarPath); JarFile sourceJarFile; try { sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath()); } catch (URISyntaxException e) { throw new IOException(e); } JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile())); try { String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName(); Enumeration<JarEntry> sourceEntries = sourceJarFile.entries(); while (sourceEntries.hasMoreElements()) { JarEntry sourceEntry = sourceEntries.nextElement(); if (sourceEntry.getName().equals(moduleSpecFileName)) { // avoid double entry for module spec continue; } destJarFile.putNextEntry(sourceEntry); if (!sourceEntry.isDirectory()) { InputStream inputStream = sourceJarFile.getInputStream(sourceEntry); IOUtils.copy(inputStream, destJarFile); IOUtils.closeQuietly(inputStream); } destJarFile.closeEntry(); } // write the module spec String serialized = moduleSpecSerializer.serialize(moduleSpec); JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName()); destJarFile.putNextEntry(moduleSpecEntry); IOUtils.write(serialized, destJarFile); destJarFile.closeEntry(); } finally { IOUtils.closeQuietly(sourceJarFile); IOUtils.closeQuietly(destJarFile); } // update the timestamp on the jar file to indicate that the module has been updated Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime())); } /** * Unsupported. */ @Override public void insertArchive(JarScriptArchive jarScriptArchive, Map<String, Object> initialDeploySpecs) throws IOException { throw new UnsupportedOperationException("This repository does not support deployment specs."); } @Override public Set<ScriptArchive> getScriptArchives(Set<ModuleId> moduleIds) throws IOException { Set<ScriptArchive> scriptArchives = new LinkedHashSet<ScriptArchive>(); for (ModuleId moduleId : moduleIds) { Path moduleJar = getModuleJarPath(moduleId); if (Files.exists(moduleJar)) { JarScriptArchive scriptArchive = new JarScriptArchive.Builder(moduleJar).build(); scriptArchives.add(scriptArchive); } } return scriptArchives; } @Override public void deleteArchive(ModuleId moduleId) throws IOException { Path moduleJar = getModuleJarPath(moduleId); if (Files.exists(moduleJar)) { Files.delete(moduleJar); } } /** * Translated a module id to an absolute path of the module jar */ protected Path getModuleJarPath(ModuleId moduleId) { Path moduleJarPath = rootDir.resolve(moduleId + ".jar"); return moduleJarPath; } protected class DefaultView implements RepositoryView { @Override public String getName() { return "Default View"; } @Override public Map<ModuleId, Long> getArchiveUpdateTimes() throws IOException { Map<ModuleId, Long> updateTimes = new LinkedHashMap<ModuleId, Long>(); try (DirectoryStream<Path> archiveJars = Files.newDirectoryStream(rootDir, JAR_FILE_FILTER)) { for (Path archiveJar : archiveJars) { Path absoluteArchiveFile = rootDir.resolve(archiveJar); long lastUpdateTime = Files.getLastModifiedTime(absoluteArchiveFile).toMillis(); String moduleName = archiveJar.getFileName().toString(); if (moduleName.endsWith(".jar")) { moduleName = moduleName.substring(0, moduleName.lastIndexOf(".jar")); } ModuleId moduleId = ModuleId.fromString(moduleName); updateTimes.put(moduleId, lastUpdateTime); } } return updateTimes; } @Override public RepositorySummary getRepositorySummary() throws IOException { Map<ModuleId, Long> archiveUpdateTimes = getArchiveUpdateTimes(); long maxUpdateTime = 0; for (Long updateTime : archiveUpdateTimes.values()) { if (updateTime > maxUpdateTime) { maxUpdateTime = updateTime; } } return new RepositorySummary(getRepositoryId(), repositoryDescription, archiveUpdateTimes.size(), maxUpdateTime); } @Override public List<ArchiveSummary> getArchiveSummaries() throws IOException { List<ArchiveSummary> summaries = new LinkedList<ArchiveSummary>(); Set<ModuleId> moduleIds = getArchiveUpdateTimes().keySet(); Set<ScriptArchive> scriptArchives = getScriptArchives(moduleIds); for (ScriptArchive scriptArchive : scriptArchives) { ScriptModuleSpec moduleSpec = scriptArchive.getModuleSpec(); long lastUpdateTime = scriptArchive.getCreateTime(); summaries.add(new ArchiveSummary(moduleSpec.getModuleId(), moduleSpec, lastUpdateTime, null)); } return summaries; } } }
1,891
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/persistence/ArchiveRepository.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import java.io.IOException; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; /** * Interface to represent a persistence store for archives * * @author James Kojo * @author Vasanth Asokan */ public interface ArchiveRepository { /** * Get the ID of this repository * @return the id string. */ public String getRepositoryId(); /** * Get the default view into this repository. * @return the default repository view. */ public RepositoryView getDefaultView(); /** * Get a specific named view into this repository. * * @param view the name of the view. * @return a {@link RepositoryView} that matches the given name or null if * one wasn't found. * @throws UnsupportedOperationException * if this repository does not support named views. */ public RepositoryView getView(String view); /** * Insert a Jar into the repository * @param jarScriptArchive script archive which describes the jar and * the ModuleSpec which should be inserted */ public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException; /** * Insert a Jar into the repository * @param jarScriptArchive script archive which describes the jar and * the ModuleSpec which should be inserted * @param initialDeploySpecs a set of initial deployment specs. * @throws UnsupportedOperationException if this repository does not support * adding deploy specs to a module. */ public void insertArchive(JarScriptArchive jarScriptArchive, Map <String, Object> initialDeploySpecs) throws IOException; /** * Get all of the {@link ScriptArchive}s for the given set of moduleIds. * * @param moduleIds keys to search for * @return set of ScriptArchives retrieved from the database */ public Set<ScriptArchive> getScriptArchives(Set<ModuleId> moduleIds) throws IOException; /** * Delete an archive by ID * @param moduleId module id to delete * @throws IOException */ public void deleteArchive(ModuleId moduleId) throws IOException; }
1,892
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/persistence/RepositoryView.java
/* * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.core.persistence; import java.io.IOException; import java.util.List; import java.util.Map; import com.netflix.nicobar.core.archive.ModuleId; /** * A repository view provides a window into querying the archives held by * an {@link ArchiveRepository}. Windowed views allow querying repositories * only for subsets of archives matching the windowing parameters. Archive * repositories must provide atleast one default view, and optionally provide * other named views. * @author Vasanth Asokan */ public interface RepositoryView { /** * Get the name of this view. * @return the name. */ public String getName(); /** * Get the last update times of all of the script archives under this * repository view. * * @return map of moduleId to last update time */ public Map<ModuleId, Long> getArchiveUpdateTimes() throws IOException; /** * Get a summary of the archives in this repository view. * * @return displayable summary of the contents */ public RepositorySummary getRepositorySummary() throws IOException; /** * Get a summary of all archives in this repository view * * @return List of summaries */ public List<ArchiveSummary> getArchiveSummaries() throws IOException; }
1,893
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/persistence/RepositorySummary.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; /** * Data object which holds summary information for a given {@link ArchiveRepository}. * Used for display and reporting purposes. * * @author James Kojo */ public class RepositorySummary { private final String repositoryId; private final String description; private final int archiveCount; private final long lastUpdated; public RepositorySummary(String repositoryId, String description, int archiveCount, long lastUpdated) { this.repositoryId = repositoryId; this.description = description; this.archiveCount = archiveCount; this.lastUpdated = lastUpdated; } public String getRepositoryId() { return repositoryId; } public String getDescription() { return description; } public int getArchiveCount() { return archiveCount; } public long getLastUpdated() { return lastUpdated; } }
1,894
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/persistence/ArchiveRepositoryPoller.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.module.ScriptModuleLoader; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Poller which periodically scans a list of {@link ArchiveRepository} for updates and publishes * them to a {@link ScriptModuleLoader} * * @author James Kojo * @author Vasanth Asokan */ public class ArchiveRepositoryPoller { public static class Builder { protected final ScriptModuleLoader moduleLoader; protected ScheduledExecutorService pollerThreadPool; public Builder(ScriptModuleLoader moduleLoader) { this.moduleLoader = moduleLoader; } /** Override the default scheduler */ public Builder setThreadPool(ScheduledExecutorService pollerThreadPool) { this.pollerThreadPool = pollerThreadPool; return this; } public ArchiveRepositoryPoller build() { ScheduledExecutorService buildPollerThreadPool = pollerThreadPool; if (buildPollerThreadPool == null ) { buildPollerThreadPool = Executors.newSingleThreadScheduledExecutor(DEFAULT_POLLER_THREAD_FACTORY); } return new ArchiveRepositoryPoller(buildPollerThreadPool, moduleLoader); } } private final static Logger logger = LoggerFactory.getLogger(ArchiveRepositoryPoller.class); /** Thread factory used for the default poller thread pool */ private final static ThreadFactory DEFAULT_POLLER_THREAD_FACTORY = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, ArchiveRepositoryPoller.class.getSimpleName() + "-" + "PollerThread"); thread.setDaemon(true); return thread; } }; /** used for book-keeping of repositories that are being polled */ protected static class RepositoryPollerContext { /** Map of moduleId to last known update time of the archive */ protected final Map<ModuleId, Long> lastUpdateTimes = new HashMap<ModuleId, Long>(); @SuppressFBWarnings(value="URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD", justification="will use later") protected volatile ScheduledFuture<?> future; protected RepositoryPollerContext() { } } /** Contains transient state required for calculating deltas */ protected final ConcurrentHashMap<ArchiveRepository, RepositoryPollerContext> repositoryContexts = new ConcurrentHashMap<ArchiveRepository, RepositoryPollerContext>(); /** Thread pool used by the pollers */ protected final ScheduledExecutorService pollerThreadPool; protected final ScriptModuleLoader moduleLoader; protected ArchiveRepositoryPoller(ScheduledExecutorService pollerThreadPool, ScriptModuleLoader moduleLoader) { this.pollerThreadPool = Objects.requireNonNull(pollerThreadPool, "pollerThreadPool"); this.moduleLoader = Objects.requireNonNull(moduleLoader, "moduleLoader"); } /** * Add a repository and schedule polling * @param archiveRepository repository to scan * @param pollInterval how often this repository should be scanned * @param timeUnit unit of the pollInterval param * @param waitForInitialPoll whether or not to block until the initial poll is complete * @return true if the repository was added. false if it already exists */ public boolean addRepository(final ArchiveRepository archiveRepository, final int pollInterval, TimeUnit timeUnit, boolean waitForInitialPoll) { if (pollInterval <= 0) { throw new IllegalArgumentException("invalid pollInterval " + pollInterval); } Objects.requireNonNull(timeUnit, "timeUnit"); RepositoryPollerContext pollerContext = new RepositoryPollerContext(); RepositoryPollerContext oldContext = repositoryContexts.putIfAbsent(archiveRepository, pollerContext); if (oldContext != null) { return false; } final CountDownLatch initialPollLatch = new CountDownLatch(1); ScheduledFuture<?> future = pollerThreadPool.scheduleWithFixedDelay(new Runnable() { public void run() { try { pollRepository(archiveRepository); initialPollLatch.countDown(); } catch (Throwable t) { // should never happen logger.error("Excecution exception on poll" , t); } } }, 0, pollInterval, timeUnit); pollerContext.future = future; if (waitForInitialPoll) { try { initialPollLatch.await(); } catch (Exception e) { // should never happen logger.error("Excecution exception on poll" , e); } } return true; } protected void pollRepository(ArchiveRepository archiveRepository) { RepositoryPollerContext context = repositoryContexts.get(archiveRepository); Map<ModuleId, Long> repoUpdateTimes; try { repoUpdateTimes = archiveRepository.getDefaultView().getArchiveUpdateTimes(); } catch (IOException e) { logger.error("Exception while fetching update times for repository " + archiveRepository.getRepositoryId(), e); return; } // search for new/updated archives by comparing update times reported by the repo // to the local repository context. Set<ModuleId> updatedModuleIds = new HashSet<ModuleId>(repoUpdateTimes.size()); for (Entry<ModuleId, Long> entry : repoUpdateTimes.entrySet()) { ModuleId moduleId = entry.getKey(); Long queryUpdateTime = entry.getValue(); Long lastUpdateTime = context.lastUpdateTimes.get(moduleId); if (lastUpdateTime == null || lastUpdateTime < queryUpdateTime) { // this is a new archive or a new revision of an existing archive. lastUpdateTime = queryUpdateTime; context.lastUpdateTimes.put(moduleId, lastUpdateTime); updatedModuleIds.add(moduleId); } } // find deleted modules by taking the set difference of moduleIds in the repository // and module ids in the repository context Set<ModuleId> deletedModuleIds = new HashSet<ModuleId>(context.lastUpdateTimes.keySet()); deletedModuleIds.removeAll(repoUpdateTimes.keySet()); context.lastUpdateTimes.keySet().removeAll(deletedModuleIds); // lookup updated archives and update archive times if (!updatedModuleIds.isEmpty()) { Set<ScriptArchive> scriptArchives; try { scriptArchives = archiveRepository.getScriptArchives(updatedModuleIds); moduleLoader.updateScriptArchives(scriptArchives); } catch (Exception e) { logger.error("Exception when attempting to Fetch archives for moduleIds: " + updatedModuleIds, e); } } if (!deletedModuleIds.isEmpty()) { for (ModuleId scriptModuleId : deletedModuleIds) { moduleLoader.removeScriptModule(scriptModuleId); } } } public void shutdown() { pollerThreadPool.shutdown(); } }
1,895
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/persistence/PathArchiveRepository.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.io.Charsets; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import com.netflix.nicobar.core.archive.GsonScriptModuleSpecSerializer; import com.netflix.nicobar.core.archive.JarScriptArchive; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.PathScriptArchive; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.archive.ScriptModuleSpec; import com.netflix.nicobar.core.archive.ScriptModuleSpecSerializer; /** * {@link ArchiveRepository} implementation which stores {@link ScriptArchive}s in * sub-directories a root directory. * * @author James Kojo */ public class PathArchiveRepository implements ArchiveRepository { private static final ScriptModuleSpecSerializer DEFAULT_SERIALIZER = new GsonScriptModuleSpecSerializer(); public static class Builder { private final Path rootDir; private String repositoryId ; private ScriptModuleSpecSerializer moduleSpecSerializer = DEFAULT_SERIALIZER; private String respositoryDescription; public Builder(Path rootDir){ this.rootDir = rootDir; } public Builder setRepostoryId(String repositoryId) { this.repositoryId = repositoryId; return this; } public Builder setRepositoryDescription(String respositoryDescription) { this.respositoryDescription = respositoryDescription; return this; } public Builder setModuleSpecSerializer(ScriptModuleSpecSerializer moduleSpecSerializer) { this.moduleSpecSerializer = moduleSpecSerializer; return this; } public PathArchiveRepository build() { String buildRepositoryId = repositoryId; if (buildRepositoryId == null) { buildRepositoryId = rootDir.toString(); } String buildDescription = respositoryDescription; if (buildDescription == null) { buildDescription = PathArchiveRepository.class.getSimpleName() + ": " + rootDir.toString(); } return new PathArchiveRepository(rootDir, buildRepositoryId, buildDescription, moduleSpecSerializer); } } /** * Directory filter which finds readable directories */ protected final static DirectoryStream.Filter<Path> DIRECTORY_FILTER = new DirectoryStream.Filter<Path>() { public boolean accept(Path path) throws IOException { return (Files.isDirectory(path) && Files.isReadable(path)); } }; private final Path rootDir; private final String repositoryId ; private final ScriptModuleSpecSerializer moduleSpecSerializer; private final String repositoryDescription; private final RepositoryView defaultView = new DefaultView(); protected PathArchiveRepository(Path rootDir, String repositoryId, String repositoryDescription, ScriptModuleSpecSerializer moduleSpecSerializer) { this.rootDir = Objects.requireNonNull(rootDir, "rootDir"); this.repositoryId = Objects.requireNonNull(repositoryId, "repositoryId"); this.moduleSpecSerializer = Objects.requireNonNull(moduleSpecSerializer, "moduleSpecSerializer"); this.repositoryDescription = Objects.requireNonNull(repositoryDescription, "repositoryDescription"); } @Override public String getRepositoryId() { return repositoryId; } /** * The default view reports all archives inserted into this repository. * @return the default view into all archives. */ @Override public RepositoryView getDefaultView() { return defaultView; } /** * No named views supported by this repository! * Throws UnsupportedOperationException. */ @Override public RepositoryView getView(String view) { throw new UnsupportedOperationException(); } @Override public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException { Objects.requireNonNull(jarScriptArchive, "jarScriptArchive"); ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec(); ModuleId moduleId = moduleSpec.getModuleId(); Path moduleDir = rootDir.resolve(moduleId.toString()); if (Files.exists(moduleDir)) { FileUtils.deleteDirectory(moduleDir.toFile()); } JarFile jarFile; try { jarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath()); } catch (URISyntaxException e) { throw new IOException(e); } try { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); Path entryName = moduleDir.resolve(jarEntry.getName()); if (jarEntry.isDirectory()) { Files.createDirectories(entryName); } else { InputStream inputStream = jarFile.getInputStream(jarEntry); try { Files.copy(inputStream, entryName); } finally { IOUtils.closeQuietly(inputStream); } } } } finally { IOUtils.closeQuietly(jarFile); } // write the module spec String serialized = moduleSpecSerializer.serialize(moduleSpec); Files.write(moduleDir.resolve(moduleSpecSerializer.getModuleSpecFileName()), serialized.getBytes(Charsets.UTF_8)); // update the timestamp on the module directory to indicate that the module has been updated Files.setLastModifiedTime(moduleDir, FileTime.fromMillis(jarScriptArchive.getCreateTime())); } /** * Unsupported. */ @Override public void insertArchive(JarScriptArchive jarScriptArchive, Map<String, Object> initialDeploySpecs) throws IOException { throw new UnsupportedOperationException("This repository does not support deployment specs."); } @Override public Set<ScriptArchive> getScriptArchives(Set<ModuleId> moduleIds) throws IOException { Set<ScriptArchive> scriptArchives = new LinkedHashSet<ScriptArchive>(); for (ModuleId moduleId : moduleIds) { Path moduleDir = rootDir.resolve(moduleId.toString()); if (Files.exists(moduleDir)) { PathScriptArchive scriptArchive = new PathScriptArchive.Builder(moduleDir).build(); scriptArchives.add(scriptArchive); } } return scriptArchives; } @Override public void deleteArchive(ModuleId moduleId) throws IOException { Path moduleDir = rootDir.resolve(moduleId.toString()); if (Files.exists(moduleDir)) { FileUtils.deleteDirectory(moduleDir.toFile()); } } protected class DefaultView implements RepositoryView { @Override public String getName() { return "Default View"; } @Override public Map<ModuleId, Long> getArchiveUpdateTimes() throws IOException { Map<ModuleId, Long> updateTimes = new LinkedHashMap<ModuleId, Long>(); DirectoryStream<Path> archiveDirs = Files.newDirectoryStream(rootDir, DIRECTORY_FILTER); for (Path archiveDir: archiveDirs) { Path absoluteArchiveDir = rootDir.resolve(archiveDir); long lastUpdateTime = Files.getLastModifiedTime(absoluteArchiveDir).toMillis(); ModuleId moduleId = ModuleId.fromString(archiveDir.getFileName().toString()); updateTimes.put(moduleId, lastUpdateTime); } return updateTimes; } @Override public RepositorySummary getRepositorySummary() throws IOException { Map<ModuleId, Long> archiveUpdateTimes = getArchiveUpdateTimes(); long maxUpdateTime = 0; for (Long updateTime : archiveUpdateTimes.values()) { if (updateTime > maxUpdateTime) { maxUpdateTime = updateTime; } } return new RepositorySummary(getRepositoryId(), repositoryDescription, archiveUpdateTimes.size(), maxUpdateTime); } @Override public List<ArchiveSummary> getArchiveSummaries() throws IOException { List<ArchiveSummary> summaries = new LinkedList<ArchiveSummary>(); Set<ModuleId> moduleIds = getArchiveUpdateTimes().keySet(); Set<ScriptArchive> scriptArchives = getScriptArchives(moduleIds); for (ScriptArchive scriptArchive : scriptArchives) { ScriptModuleSpec moduleSpec = scriptArchive.getModuleSpec(); long lastUpdateTime = scriptArchive.getCreateTime(); summaries.add(new ArchiveSummary(moduleSpec.getModuleId(), moduleSpec, lastUpdateTime, null)); } return summaries; } } }
1,896
0
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core
Create_ds/Nicobar/nicobar-core/src/main/java/com/netflix/nicobar/core/persistence/ArchiveSummary.java
/* * * Copyright 2013 Netflix, Inc. * * 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. * */ package com.netflix.nicobar.core.persistence; import java.util.Map; import java.util.Objects; import javax.annotation.Nullable; import com.netflix.nicobar.core.archive.ModuleId; import com.netflix.nicobar.core.archive.ScriptModuleSpec; /** * Data object for a summary of an individual script archive. useful for displaying a list view * of archives. * * @author James Kojo * @author Vasanth Asokan */ public class ArchiveSummary { private final ModuleId moduleId; private final ScriptModuleSpec moduleSpec; private final long lastUpdateTime; private final Map<String, Object> deploySpecs; public ArchiveSummary(ModuleId moduleId, ScriptModuleSpec moduleSpec, long lastUpdateTime, @Nullable Map<String, Object> deploySpecs) { this.moduleId = Objects.requireNonNull(moduleId, "moduleId"); this.moduleSpec = moduleSpec; this.lastUpdateTime = lastUpdateTime; this.deploySpecs = deploySpecs; } public ModuleId getModuleId() { return moduleId; } public ScriptModuleSpec getModuleSpec() { return moduleSpec; } public long getLastUpdateTime() { return lastUpdateTime; } /** * Deployment specs for this archive. This depends on the underlying * archive repository's support for deploy specs, and thus could be null. * @return concrete set of deployment specs, or null */ public Map<String, Object> getDeploySpecs() { return deploySpecs; } }
1,897
0
Create_ds/Nicobar/nicobar-manager/src/test/java/com/netflix/nicobar/manager
Create_ds/Nicobar/nicobar-manager/src/test/java/com/netflix/nicobar/manager/explorer/ExplorerAppTest.java
/** * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.manager.explorer; import static org.testng.Assert.assertEquals; import java.io.IOException; import java.net.ServerSocket; import java.util.Map; import javax.ws.rs.core.MediaType; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; import com.google.inject.servlet.GuiceFilter; import com.netflix.karyon.server.guice.KaryonGuiceContextListener; public class ExplorerAppTest { private static final Logger LOG = LoggerFactory.getLogger(ExplorerAppTest.class); private static final Map<String, String> REST_END_POINTS = new ImmutableMap.Builder<String, String>() .put("/", MediaType.TEXT_HTML) .put("/scriptmanager", MediaType.TEXT_HTML) .put("/scriptmanager/repositorysummaries", MediaType.APPLICATION_JSON) .build(); private static int TEST_LOCAL_PORT; static { try { TEST_LOCAL_PORT = getLocalPort(); } catch (IOException e) { LOG.error("IOException in finding local port for starting jetty ", e); } } private static int getLocalPort() throws IOException { ServerSocket ss = new ServerSocket(0); ss.setReuseAddress(true); return ss.getLocalPort(); } private Server server; @BeforeClass public void init() throws Exception { System.setProperty("archaius.deployment.applicationId","scriptmanager-app"); System.setProperty("archaius.deployment.environment","dev"); server = new Server(TEST_LOCAL_PORT); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addEventListener(new KaryonGuiceContextListener()); context.addFilter(GuiceFilter.class, "/*", 1); context.addServlet(DefaultServlet.class, "/"); server.setHandler(context); server.start(); } @AfterClass public void cleanup() throws Exception { if (server != null) { server.stop(); } } public void verifyRESTEndpoints() throws IOException { HttpClient client = new DefaultHttpClient(); for (Map.Entry<String, String> restEndPoint : REST_END_POINTS.entrySet()) { final String endPoint = buildLocalHostEndpoint(restEndPoint.getKey()); LOG.info("REST endpoint " + endPoint); HttpGet restGet = new HttpGet(endPoint); HttpResponse response = client.execute(restGet); assertEquals(response.getStatusLine().getStatusCode(), 200); assertEquals(response.getEntity().getContentType().getValue(), restEndPoint.getValue()); // need to consume full response before make another rest call with // the default SingleClientConnManager used with DefaultHttpClient IOUtils.closeQuietly(response.getEntity().getContent()); } } private String buildLocalHostEndpoint(String endPoint) { return "http://localhost:" + TEST_LOCAL_PORT + endPoint; } }
1,898
0
Create_ds/Nicobar/nicobar-manager/src/main/java/com/netflix/nicobar/manager
Create_ds/Nicobar/nicobar-manager/src/main/java/com/netflix/nicobar/manager/explorer/ScriptManagerApp.java
/** * Copyright 2013 Netflix, Inc. * * 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. */ package com.netflix.nicobar.manager.explorer; import com.netflix.karyon.spi.Application; @Application public class ScriptManagerApp { }
1,899