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-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/manager/package-info.java
/******************************************************************************* * Copyright 2010-2021 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. ******************************************************************************/ /** * Managers for S3 and SQS related activities. */ package com.amazonaws.services.cloudtrail.processinglibrary.manager;
5,300
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/SQSBasedSource.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model; import com.amazonaws.services.sqs.model.Message; import java.util.List; import java.util.Map; public class SQSBasedSource implements CloudTrailSource{ /** * List of CloudTrailLogs inside this source. */ private final List<CloudTrailLog> logs; /** * The SQS message polled from queue. */ private final Message sqsMessage; /** * This method return a Map of String (key) and String (value). This map contains standard SQS message * attributes, i.e. SenderId, SentTimestamp, ApproximateReceiveCount, and/or * ApproximateFirstReceiveTimestamp, etc as well as attributes CloudTrail published. * * @param sqsMessage {@link Message} SQS message. * @param logs A list of {@link CloudTrailLog}. */ public SQSBasedSource(Message sqsMessage, List<CloudTrailLog> logs) { this.sqsMessage = sqsMessage; this.logs = logs; } /** * Retrieve the CloudTrailSource attributes. */ @Override public Map<String, String> getSourceAttributes() { return sqsMessage.getAttributes(); } /** * @return the SQS message. */ public Message getSqsMessage() { return sqsMessage; } /** * @return the list of CloudTrailLog retrieved from the source. */ public List<CloudTrailLog> getLogs() { return logs; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{"); if (logs != null) { builder.append("logs: "); builder.append(logs); builder.append(", "); } if (sqsMessage != null) { builder.append("sqsMessage: "); builder.append(sqsMessage); } builder.append("}"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((logs == null) ? 0 : logs.hashCode()); result = prime * result + ((sqsMessage == null) ? 0 : sqsMessage.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SQSBasedSource other = (SQSBasedSource) obj; if (logs == null) { if (other.logs != null) return false; } else if (!logs.equals(other.logs)) return false; if (sqsMessage == null) { if (other.sqsMessage != null) return false; } else if (!sqsMessage.equals(other.sqsMessage)) return false; return true; } }
5,301
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/SourceAttributeKeys.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model; /** * Enumeration of source attribute key names. */ public enum SourceAttributeKeys { SOURCE_TYPE("SourceType"), ACCOUNT_ID("accountId"), APPROXIMATE_FIRST_RECEIVE_TIMESTAMP("ApproximateFirstReceiveTimestamp"), APPROXIMATE_RECEIVE_COUNT("ApproximateReceiveCount"), SEND_TIMESTAMP("SentTimestamp"), SENDER_ID("SenderId"); private final String attributeKey; private SourceAttributeKeys(String attributeKey) { this.attributeKey = attributeKey; } public String getAttributeKey() { return attributeKey; } public static SourceAttributeKeys fromAttributeKeyName(String attributeKeyName) { for (SourceAttributeKeys attributeKey : SourceAttributeKeys.values()) { if (attributeKeyName.equals(attributeKey.getAttributeKey())) { return attributeKey; } } throw new IllegalArgumentException("Cannot create enum from " + attributeKeyName + " value!"); } }
5,302
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/CloudTrailLog.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model; /** * This a log that AWS CloudTrail published to user's SNS topic. */ public class CloudTrailLog { /** * The S3 bucket where log files are stored. */ private final String s3Bucket; /** * S3 object key. */ private String s3ObjectKey; /** * The CloudTrail log file size in bytes. */ private long logFileSize; /** * Constructs a new CloudTrailLog object. * * @param s3Bucket The S3 bucket where log files are stored. * @param s3ObjectKey The S3 object key. */ public CloudTrailLog(String s3Bucket, String s3ObjectKey) { this.s3Bucket = s3Bucket; this.s3ObjectKey = s3ObjectKey; } /** * Get AWS S3 bucket name. * @return AWS S3 bucket name. */ public String getS3Bucket() { return s3Bucket; } /** * Get AWS S3 object key in a single SQS message. * @return S3 object keys in a single SQS message. */ public String getS3ObjectKey() { return s3ObjectKey; } /** * CloudTrail log File size in bytes. * @return CloudTrail log file size in bytes. */ public long getLogFileSize() { return logFileSize; } /** * Set log file size when retrieve this information from S3 metadata. * @param logFileSize The CloudTrail log file size. */ public void setLogFileSize(long logFileSize) { this.logFileSize = logFileSize; } /** * Returns a string representation of this object; useful for testing and debugging. */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("CloudTrailLog ["); if (s3Bucket != null) { builder.append("s3Bucket="); builder.append(s3Bucket); builder.append(", "); } if (s3ObjectKey != null) { builder.append("s3ObjectKey="); builder.append(s3ObjectKey); builder.append(", "); } builder.append("logFileSize="); builder.append(logFileSize); builder.append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (logFileSize ^ (logFileSize >>> 32)); result = prime * result + ((s3Bucket == null) ? 0 : s3Bucket.hashCode()); result = prime * result + ((s3ObjectKey == null) ? 0 : s3ObjectKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CloudTrailLog other = (CloudTrailLog) obj; if (logFileSize != other.logFileSize) return false; if (s3Bucket == null) { if (other.s3Bucket != null) return false; } else if (!s3Bucket.equals(other.s3Bucket)) return false; if (s3ObjectKey == null) { if (other.s3ObjectKey != null) return false; } else if (!s3ObjectKey.equals(other.s3ObjectKey)) return false; return true; } }
5,303
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/CloudTrailSource.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model; import java.util.Map; /** * A skeleton class used for source filter. * <p> * When using it, users should cast it to a specific subclass. */ public interface CloudTrailSource { /** * Retrieve {@link CloudTrailSource} attributes. * * @return a Map containing key/value pairs representing the attributes of the CloudTrailSource. */ public Map<String, String> getSourceAttributes(); }
5,304
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/CloudTrailEventMetadata.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model; /** * A skeleton class used for providing CloudTrail delivery information. * <p> * CloudTrailEventMetadata information is provided when raw event information is enabled in the configuration parameters. * </p> */ public interface CloudTrailEventMetadata { }
5,305
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/CloudTrailEvent.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model; /** * Provides AWS CLoudTrail log information to your * {@link com.amazonaws.services.cloudtrail.processinglibrary.interfaces.EventsProcessor}'s * <code>process</code> method. */ public class CloudTrailEvent { /** An instance of CloudTrailEventData. */ private CloudTrailEventData eventData; /** An instance of CloudTrailEventMetadata. */ private CloudTrailEventMetadata eventMetadata; /** * Initializes a CloudTrailEvent object. * * @param eventData The {@link CloudTrailEventData} to process. * @param eventMetadata A {@link CloudTrailEventMetadata} object that can provide delivery information about the event. */ public CloudTrailEvent(CloudTrailEventData eventData, CloudTrailEventMetadata eventMetadata) { this.eventData = eventData; this.eventMetadata = eventMetadata; } /** * Get the {@link CloudTrailEventData} used to initialize this object. * * @return the <code>CloudTrailEventData</code> held by this instance. */ public CloudTrailEventData getEventData() { return eventData; } /** * Get the {@link CloudTrailEventMetadata} used to initialize this object. * * @return the <code>CloudTrailDeliveryInfo</code>. */ public CloudTrailEventMetadata getEventMetadata() { return eventMetadata; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string with the format: * <code>{ eventData: "eventData", eventMetadata: "eventMetadata" }</code>. * A field will not be rendered if its value is <code>null</code>. */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{"); if (eventData != null) builder.append("eventData: ").append(eventData).append(", "); if (eventMetadata != null) builder.append("eventMetadata: ").append(eventMetadata); builder.append("}"); return builder.toString(); } /** * Returns a hash code for the object. * * @return the object's hash code value. */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((eventMetadata == null) ? 0 : eventMetadata.hashCode()); result = prime * result + ((eventData == null) ? 0 : eventData.hashCode()); return result; } /** * Compares this <code>CloudTrailEvent</code> object with another. * * @return <code>true</code> if they represent the same event; * <code>false</code> * otherwise. */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CloudTrailEvent other = (CloudTrailEvent) obj; if (eventMetadata == null) { if (other.eventMetadata != null) return false; } else if (!eventMetadata.equals(other.eventMetadata)) return false; if (eventData == null) { if (other.eventData != null) return false; } else if (!eventData.equals(other.eventData)) return false; return true; } }
5,306
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/CloudTrailEventData.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.Addendum; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.CloudTrailDataStore; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.CloudTrailEventField; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.InsightDetails; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.Resource; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.TlsDetails; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.UserIdentity; import java.util.Date; import java.util.List; import java.util.UUID; /** * Contains information about requests for resources in your AWS account. * <p> * Information provided includes what services were accessed, what action was performed, and any parameters for the * action. The request also provides information about who made the request. * * @see <a href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/event_reference_top_level.html">CloudTrail Event Reference</a> */ public class CloudTrailEventData extends CloudTrailDataStore { /** * Get the event version. * * @return The version of the log event format. The current version is 1.02. */ public String getEventVersion() { return (String) get(CloudTrailEventField.eventVersion.name()); } /** * Get the UserIdentity object held by this instance. * * @see <a href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/event_reference_user_identity.html">userIdentity Element</a> * @return Information about the user that made a request. */ public UserIdentity getUserIdentity() { return (UserIdentity) get(CloudTrailEventField.userIdentity.name()); } /** * Get the event timestamp for this event. * * @return The date and time the request was made, in coordinated universal time (UTC). */ public Date getEventTime() { return (Date) get(CloudTrailEventField.eventTime.name()); } /** * Get the event name for this event. * * @see <a href="http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_Operations.html">AWS CloudTrail Actions</a> * @return The event name, an AWS CloudTrail action as listed in the API Reference. */ public String getEventName() { return (String) get(CloudTrailEventField.eventName.name()); } /** * Get the event source for this event. * * @return The service that the request was made to. For example, a call to Amazon EC2 is listed in the eventSource * field as ec2.amazonaws.com. */ public String getEventSource() { return (String) get(CloudTrailEventField.eventSource.name()); } /** * Get the AWS region for this event. * * @return The AWS region that the request was made to. */ public String getAwsRegion() { return (String) get(CloudTrailEventField.awsRegion.name()); } /** * Get the source IP address for this event. * <p> * For actions that originate from the service console, the address reported is for the underlying customer * resource, not the console web server. For services in AWS, only the DNS name is displayed. * </p> * @return The apparent IP address that the request was made from. */ public String getSourceIPAddress() { return (String) get(CloudTrailEventField.sourceIPAddress.name()); } /** * Get the event user agent for this event. * * @return The agent through which the request was made, such as the AWS Management Console or an AWS SDK. */ public String getUserAgent() { return (String) get(CloudTrailEventField.userAgent.name()); } /** * Get the request ID. * * @return An identifier generated by the service being called to uniquely identify * the request. */ public String getRequestId() { return (String) get(CloudTrailEventField.requestID.name()); } /** * Get the API call error code. * * @return The AWS service error if the request returns an error, or <code>null</code> if no error was returned. */ public String getErrorCode() { return (String) get(CloudTrailEventField.errorCode.name()); } /** * Get API call error message. * <p> * This includes messages for authorization failures. For such messages, CloudTrail captures the message logged by * the service in its exception handling. * </p> * @return If the request returns an error, the description of the error, or <code>null</code> if there was no * error. */ public String getErrorMessage() { return (String) get(CloudTrailEventField.errorMessage.name()); } /** * Get API call request parameters. * <p> * API Request parameters are specific to both the AWS service and the API action that is being called. Refer to the * API reference for the service identified in the request for more details about the parameters. * </p> * @return The parameters, if any, that were sent with the request. */ public String getRequestParameters() { return (String) get(CloudTrailEventField.requestParameters.name()); } /** * Get API call response elements. * <p> * If an action does not change state (for example, a request to <code>get</code> or <code>list</code> objects), * this element is omitted. Response elements such as request parameters are documented in the API Reference * documentation for the AWS service identified in the response. * </p> * @return The response element for actions that make changes (such as the <code>create</code>, <code>update</code>, * or <code>delete</code> actions). */ public String getResponseElements() { return (String) get(CloudTrailEventField.responseElements.name()); } /** * Get aws service event details * <p> * This field will only be visible to awsServiceEvent type, it indicates what trigger the event and what the result * of this event. * </p> * @return The service event detail for an awsServiceEvent type event */ public String getServiceEventDetails() { return (String) get(CloudTrailEventField.serviceEventDetails.name()); } /** * Get additional API data. * * @return Additional API call data set by AWS services. */ public String getAdditionalEventData() { return (String) get(CloudTrailEventField.additionalEventData.name()); } /** * Get the event ID. * <p> * You can use this value to identify a single event. For example, you can use the ID as a primary key to retrieve * log data from a searchable database. * </p> * @return A GUID generated by CloudTrail to uniquely identify each event. */ public UUID getEventId() { return (UUID) get(CloudTrailEventField.eventID.name()); } /** * Check whether the operation is read-only. * * @return <code>true</code> if the operation identified in the log is read-only. */ public Boolean isReadOnly() { return (Boolean) get(CloudTrailEventField.readOnly.name()); } /** * Check whether the event is a management event. * @return <code>true</code> if the event identified in the log is a management event. */ public Boolean isManagementEvent() { return (Boolean) get(CloudTrailEventField.managementEvent.name()); } /** * Get the resources used in the operation. * * @return A list of resources used in this operation. */ @SuppressWarnings("unchecked") public List<Resource> getResources() { return (List<Resource>) get(CloudTrailEventField.resources.name()); } /** * Get the AWS account ID from UserIdentity. * <p> * If the request was made using temporary security credentials, this is the account that owns the IAM user or role * that was used to obtain credentials. * </p> * @return The account that owns the entity that granted permissions for the request. */ public String getAccountId() { return (String) get(CloudTrailEventField.accountId.name()); } /** * Get the event category. * * @return Identifies the category of CloudTrail event. */ public String getEventCategory() { return (String) get(CloudTrailEventField.eventCategory.name()); } /** * Get the event type. * * @return Identifies the type of event that generated the event. */ public String getEventType() { return (String) get(CloudTrailEventField.eventType.name()); } /** * Get the API version. * * @return the API version associated with the AWS API call's eventType value. */ public String getApiVersion() { return (String) get(CloudTrailEventField.apiVersion.name()); } /** * Get the recipient account ID * * @return the account ID that received this event. */ public String getRecipientAccountId() { return (String) get(CloudTrailEventField.recipientAccountId.name()); } /** * Get the shared event ID * * @return When recipientAccountList has size greater than 1, then sharedEventID is generated * to indicate multiple CloudTrail events originate from a single service event. */ public String getSharedEventId() { return (String) get(CloudTrailEventField.sharedEventID.name()); } /** * Get the annotation * * @return User provided annotation tagging delivered by CloudTrail. */ public String getAnnotation() { return (String) get(CloudTrailEventField.annotation.name()); } /** * Get the vpc endpoint ID * * @return The VPC endpoint in which requests were made from a VPC to another AWS service, such as Amazon S3. */ public String getVpcEndpointId() { return (String) get(CloudTrailEventField.vpcEndpointId.name()); } /** * Get the insight details * * @return information about the underlying triggers of an Insights event, such as event source, * statistics, API name, and whether the event is the start or end of the Insights event. */ public InsightDetails getInsightDetails() { return (InsightDetails) get(CloudTrailEventField.insightDetails.name()); } /** * Get the addendum * <p> * The Addendum block of an addendum event includes details to fill an auditing gap or update an older event. * It only appears to update an older event. * </p> * @return Details of an Addendum block, such as a reason for the addendum, * updated fields, original request ID, and original event ID.. */ public Addendum getAddendum() { return (Addendum) get(CloudTrailEventField.addendum.name()); } /** * Get the edge device details * * @return Information about the edge device, such as device type, device ID. */ public String getEdgeDeviceDetails() { return (String) get(CloudTrailEventField.edgeDeviceDetails.name()); } /** * Get the TLS details * <p> * Shows information about the Transport Layer Security (TLS) version, cipher suites, and FQDN of the * client-provided host name of the service API call. * </p> * @return The TLS details of a service API call. */ public TlsDetails getTlsDetails() { return (TlsDetails) get(CloudTrailEventField.tlsDetails.name()); } /** * Check whether an event originated from an AWS Management Console session. * <p> * The field is not shown unless the value is true, meaning that the client that was used to make the API call * was either a proxy or an external client. * </p> * @return <code>true</code> if the event originated from an AWS Management Console session. */ public String getSessionCredentialFromConsole() { return (String) get(CloudTrailEventField.sessionCredentialFromConsole.name()); } }
5,307
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/package-info.java
/******************************************************************************* * Copyright 2010-2021 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. ******************************************************************************/ /** * Provides lower-level types that are used by many of the AWS CloudTrail Processing Library's methods. */ package com.amazonaws.services.cloudtrail.processinglibrary.model;
5,308
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/LogDeliveryInfo.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model; /** * CloudTrail log delivery information. */ public class LogDeliveryInfo implements CloudTrailEventMetadata{ private CloudTrailLog log; private int charStart; private int charEnd; private String rawEvent; /** * The log delivery information. * * @param log that event was coming from. * @param charStart the 0-based location of the event's starting character "{" and -1 when enableRawEventInfo is false. * @param charEnd the 0-based location of the event's ending character "}" and -1 when enableRawEventInfo is false. * @param rawEvent the CloudTrail event in raw String - as it is in the log file and null when enableRawEventInfo is false. */ public LogDeliveryInfo(CloudTrailLog log, int charStart, int charEnd, String rawEvent) { this.log = log; this.charStart = charStart; this.charEnd = charEnd; this.rawEvent = rawEvent; } /** * @return the CloudTrail log. */ public CloudTrailLog getLog() { return log; } /** * @return the location of the event's starting character. */ public long getCharStart() { return charStart; } /** * @return the location of the event's ending character. */ public long getCharEnd() { return charEnd; } /** * @return the CloudTrail event in raw String - as it is in the log file. */ public String getRawEvent() { return rawEvent; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{"); if (log != null) { builder.append("log: "); builder.append(log); builder.append(", "); } builder.append("charStart: "); builder.append(charStart); builder.append(", charEnd: "); builder.append(charEnd); builder.append(", "); if (rawEvent != null) { builder.append("rawEvent: "); builder.append(rawEvent); } builder.append("}"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (charEnd ^ (charEnd >>> 32)); result = prime * result + (charStart ^ (charStart >>> 32)); result = prime * result + ((log == null) ? 0 : log.hashCode()); result = prime * result + ((rawEvent == null) ? 0 : rawEvent.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LogDeliveryInfo other = (LogDeliveryInfo) obj; if (charEnd != other.charEnd) return false; if (charStart != other.charStart) return false; if (log == null) { if (other.log != null) return false; } else if (!log.equals(other.log)) return false; if (rawEvent == null) { if (other.rawEvent != null) return false; } else if (!rawEvent.equals(other.rawEvent)) return false; return true; } }
5,309
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/TlsDetails.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; /** * Information about the Transport Layer Security (TLS) details of a service API call. */ public class TlsDetails extends CloudTrailDataStore { /** * Get the TLS version of the request. * * @return The TLS version */ public String getTlsVersion() { return (String) this.get(CloudTrailEventField.tlsVersion.name()); } /** * Get the cipher suite (combination of security algorithms used) of the request. * * @return The cipher suite */ public String getCipherSuite() { return (String) this.get(CloudTrailEventField.cipherSuite.name()); } /** * Get the client-provided host header. * * @return the FQDN of the client that made the request. */ public String getClientProvidedHostHeader() { return (String) this.get(CloudTrailEventField.clientProvidedHostHeader.name()); } }
5,310
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/InsightDetails.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; /** * Shows information about the underlying triggers of an Insights event, such as event source, * statistics, API name, and whether the event is the start or end of the Insights event. */ public class InsightDetails extends CloudTrailDataStore { /** * Get event name * * @return The AWS API for which unusual activity was detected. */ public String getEventName() { return (String) this.get(CloudTrailEventField.eventName.name()); } /** * Get event source * * @return The service that the request was made to. This name is typically a short form of the service name without spaces plus .amazonaws.com. */ public String getEventSource() { return (String) this.get(CloudTrailEventField.eventSource.name()); } /** * Get insight context * * @return {@link InsightContext} Data about the rate of calls that triggered the Insights event compared to the normal rate of calls to the subject API per minute. */ public InsightContext getInsightContext() { return (InsightContext) this.get(CloudTrailEventField.insightContext.name()); } /** * Get insight type * * @return The type of Insights event. Value is ApiCallRateInsight or ApiErrorRateInsight. */ public String getInsightType() { return (String) this.get(CloudTrailEventField.insightType.name()); } /** * Get state * * @return Shows whether the event represents the start or end of the insight (the start or end of unusual activity). Values are start or end. */ public String getState() { return (String) this.get(CloudTrailEventField.state.name()); } /** * Get error code * * @return The AWS API error code on which unusual activity is detected. */ public String getErrorCode() { return (String) this.get(CloudTrailEventField.errorCode.name()); } }
5,311
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/Resource.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; /** * AWS resources. */ public class Resource extends CloudTrailDataStore { /** * Get the Amazon Resource Name (ARN) for this resource. * * @return the ARN associated with the resource. */ public String getArn() { return (String) get(CloudTrailEventField.ARN.name()); } /** * Get the ARNPrefix of the resource. * * Resource must have either ARN or ARNPrefix, but not both. * * @return the ARNPrefix associated with the resource. */ public String getArnPrefix() { return (String) get(CloudTrailEventField.ARNPrefix.name()); } /** * Get the account ID associated with the resource. * * This value could be null * * @return the account ID */ public String getAccountId() { return (String) get(CloudTrailEventField.accountId.name()); } /** * * Get resource type * * @return the type of resource. e.g. AWS::IAM::Role */ public String getType() { return (String) get(CloudTrailEventField.type.name()); } }
5,312
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/InsightStatistics.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; import java.util.Map; /** * A container for data about the typical average rate of calls to the subject API by an account, * the rate of calls that triggered the Insights event, and the duration, in minutes, of the Insights event. */ public class InsightStatistics extends CloudTrailDataStore { /** * Get baseline * * @return Shows the typical average rate of calls to the subject API by an account. */ @SuppressWarnings("unchecked") public Map<String, Double> getBaseline() { return (Map<String, Double>) this.get(CloudTrailEventField.baseline.name()); } /** * Get insight * * @return Shows the unusual rate of calls to the subject API that triggers the logging of an Insights event. */ @SuppressWarnings("unchecked") public Map<String, Double> getInsight() { return (Map<String, Double>) this.get(CloudTrailEventField.insight.name()); } /** * Get insight duration * * @return The duration, in minutes, of an Insights event (the time period from the start to end of unusual activity on the subject API). */ public Integer getInsightDuration() { return (Integer) this.get(CloudTrailEventField.insightDuration.name()); } /** * Get baseline duration * * @return The baseline duration, in minutes, of an Insights event. Start day and time is 7 days before an Insights * event occurs, rounded down to a full (or integral) day. The end time is when the Insights event occurs. */ public Integer getBaselineDuration() { return (Integer) this.get(CloudTrailEventField.baselineDuration.name()); } }
5,313
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/InsightContext.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; import java.util.List; /** * Data about the rate of calls that triggered the Insights event * compared to the normal rate of calls to the subject API per minute. */ public class InsightContext extends CloudTrailDataStore { /** * Get insight statistics * * @return {@link InsightStatistics} */ public InsightStatistics getStatistics() { return (InsightStatistics) this.get(CloudTrailEventField.statistics.name()); } /** * Get Insights event attributions. Each {@link InsightAttributions} contains attribute values for a specific * type of attribute, such as userIdentityArn, userAgent and errorCode. * * @return list of {@link InsightAttributions} */ @SuppressWarnings("unchecked") public List<InsightAttributions> getAttributions() { return (List<InsightAttributions>) this.get(CloudTrailEventField.attributions.name()); } }
5,314
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/UserIdentity.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.CloudTrailDataStore; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.CloudTrailEventField; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.OnBehalfOf; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.SessionContext; /** * Information about the user that made a request is included in the userIdentity element. * This information can help you determine how your AWS resources have been accessed. */ public class UserIdentity extends CloudTrailDataStore { /** * Get identity type. * * @return The type of the principal that made the call. */ public String getIdentityType() { return (String) this.get(CloudTrailEventField.type.name()); } /** * Get principal ID. * * @return A unique identifier for the principal. For requests made with temporary * security credentials, this value includes the session name that is passed to * the AssumeRole, AssumeRoleWIthWebIdentity, or GetFederationToken API call. */ public String getPrincipalId() { return (String) this.get(CloudTrailEventField.principalId.name()); } /** * Get principal ARN. * * @return The Amazon Resource Name (ARN) of the principal that made the call. */ public String getARN() { return (String) this.get(CloudTrailEventField.arn.name()); } /** * Get account ID. * * @return The account that owns the entity that granted permissions for the * request. If the request was made using temporary security credentials, this * is the account that owns the IAM user or role that was used to obtain credentials. */ public String getAccountId() { return (String) this.get(CloudTrailEventField.accountId.name()); } /** * Get access key ID. * * @return The access key ID that was used to sign the request. If the request * was made using temporary security credentials, this is the access key ID of * the temporary credentials. */ public String getAccessKeyId() { return (String) this.get(CloudTrailEventField.accessKeyId.name()); } /** * Get user name. * * @return Friendly name of the principal that made the call. */ public String getUserName() { return (String) this.get(CloudTrailEventField.userName.name()); } /** * Get invoked by. * * @return If the request was made by another AWS service, such as Auto * Scaling or AWS Elastic Beanstalk, the name of the service. */ public String getInvokedBy() { return (String) this.get(CloudTrailEventField.invokedBy.name()); } /** * Get session context. * * @return {@link SessionContext} If the request was made with temporary security credentials, an element * that provides information about the session that was created for those credentials. */ public SessionContext getSessionContext() { return (SessionContext) this.get(CloudTrailEventField.sessionContext.name()); } /** * Get identity provider. * * @return The principal name of the external identity provider. * This field appears only for SAMLUser or WebIdentityUser types. */ public String getIdentityProvider() { return (String) this.get(CloudTrailEventField.identityProvider.name()); } public String getCredentialId() { return (String) this.get(CloudTrailEventField.credentialId.name()); } public OnBehalfOf getOnBehalfOf() { return (OnBehalfOf) this.get(CloudTrailEventField.onBehalfOf.name()); } }
5,315
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/WebIdentitySessionContext.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; import java.util.Map; /** * If the request was made with temporary security credentials obtained using web * identity federation, an element that lists information about the identity provider. */ public class WebIdentitySessionContext extends CloudTrailDataStore{ /** * Get federated provider. * @return Who To grant temporary access to a non-AWS user. */ public String getFederatedProvider() { return (String) this.get(CloudTrailEventField.federatedProvider.name()); } /** * Get attributes. * * @return additional web identity session contest attributes. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Map<String, String> getAttributes() { return (Map) this.get(CloudTrailEventField.attributes.name()); } }
5,316
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/OnBehalfOf.java
package com.amazonaws.services.cloudtrail.processinglibrary.model.internal; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.CloudTrailDataStore; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.CloudTrailEventField; public class OnBehalfOf extends CloudTrailDataStore { public String getUserId() { return (String) this.get(CloudTrailEventField.onBehalfOfUserId.name()); } public String getIdentityStoreArn() { return (String) this.get(CloudTrailEventField.onBehalfOfIdentityStoreArn.name()); } }
5,317
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/InsightAttributions.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; import java.util.List; /** * Data structure that contains attribute value entities for a specific attribute type (for example, userIdentityArn, * userAgent and errorCode), available for both insightDuration and baselineDuration of an Insights event. */ public class InsightAttributions extends CloudTrailDataStore { /** * Get attribute type * * @return type, or name of this {@link InsightAttributions}. For example, "userIdentityArn". */ public String getAttribute() { return (String) this.get(CloudTrailEventField.attribute.name()); } /** * Get list of attribute values for the duration of the Insights event. * * @return list of {@link AttributeValue}, sorted by their average numbers in descending order. */ @SuppressWarnings("unchecked") public List<AttributeValue> getInsight() { return (List<AttributeValue>) this.get(CloudTrailEventField.insight.name()); } /** * Get the list of attribute values for the baselineDuration of the Insights event, which is about the seven-day * period before the start time of the Insights event. * * @return list of {@link AttributeValue}, sorted by their average numbers in descending order. */ @SuppressWarnings("unchecked") public List<AttributeValue> getBaseline() { return (List<AttributeValue>) this.get(CloudTrailEventField.baseline.name()); } }
5,318
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/CloudTrailDataStore.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; import java.util.HashMap; import java.util.Map; /** * Internal use only. * <p> * Generic data store for the AWS CloudTrail model. */ public class CloudTrailDataStore { /** * Store underlying data into a map. */ private Map<String, Object> dataStore; public CloudTrailDataStore() { this.dataStore = new HashMap<>(); } /** * Internal use only. * <p> * Add a key/value pair to the underlying data store. * * @param key the key used to index the value. * @param value the value that will be associated with the provided key. */ public void add(String key, Object value) { this.dataStore.put(key, value); } /** * Internal use only. * <p> * Retrieve a value associated with a key from the underlying data store. * * @param key the key in data store * @return the value associated with the provided key. */ public Object get(String key) { return this.dataStore.get(key); } /** * Internal use only. * <p> * Verifies if the data store has a value associated with a particluar key. * * @param key the key in the data store to query. * @return <code>true</code> if the provided key exists in the data store; <code>false</code> otherwise. */ public boolean has(String key) { return this.dataStore.containsKey(key); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{"); if (dataStore != null) { builder.append(this.getClass().getSimpleName()); builder.append(": "); builder.append(dataStore); } builder.append("}"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dataStore == null) ? 0 : dataStore.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CloudTrailDataStore other = (CloudTrailDataStore) obj; if (dataStore == null) { if (other.dataStore != null) return false; } else if (!dataStore.equals(other.dataStore)) return false; return true; } }
5,319
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/SessionIssuer.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; public class SessionIssuer extends CloudTrailDataStore{ /** * Get session issuer type * * @return The source of the temporary security credentials, such as "Root", "IAMUser", or "Role" */ public String getType() { return (String) this.get(CloudTrailEventField.type.name()); } /** * Get session issuer principal ID * * @return The internal ID of the entity that was used to get credentials. */ public String getPrincipalId() { return (String) this.get(CloudTrailEventField.principalId.name()); } /** * Get session issuer ARN * * @return The ARN of the source (account, IAM user, or role) that was used to get temporary security credentials. */ public String getArn() { return (String) this.get(CloudTrailEventField.arn.name()); } /** * Get session issuer account ID * * @return The account that owns the entity that was used to get credentials. */ public String getAccountId() { return (String) this.get(CloudTrailEventField.accountId.name()); } /** * Get session issuer user name * * @return The friendly name of the user or role. */ public String getUserName() { return (String) this.get(CloudTrailEventField.userName.name()); } }
5,320
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/Addendum.java
/******************************************************************************* * Copyright 2010-2019 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.cloudtrail.processinglibrary.model.internal; /** * The Addendum block of an addendum event includes details to fill an auditing gap or update an older event. * * It shows details of an addendum to an older event, such as a reason for delivery, * updated fields, original request ID, and original event ID. */ public class Addendum extends CloudTrailDataStore { /** * Get reason * * @return The reason for the delivery of the addendum event. */ public String getReason() { return (String) this.get(CloudTrailEventField.reason.name()); } /** * Get updated fields * * @return A string of comma-delimited updated fields. */ public String getUpdatedFields() { return (String) this.get(CloudTrailEventField.updatedFields.name()); } /** * Get original request ID * * @return The request ID that matches the original delivered event. If there is no original delivered event, the value is null. */ public String getOriginalRequestID() { return (String) this.get(CloudTrailEventField.originalRequestID.name()); } /** * Get original event ID * * @return The event ID that matches the original delivered event. If there is no original delivered event, the value is null. */ public String getOriginalEventID() { return (String) this.get(CloudTrailEventField.originalEventID.name()); } }
5,321
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/AttributeValue.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; /** * POJO (Plain Old Java Object) that represents the attribute value entitle for a specific attribute type. * Contains the value of the attribute and average for a specified time range */ public class AttributeValue extends CloudTrailDataStore { /** * Get the value of the attribute. * * @return a string value representation of the attribute. */ public String getValue() { return (String) this.get(CloudTrailEventField.value.name()); } /** * Get the average number of occurrences for the attribute value within a time range (either the time range of * insightDuration or baselineDuration). * * @return {@link Double} representation, which is precise to the 10th decimal number. */ public Double getAverage() { return (Double) this.get(CloudTrailEventField.average.name()); } public static class OnBehalfOf extends CloudTrailDataStore { public String getUserId() { return (String) this.get(CloudTrailEventField.onBehalfOfUserId.name()); } public String getIdentityStoreArn() { return (String) this.get(CloudTrailEventField.onBehalfOfIdentityStoreArn.name()); } } }
5,322
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/SessionContext.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; import java.util.Map; /** * If the request was made with temporary security credentials, an element that provides information about * the session that was created for those credentials. Sessions are created when any API is called that * returns temporary credentials. Sessions are also created when users work in the console and when users * make a request using APIs that include multi-factor authentication. */ public class SessionContext extends CloudTrailDataStore{ public SessionIssuer getSessionIssuer() { return (SessionIssuer) this.get(CloudTrailEventField.sessionIssuer.name()); } /** * Get Web IdentitySessionContext * * @return {@link WebIdentitySessionContext} */ public WebIdentitySessionContext getWebIdFederationData() { return (WebIdentitySessionContext) this.get(CloudTrailEventField.webIdFederationData.name()); } /** * Get attributes * * @return additional session context attributes */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Map<String, String> getAttributes() { return (Map) this.get(CloudTrailEventField.attributes.name()); } }
5,323
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/SourceType.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailSource; import com.amazonaws.services.sqs.model.Message; /** * Enumeration of type of {@link CloudTrailSource}. * <p> * If there are multiple source types in {@link Message}, the priority of source type is in the following order: * <code>CloudTrailLog</code>, <code>Other</code>. * </p> * */ public enum SourceType { /** * CloudTrail log file. */ CloudTrailLog, /** * CloudTrail Validation Message. */ CloudTrailValidationMessage, /** * Non-CloudTrail log file. */ Other }
5,324
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/CloudTrailEventField.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.model.internal; /** * Internal use only. */ public enum CloudTrailEventField { Records, accessKeyId, accountId, addendum, additionalEventData, annotation, apiVersion, arn, ARN, ARNPrefix, attribute, attributes, attributions, average, awsRegion, baseline, baselineDuration, cipherSuite, clientProvidedHostHeader, credentialId, edgeDeviceDetails, errorCode, errorMessage, eventCategory, eventID, eventName, eventSource, eventTime, eventType, eventVersion, federatedProvider, identityProvider, insight, insightContext, insightDetails, insightDuration, insightType, invokedBy, managementEvent, originalRequestID, originalEventID, onBehalfOf, onBehalfOfUserId, onBehalfOfIdentityStoreArn, principalId, readOnly, reason, recipientAccountId, requestID, requestParameters, resources, responseElements, serviceEventDetails, sessionContext, sessionCredentialFromConsole, sessionIssuer, sharedEventID, sourceIPAddress, state, statistics, tlsDetails, tlsVersion, type, updatedFields, userAgent, userIdentity, userName, value, vpcEndpointId, webIdFederationData }
5,325
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/model/internal/package-info.java
/******************************************************************************* * Copyright 2010-2021 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. ******************************************************************************/ /** * Internal types. */ package com.amazonaws.services.cloudtrail.processinglibrary.model.internal;
5,326
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/factory/EventReaderFactory.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.factory; import com.amazonaws.services.cloudtrail.processinglibrary.configuration.ProcessingConfiguration; import com.amazonaws.services.cloudtrail.processinglibrary.interfaces.ExceptionHandler; import com.amazonaws.services.cloudtrail.processinglibrary.interfaces.ProgressReporter; import com.amazonaws.services.cloudtrail.processinglibrary.interfaces.EventFilter; import com.amazonaws.services.cloudtrail.processinglibrary.interfaces.EventsProcessor; import com.amazonaws.services.cloudtrail.processinglibrary.interfaces.SourceFilter; import com.amazonaws.services.cloudtrail.processinglibrary.manager.S3Manager; import com.amazonaws.services.cloudtrail.processinglibrary.manager.SqsManager; import com.amazonaws.services.cloudtrail.processinglibrary.reader.EventReader; import com.amazonaws.services.cloudtrail.processinglibrary.utils.LibraryUtils; /** * <i>Internal use only</i>. * * This class creates {@link EventReader} objects. It encapsulates and maintains instances of the objects that * <code>EventReader</code> will use to limit the parameters needed to create an instance. */ public class EventReaderFactory { private ProcessingConfiguration config; private EventsProcessor eventsProcessor; private SourceFilter sourceFilter; private EventFilter eventFilter; private ProgressReporter progressReporter; private ExceptionHandler exceptionHandler; /* The class responsible for SQS-related operations. */ private SqsManager sqsManager; /* The class responsible for S3-related operations. */ private S3Manager s3Manager; /** * EventReaderFactory constructor. * <p> * Except for ProcessingConfiguration, the other parameters can be <code>null</code>. * </p> * @param builder a {@link Builder} object to use to create the <code>EventReaderFactory</code>. */ private EventReaderFactory(Builder builder) { config = builder.config; eventsProcessor = builder.eventsProcessor; sourceFilter = builder.sourceFilter; eventFilter = builder.eventFilter; progressReporter = builder.progressReporter; exceptionHandler = builder.exceptionHandler; sqsManager = builder.sqsManager; s3Manager = builder.s3Manager; validate(); } public static class Builder { private final ProcessingConfiguration config; private EventsProcessor eventsProcessor; private SourceFilter sourceFilter; private EventFilter eventFilter; private ProgressReporter progressReporter; private ExceptionHandler exceptionHandler; private S3Manager s3Manager; private SqsManager sqsManager; public Builder(ProcessingConfiguration config) { this.config = config; } public Builder withEventsProcessor(EventsProcessor eventsProcessor) { this.eventsProcessor = eventsProcessor; return this; } public Builder withSourceFilter(SourceFilter sourceFilter) { this.sourceFilter = sourceFilter; return this; } public Builder withEventFilter(EventFilter eventFilter) { this.eventFilter = eventFilter; return this; } public Builder withProgressReporter(ProgressReporter progressReporter) { this.progressReporter = progressReporter; return this; } public Builder withExceptionHandler(ExceptionHandler exceptionHander) { this.exceptionHandler = exceptionHander; return this; } public Builder withS3Manager(S3Manager s3Manager) { this.s3Manager = s3Manager; return this; } public Builder withSQSManager(SqsManager sqsManager) { this.sqsManager = sqsManager; return this; } public EventReaderFactory build() { return new EventReaderFactory(this); } } /** * Create an instance of an {@link EventReader}. * * @return the {@link EventReader}. */ public EventReader createReader() { return new EventReader(eventsProcessor, sourceFilter, eventFilter, progressReporter, exceptionHandler, sqsManager, s3Manager, config); } /** * Validate input parameters. */ private void validate() { LibraryUtils.checkArgumentNotNull(config, "Configuration is null."); LibraryUtils.checkArgumentNotNull(eventsProcessor, "Events Processor is null."); LibraryUtils.checkArgumentNotNull(sourceFilter, "Source Filter is null."); LibraryUtils.checkArgumentNotNull(eventFilter, "Event Filter is null."); LibraryUtils.checkArgumentNotNull(progressReporter, "Progress Reporter is null."); LibraryUtils.checkArgumentNotNull(exceptionHandler, "Exception Handler is null."); LibraryUtils.checkArgumentNotNull(s3Manager, "S3 Manager is null."); LibraryUtils.checkArgumentNotNull(sqsManager, "SQS Manager is null."); } }
5,327
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/factory/SourceSerializerFactory.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.factory; import com.amazonaws.services.cloudtrail.processinglibrary.serializer.*; import com.amazonaws.services.cloudtrail.processinglibrary.utils.SNSMessageBodyExtractor; import com.amazonaws.services.cloudtrail.processinglibrary.utils.SourceIdentifier; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Factory for creating {@link SourceSerializer}. */ public class SourceSerializerFactory { private static final ObjectMapper mapper = new ObjectMapper(); private static final SNSMessageBodyExtractor snsMessageExtractor = new SNSMessageBodyExtractor(mapper); private static final SourceIdentifier sourceIdentifier = new SourceIdentifier(); /** * Default {@link SourceSerializerChain} construction. * <p> * This is the default serializer which is used if you do not provide a serializer. * </p> * * @return {@link SourceSerializer} Each of these source serializers is in the specified order. */ public static SourceSerializer createSourceSerializerChain() { List<SourceSerializer> sourceSerializers = new ArrayList<>(Arrays.asList( createCloudTrailSourceSerializer(), createS3SNSSourceSerializer(), createS3SourceSerializer(), createCloudTrailValidationMessageSerializer() )); return new SourceSerializerChain(sourceSerializers); } /** * Default {@link CloudTrailSourceSerializer} construction. * @return {@link SourceSerializer}. */ public static CloudTrailSourceSerializer createCloudTrailSourceSerializer() { return new CloudTrailSourceSerializer(snsMessageExtractor, mapper, sourceIdentifier); } /** * Default {@link S3SourceSerializer} construction. * @return {@link SourceSerializer}. */ public static S3SourceSerializer createS3SourceSerializer() { return new S3SourceSerializer(mapper, sourceIdentifier); } /** * Default {@link S3SNSSourceSerializer} construction. * @return {@link SourceSerializer}. */ public static S3SNSSourceSerializer createS3SNSSourceSerializer() { return new S3SNSSourceSerializer(snsMessageExtractor, createS3SourceSerializer()); } /** * Default {@link CloudTrailValidationMessageSerializer} construction. * @return {@link SourceSerializer}. */ public static CloudTrailValidationMessageSerializer createCloudTrailValidationMessageSerializer() { return new CloudTrailValidationMessageSerializer(snsMessageExtractor); } }
5,328
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/factory/ThreadPoolFactory.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.factory; import com.amazonaws.services.cloudtrail.processinglibrary.interfaces.ExceptionHandler; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailSource; import com.amazonaws.services.cloudtrail.processinglibrary.progress.ProgressState; import com.amazonaws.services.cloudtrail.processinglibrary.progress.ProgressStatus; import com.amazonaws.services.cloudtrail.processinglibrary.utils.LibraryUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * This class creates thread pool for ThreadPoolFactory. */ public class ThreadPoolFactory { private static final Log logger = LogFactory.getLog(ThreadPoolFactory.class); /** * Number of current running thread to process CloudTrailSources */ private int threadCount; /** * The exceptionHandler is used to handle uncaught exception. */ private ExceptionHandler exceptionHandler; /** * A factory to create an instance of ExecutorService based on configuration * * @param threadCount number of threads * @param exceptionHandler instance of {@link ExceptionHandler} */ public ThreadPoolFactory(int threadCount, ExceptionHandler exceptionHandler) { this.threadCount = threadCount; this.exceptionHandler = exceptionHandler; } /** * Create an instance of ScheduledExecutorService. We only need single thread to poll messages from the SQS queue. * * @return ScheduledExecutorService continuous poll messages from SQS queue. */ public ScheduledExecutorService createScheduledThreadPool(int numOfParallelReaders) { return Executors.newScheduledThreadPool(numOfParallelReaders); } /** * Create an instance of ExecutorService. ExecutorService is AWS CloudTrail Processing Library's main thread pool, * used to process each CloudTrailSource. The thread pool queue, size are configurable through * ProcessingConfiguration. * * @return {@link ExecutorService} that processes {@link CloudTrailSource}. */ public ExecutorService createMainThreadPool() { LibraryUtils.checkCondition(threadCount < 1, "Thread Count cannot be less than 1."); return this.createThreadPoolWithBoundedQueue(threadCount); } /** * Helper function to create an instance of ExecutorService with bounded queue size. * <p> * When no more threads or queue slots are available because their bounds would be exceeded, the scheduled * thread pool will run the rejected task directly. Unless the executor has been shut down, in which case the * task is discarded. Note while scheduled thread poll is running rejected task, scheduled thread pool will not * poll more messages to process. * </p> * @param threadCount the number of threads. * @return {@link ExecutorService} that processes {@link CloudTrailSource}. */ private ExecutorService createThreadPoolWithBoundedQueue(int threadCount) { BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(threadCount); RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy(); return new ProcessingLibraryThreadPoolExecutor(threadCount, threadCount, 0, TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler, exceptionHandler); } /** * When unexpected behavior happened, for example runtimeException. ProcessingLibraryThreadPoolExecutor will handle * the exception by calling ExceptionHandler provided by end user. */ public class ProcessingLibraryThreadPoolExecutor extends ThreadPoolExecutor { private ExceptionHandler exceptionHandler; public ProcessingLibraryThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler, ExceptionHandler exceptionHandler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); this.exceptionHandler = exceptionHandler; } @Override public void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); logger.debug("AWS CloudTrail Processing Library created a thread " + t.getName()); } @Override public void afterExecute(Runnable r, Throwable t) { try { if (t != null) { logger.error("AWS CloudTrail Processing Library encounters an uncaught exception. " + t.getMessage(), t); LibraryUtils.handleException(exceptionHandler, new ProgressStatus(ProgressState.uncaughtException, null), t.getMessage()); } } finally { super.afterExecute(r, t); logger.debug("AWS CloudTrail Processing Library completed execution of a runnable."); } } } }
5,329
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/factory/package-info.java
/******************************************************************************* * Copyright 2010-2021 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. ******************************************************************************/ /** * Factories used to construct objects. */ package com.amazonaws.services.cloudtrail.processinglibrary.factory;
5,330
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/interfaces/ExceptionHandler.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.interfaces; import com.amazonaws.services.cloudtrail.processinglibrary.exceptions.ProcessingLibraryException; import com.amazonaws.services.cloudtrail.processinglibrary.manager.S3Manager; import com.amazonaws.services.cloudtrail.processinglibrary.manager.SqsManager; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailLog; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailSource; import com.amazonaws.services.cloudtrail.processinglibrary.progress.ProgressStatus; import com.amazonaws.services.cloudtrail.processinglibrary.reader.EventReader; import com.amazonaws.services.sqs.model.Message; import java.util.List; /** * Provides a callback function that handles exceptions that occurred while processing AWS CloudTrail log files. * <p> * The {@link #handleException(ProcessingLibraryException)} method is invoked when exceptions are raised in the following scenarios when: * </p> * <ol> * <li>Polling messages from SQS - {@link SqsManager#pollQueue()}.</li> * <li>Parsing message from SQS - {@link SqsManager#parseMessage(List)}</li> * <li>Deleting messages from SQS - {@link SqsManager#deleteMessageFromQueue(Message, ProgressStatus)}.</li> * <li>Downloading an AWS CloudTrail log file - {@link S3Manager#downloadLog(CloudTrailLog, CloudTrailSource)}.</li> * <li>Processing the AWS CloudTrail log file - {@link EventReader#processSource(CloudTrailSource)}.</li> * <li>Any uncaught exceptions.</li> * </ol> * <p> * A {@link ProcessingLibraryException} contains execution context in the held {@link ProgressStatus} object, * which can be obtained by calling {@link ProcessingLibraryException#getStatus()}. * </p> */ public interface ExceptionHandler { /** * A callback method that handles exceptions that occurred while processing AWS CloudTrail log files. * * @param exception A {@link ProcessingLibraryException}. */ public void handleException(ProcessingLibraryException exception); }
5,331
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/interfaces/EventsProcessor.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.interfaces; import com.amazonaws.services.cloudtrail.processinglibrary.AWSCloudTrailProcessingExecutor; import com.amazonaws.services.cloudtrail.processinglibrary.configuration.ProcessingConfiguration; import com.amazonaws.services.cloudtrail.processinglibrary.exceptions.CallbackException; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailEvent; import java.util.List; /** * Provides a callback method that is used by an {@link AWSCloudTrailProcessingExecutor} to deliver AWS CloudTrail * records for processing. * <p> * The {@link #process(List)} is invoked after the optional {@link EventFilter}'s callback is invoked. If the * event was rejected by the {@link EventFilter}, then it will not be sent to {@link #process(List)}. * <p> * The number of events in the list is configurable through the <code>maxEventsPerEmit</code> property. * * @see ProcessingConfiguration */ public interface EventsProcessor { /** * A callback method that processes a list of {@link CloudTrailEvent}. * <p> * This callback is called by an {@link AWSCloudTrailProcessingExecutor} when it has records to process. * * @param events a list of {@link CloudTrailEvent}. * @throws CallbackException if an error occurs while processing <code>events</code>. */ public void process(List<CloudTrailEvent> events) throws CallbackException; }
5,332
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/interfaces/ProgressReporter.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.interfaces; import com.amazonaws.services.cloudtrail.processinglibrary.manager.S3Manager; import com.amazonaws.services.cloudtrail.processinglibrary.manager.SqsManager; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailLog; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailSource; import com.amazonaws.services.cloudtrail.processinglibrary.progress.ProgressStatus; import com.amazonaws.services.cloudtrail.processinglibrary.reader.EventReader; import com.amazonaws.services.sqs.model.Message; import java.util.List; /** * <code>ProgressReporter</code> is an interface for providing custom handlers of AWS CloudTrail Processing Library * progress. *<p> * {@link #reportStart(ProgressStatus)} and {@link #reportEnd(ProgressStatus, Object)} are invoked at the beginning and * the end of the following actions: * </p> * <ol> * <li>Polling messages from SQS - {@link SqsManager#pollQueue()}.</li> * <li>Parsing message from SQS - {@link SqsManager#parseMessage(List)}.</li> * <li>Deleting messages from SQS - {@link SqsManager#deleteMessageFromQueue(Message, ProgressStatus)}.</li> * <li>Downloading an AWS CloudTrail log file - {@link S3Manager#downloadLog(CloudTrailLog, CloudTrailSource)}.</li> * <li>Processing the AWS CloudTrail log file - {@link EventReader#processSource(CloudTrailSource)}.</li> * </ol> * * @see ProgressStatus for more information. */ public interface ProgressReporter { /** * A callback method that report starting status. * * @param status A {@link ProgressStatus} that represents the status of the current action being performed. * @return An {@link Object} that can be sent to {@link #reportEnd(ProgressStatus, Object)}. */ public Object reportStart(ProgressStatus status); /** * A callback method that report ending status. * * @param status A {@link ProgressStatus} that represents the status of the current action being performed. * @param object An {@link Object} to send; usually the object returned by {{@link #reportStart(ProgressStatus)}}. */ public void reportEnd(ProgressStatus status, Object object); }
5,333
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/interfaces/SourceFilter.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.interfaces; import com.amazonaws.services.cloudtrail.processinglibrary.exceptions.CallbackException; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailSource; /** * SourceFilter is a call back function that hands a CloudTrailSource to user. User can * determinate whether want to process this source. The filter() method is invoked after * polled SQS message from SQS queue and before process events. For performance, CloudTrailSource * is not cloned, caller should not change the content of source. */ public interface SourceFilter{ /** * A callback method used to filter a {@link CloudTrailSource} prior to process. * <p> * For performance, the source object is not a copy; you should only filter the source here, not change its contents. * </p> * @param source The {@link CloudTrailSource} to filter. * @return <code>true</code> if the source should be processed by the {@link SourceFilter}. * @throws CallbackException When error happened during filtering <code>source</code>. CPL will eventually hand this * exception back to <code>ExceptionHandler</code>. */ public boolean filterSource(final CloudTrailSource source) throws CallbackException; }
5,334
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/interfaces/EventFilter.java
/******************************************************************************* * Copyright 2010-2021 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.cloudtrail.processinglibrary.interfaces; import com.amazonaws.services.cloudtrail.processinglibrary.AWSCloudTrailProcessingExecutor; import com.amazonaws.services.cloudtrail.processinglibrary.exceptions.CallbackException; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailEvent; /** * Provides a callback method used by an {@link AWSCloudTrailProcessingExecutor} to determine * whether or not to process a record. * <p> * If {@link #filterEvent(CloudTrailEvent)} returns <code>false</code>, then the event is not sent to the * {@link EventsProcessor} for further processing. * </P> */ public interface EventFilter{ /** * A callback method used to filter a {@link CloudTrailEvent} prior to process. * <p> * For performance, the event object is not a copy; you should only filter the event here, not change its contents. * </P> * @param event The {@link CloudTrailEvent} to filter. * @return <code>true</code> If the event should be processed by the {@link EventsProcessor}. * @throws CallbackException If an error occurs while filtering. */ public boolean filterEvent(CloudTrailEvent event) throws CallbackException; }
5,335
0
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary
Create_ds/aws-cloudtrail-processing-library/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/interfaces/package-info.java
/******************************************************************************* * Copyright 2010-2021 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. ******************************************************************************/ /** * Call back interfaces, implemented by users. */ package com.amazonaws.services.cloudtrail.processinglibrary.interfaces;
5,336
0
Create_ds/jfnr/src/test/java/com/cisco
Create_ds/jfnr/src/test/java/com/cisco/fnr/FNRTest.java
package com.cisco.fnr; /* * jfnr - uses JNA for calling native implementation of libFNR * * jfnr extensions are contributed by Bhanu Prakash Gopularam (bhanprak@cisco.com) * * libFNR - A reference implementation library for FNR encryption mode. * * FNR represents "Flexible Naor and Reingold" mode * FNR is a small domain block cipher to encrypt small domain * objects ( < 128 bits ) like IPv4, MAC, Credit Card numbers etc. * FNR is designed by Sashank Dara (sadara@cisco.com), Scott Fluhrer (sfluhrer@cisco.com) * * jfnr extensions are contributed by Bhanu Prakash Gopularam (bhanprak@cisco.com) * * Copyright (C) 2014 , Cisco Systems Inc. * * This library 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 library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * **/ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidParameterException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.concurrent.Exchanger; public class FNRTest extends TestCase { FNR blockCipher ; SecretKeySpec keySpec ; String password; String tweak; /** * Create the test case * * @param testName name of the test case */ public FNRTest (String testName) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( FNRTest.class ); } public void setUp() throws Exception { super.setUp(); blockCipher = null; password = "password"; // Not for production tweak = "tweak" ; // Not for production try { initKeySpec(); } catch (Exception e) { e.printStackTrace(); } } private void initKeySpec() throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] saltyBytes = FNRUtils.getRandomBytes(20); keySpec = FNRUtils.getSecretKeySpec(password, saltyBytes); } public void tearDown() throws Exception { } /** * Rigourous Test :-) */ public void testString(){ try { System.out.println("Test String"); String plainText = "Hello123"; byte[] plainBytes = plainText.getBytes(); blockCipher = new FNR(keySpec.getEncoded(), tweak, plainText.getBytes().length * Byte.SIZE); byte[] cipherBytes = blockCipher.encrypt(plainBytes); byte[] decryptBytes = blockCipher.decrypt(cipherBytes); if (Arrays.equals(plainBytes, decryptBytes)) { System.out.println("It works for Strings!"); assertTrue(true); } } catch (Exception e) { System.out .println("Something went wrong .. some where for String .." + e.getMessage()); assertTrue(false); } } public void testIPv4(){ try { System.out.println("Test IPv4 Address"); String plainIP = "10.20.30.40"; String decryptedIP, cipherIP; final byte[] intArray = FNRUtils.rankIPAddress(plainIP); blockCipher = new FNR(keySpec.getEncoded(), tweak, intArray.length * Byte.SIZE); byte[] cipherBytes = blockCipher.encrypt(intArray); cipherIP = FNRUtils.deRankIPAddress(cipherBytes); System.out.println("Given IPv4 Address is " + plainIP); System.out.println("Encrypted IPv4 Address is " + cipherIP); byte[] decryptBytes = blockCipher.decrypt(cipherBytes); decryptedIP = FNRUtils.deRankIPAddress(decryptBytes); if (plainIP.equals(decryptedIP)) { System.out.println("It works for IPv4 Address!"); assertTrue(true); } } catch (Exception e) { System.out .println("Something went wrong .. some where for String .." + e.getMessage()); assertTrue(false); } } public void testTweakSize(){ System.out.println("Testing tweak size"); try { tweak ="thisislongtweakeeeeeeee" ; blockCipher = new FNR(keySpec.getEncoded(), tweak, 32); } catch (InvalidParameterException e){ assertFalse("Invalid tweak size", false); } try { tweak ="smalltweak" ; blockCipher = new FNR(keySpec.getEncoded(), tweak, 32); } catch (InvalidParameterException e){ assertFalse("Invalid tweak size", false); } try { tweak ="tweak" ; blockCipher = new FNR(keySpec.getEncoded(), tweak, 32); } catch (InvalidParameterException e){ assertTrue("Invalid tweak size", false); } } public void testBlockSize(){ System.out.println("Testing Block size"); try { blockCipher = new FNR(keySpec.getEncoded(), tweak, 0); } catch (InvalidParameterException e){ assertFalse("Invalid block size", false); } try { blockCipher = new FNR(keySpec.getEncoded(), tweak, 130); } catch (InvalidParameterException e){ assertFalse("Invalid block size", false); } try { blockCipher = new FNR(keySpec.getEncoded(), tweak, 32); } catch (InvalidParameterException e){ assertTrue("Invalid block size", false); } } public void testInputLength(){ System.out.println("Testing Input Lengths in Encryption"); byte[] bytes = new byte[10]; Arrays.fill(bytes, (byte) 0); // blockCipher = new FNR(keySpec.getEncoded(), tweak, 32); // 4 bytes try { blockCipher.encrypt(bytes); } catch (InvalidParameterException e){ assertFalse("Invalid input size", false); } try { blockCipher.decrypt(bytes); } catch (InvalidParameterException e){ assertFalse("Invalid input size", false); } bytes = new byte[4]; Arrays.fill(bytes, (byte) 0); // try { blockCipher.encrypt(bytes); } catch (InvalidParameterException e){ assertTrue("Invalid input size" + e.getMessage(), false); } try { blockCipher.decrypt(bytes); } catch (InvalidParameterException e){ assertTrue("Invalid input size" + e.getMessage(), false); } } public void testKeySize(){ System.out.println("Testing Key Sizes in Encryption"); byte[] plainBytes = new byte[4]; byte[] keyBytes = FNRUtils.getRandomBytes(20); Arrays.fill(plainBytes, (byte) 0); // try { blockCipher = new FNR(keyBytes, tweak, 32); // 4 bytes } catch (InvalidParameterException e){ assertTrue("Invalid key size", true); } password = "password123344555555555"; // Not for production tweak = "tweak" ; // Not for production try { initKeySpec(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { e.printStackTrace(); } try { blockCipher = new FNR(keyBytes, tweak, 32); // 4 bytes } catch (InvalidParameterException e){ assertTrue("Invalid key size", true); } try { blockCipher = new FNR(null, tweak, 32); // 4 bytes } catch (InvalidParameterException e){ assertTrue("Invalid key size", true); } try { keyBytes = FNRUtils.getRandomBytes(16); blockCipher = new FNR(keyBytes, tweak, 32); // 4 bytes } catch (InvalidParameterException e){ assertTrue("Invalid key size", false); } } }
5,337
0
Create_ds/jfnr/src/main/java/com/cisco
Create_ds/jfnr/src/main/java/com/cisco/fnr/FNRLibrary.java
package com.cisco.fnr; /* * jfnr - uses JNA for calling native implementation of libFNR * * jfnr extensions are contributed by Bhanu Prakash Gopularam (bhanprak@cisco.com) * * libFNR - A reference implementation library for FNR encryption mode. * * FNR represents "Flexible Naor and Reingold" mode * FNR is a small domain block cipher to encrypt small domain * objects ( < 128 bits ) like IPv4, MAC, Credit Card numbers etc. * FNR is designed by Sashank Dara (sadara@cisco.com), Scott Fluhrer (sfluhrer@cisco.com) * * Copyright (C) 2014 , Cisco Systems Inc. * * This library 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 library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * **/ import com.sun.jna.IntegerType; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; public interface FNRLibrary extends Library { public static class fnr_expanded_key extends Structure { public int full_bytes; public char final_mask; public int full_elements; public byte final_element_mask; public int num_bits; public size_t size; AES_KEY expanded_aes_key; byte[] aes_key; byte green[]; byte red[] = new byte[1]; @Override protected List getFieldOrder() { return Arrays.asList(new String[]{"final_element_mask", "final_mask", "full_bytes", "full_elements", "num_bits", "size",}); } public static class ByReference extends fnr_expanded_key implements Structure.ByReference { } public static class ByValue extends fnr_expanded_key implements Structure.ByValue { } } public static class fnr_expanded_tweak extends Structure { public static class ByReference extends fnr_expanded_tweak implements Structure.ByReference { } public static class ByValue extends fnr_expanded_tweak implements Structure.ByValue { } public byte[] tweak = new byte[15]; @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "tweak" }); } } public static class AES_KEY extends Structure { public long rd_key[] = new long[4 * (14 + 1)]; int rounds; @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "rd_key", "rounds" }); } public static class ByReference extends AES_KEY implements Structure.ByReference { } public static class ByValue extends AES_KEY implements Structure.ByValue { } } public static class size_t extends IntegerType { public size_t() { this(0); } public size_t(long value) { super(Native.SIZE_T_SIZE, value); } } public void FNR_init(); public fnr_expanded_key.ByReference FNR_expand_key(byte[] aes_key, int aes_key_size, size_t num_bits); public void FNR_expand_tweak( fnr_expanded_tweak.ByReference expanded_tweak, fnr_expanded_key.ByReference key, byte[] tweak, size_t len_tweak); void FNR_encrypt(fnr_expanded_key.ByReference key, fnr_expanded_tweak.ByReference tweak, byte[] plaintext, byte[] ciphertext); void FNR_decrypt(fnr_expanded_key.ByReference key, fnr_expanded_tweak.ByReference tweak, byte[] ciphertext, byte[] plaintext); }
5,338
0
Create_ds/jfnr/src/main/java/com/cisco
Create_ds/jfnr/src/main/java/com/cisco/fnr/FNRUtils.java
package com.cisco.fnr; /* * jfnr - uses JNA for calling native implementation of libFNR * * jfnr extensions are contributed by Bhanu Prakash Gopularam (bhanprak@cisco.com) * * libFNR - A reference implementation library for FNR encryption mode. * * FNR represents "Flexible Naor and Reingold" mode * FNR is a small domain block cipher to encrypt small domain * objects ( < 128 bits ) like IPv4, MAC, Credit Card numbers etc. * FNR is designed by Sashank Dara (sadara@cisco.com), Scott Fluhrer (sfluhrer@cisco.com) * * * Copyright (C) 2014 , Cisco Systems Inc. * * This library 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 library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * **/ import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; public class FNRUtils { public static byte[] rankIPAddress(String ipAddress){ int a,b,c,d ; String[] comps = ipAddress.split("\\."); a = Integer.valueOf( comps[0]); b = Integer.valueOf( comps[1]); c = Integer.valueOf( comps[2]); d = Integer.valueOf( comps[3]); int ip = (a << 24) + (b << 16) + (c << 8) + d; return ByteBuffer.allocate(4).putInt(ip).array(); } public static String deRankIPAddress(byte[] ipBytes){ final int ip = ByteBuffer.wrap(ipBytes).getInt(); return toIPv4String(ip); } public static String toIPv4String (int address) { StringBuilder sb = new StringBuilder(16); for (int ii = 3; ii >= 0; ii--) { sb.append((int) (0xFF & (address >> (8*ii)))); if (ii > 0) sb.append("."); } return sb.toString(); } public static SecretKeySpec getSecretKeySpec(String password, byte[] saltyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException { int pswdIterations = 65536 ; int keySize = 128; // Derive the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec( password.toCharArray(),saltyBytes, pswdIterations, keySize ); SecretKey secretKey = factory.generateSecret(spec); return new SecretKeySpec(secretKey.getEncoded(), "AES"); } public static byte[] getRandomBytes(int count) { // Generate the Salt SecureRandom random = new SecureRandom(); byte[] saltyBytes = new byte[count]; random.nextBytes(saltyBytes); return saltyBytes; } }
5,339
0
Create_ds/jfnr/src/main/java/com/cisco
Create_ds/jfnr/src/main/java/com/cisco/fnr/FNR.java
package com.cisco.fnr; /* * jfnr - uses JNA for calling native implementation of libFNR * * jfnr extensions are contributed by Bhanu Prakash Gopularam (bhanprak@cisco.com) * * libFNR - A reference implementation library for FNR encryption mode. * * FNR represents "Flexible Naor and Reingold" mode * FNR is a small domain block cipher to encrypt small domain * objects ( < 128 bits ) like IPv4, MAC, Credit Card numbers etc. * FNR is designed by Sashank Dara (sadara@cisco.com), Scott Fluhrer (sfluhrer@cisco.com) * * jfnr extensions are contributed by Bhanu Prakash Gopularam (bhanprak@cisco.com) * * Copyright (C) 2014 , Cisco Systems Inc. * * This library 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 library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * **/ import com.sun.jna.Native; import java.security.InvalidParameterException; public class FNR { private int blockSize; private FNRLibrary.fnr_expanded_key.ByReference expanded_key = null; private FNRLibrary.fnr_expanded_tweak.ByReference expanded_tweak = null; private FNRLibrary fnrInstance ; public FNR(byte[] key, String tweak, int blockSize) throws InvalidParameterException{ final int MAX_BLOCK_SIZE = 128; final int KEY_SIZE = 128; final int MAX_TWEAK_LENGTH = 8; final int MIN_BLOCK_SIZE = 16; if( blockSize < MIN_BLOCK_SIZE || blockSize >= MAX_BLOCK_SIZE) throw new InvalidParameterException("Invalid Block Size"); if(tweak.length() > MAX_TWEAK_LENGTH) throw new InvalidParameterException("Invalid Tweak Size"); if(key == null || key.length * 8 != KEY_SIZE) throw new InvalidParameterException("Invalid Key Size"); try { // Load the Library fnrInstance = (FNRLibrary) Native.loadLibrary("fnr", FNRLibrary.class); // 1. FNR Init fnrInstance.FNR_init(); // 2. expand key expanded_key = fnrInstance.FNR_expand_key(key, MAX_BLOCK_SIZE, new FNRLibrary.size_t(blockSize)); // 3. create tweak expanded_tweak = new FNRLibrary.fnr_expanded_tweak.ByReference(); fnrInstance.FNR_expand_tweak(expanded_tweak, expanded_key, tweak.getBytes(), new FNRLibrary.size_t(tweak.length())); } catch (UnsatisfiedLinkError error){ throw new InvalidParameterException("Invalid library file" +error.getMessage()) ; } this.blockSize = blockSize; } public byte[] encrypt(byte[] plainBytes) throws InvalidParameterException { if (plainBytes == null || (plainBytes.length* Byte.SIZE) != blockSize) throw new InvalidParameterException("Invalid Input Length"); byte[] cipherBytes = new byte[plainBytes.length]; fnrInstance.FNR_encrypt(expanded_key, expanded_tweak, plainBytes, cipherBytes); return cipherBytes; } public byte[] decrypt(byte[] cipherBytes) throws InvalidParameterException { if (cipherBytes == null || (cipherBytes.length * Byte.SIZE) != blockSize) throw new InvalidParameterException("Invalid Input Length"); byte decryptedBytes[] = new byte[cipherBytes.length]; fnrInstance.FNR_decrypt(expanded_key, expanded_tweak, cipherBytes, decryptedBytes); return decryptedBytes; } }
5,340
0
Create_ds/amazon-ivs-react-native-player/example/android/app/src/androidTest/java/com/example
Create_ds/amazon-ivs-react-native-player/example/android/app/src/androidTest/java/com/example/amazonivsreactnativeplayer/DetoxTest.java
package com.example.amazonivsreactnativeplayer; import com.wix.detox.Detox; import com.wix.detox.config.DetoxConfig; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; @RunWith(AndroidJUnit4.class) @LargeTest public class DetoxTest { @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class, false, false); @Test public void runDetoxTests() { DetoxConfig detoxConfig = new DetoxConfig(); detoxConfig.idlePolicyConfig.masterTimeoutSec = 90; detoxConfig.idlePolicyConfig.idleResourceTimeoutSec = 60; detoxConfig.rnContextLoadTimeoutSec = (com.amazonaws.ivs.reactnative.player.BuildConfig.DEBUG ? 180 : 60); Detox.runTests(mActivityRule, detoxConfig); } }
5,341
0
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example/amazonivsreactnativeplayer/MainApplication.java
package com.example.amazonivsreactnativeplayer; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.config.ReactFeatureFlags; import com.facebook.react.ReactInstanceManager; import com.facebook.soloader.SoLoader; import com.example.amazonivsreactnativeplayer.newarchitecture.MainApplicationReactNativeHost; import java.lang.reflect.InvocationTargetException; import java.util.List; import com.amazonaws.ivs.reactnative.player.AmazonIvsPackage; import com.facebook.react.bridge.JSIModulePackage; import com.swmansion.reanimated.ReanimatedJSIModulePackage; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for AmazonIvsExample: // packages.add(new MyReactNativePackage()); packages.add(new AmazonIvsPackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } @Override protected JSIModulePackage getJSIModulePackage() { return new ReanimatedJSIModulePackage(); } }; private final ReactNativeHost mNewArchitectureNativeHost = new MainApplicationReactNativeHost(this); @Override public ReactNativeHost getReactNativeHost() { if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { return mNewArchitectureNativeHost; } else { return mReactNativeHost; } } @Override public void onCreate() { super.onCreate(); // If you opted-in for the New Architecture, we enable the TurboModule system ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; SoLoader.init(this, /* native exopackage */ false); } /** * Loads Flipper in React Native templates. * * @param context */ private static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class<?> aClass = Class.forName("com.amazonaws.ivs.reactnative.playerExample.ReactNativeFlipper"); aClass .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }
5,342
0
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example/amazonivsreactnativeplayer/MainActivity.java
package com.example.amazonivsreactnativeplayer; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; import com.facebook.react.ReactRootView; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ @Override protected String getMainComponentName() { return "AmazonIvsExample"; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(null); } /** * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and * you can specify the rendered you wish to use (Fabric or the older renderer). */ @Override protected ReactActivityDelegate createReactActivityDelegate() { return new MainActivityDelegate(this, getMainComponentName()); } public static class MainActivityDelegate extends ReactActivityDelegate { public MainActivityDelegate(ReactActivity activity, String mainComponentName) { super(activity, mainComponentName); } @Override protected ReactRootView createRootView() { ReactRootView reactRootView = new ReactRootView(getContext()); // If you opted-in for the New Architecture, we enable the Fabric Renderer. reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED); return reactRootView; } @Override protected boolean isConcurrentRootEnabled() { // If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18). // More on this on https://reactjs.org/blog/2022/03/29/react-v18.html return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; } } }
5,343
0
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example/amazonivsreactnativeplayer
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example/amazonivsreactnativeplayer/newarchitecture/MainApplicationReactNativeHost.java
package com.example.amazonivsreactnativeplayer.newarchitecture; import android.app.Application; import androidx.annotation.NonNull; import com.facebook.react.PackageList; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.ReactPackageTurboModuleManagerDelegate; import com.facebook.react.bridge.JSIModulePackage; import com.facebook.react.bridge.JSIModuleProvider; import com.facebook.react.bridge.JSIModuleSpec; import com.facebook.react.bridge.JSIModuleType; import com.facebook.react.bridge.JavaScriptContextHolder; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.UIManager; import com.facebook.react.fabric.ComponentFactory; import com.facebook.react.fabric.CoreComponentsRegistry; import com.facebook.react.fabric.FabricJSIModuleProvider; import com.facebook.react.fabric.ReactNativeConfig; import com.facebook.react.uimanager.ViewManagerRegistry; import com.example.amazonivsreactnativeplayer.BuildConfig; import com.example.amazonivsreactnativeplayer.newarchitecture.components.MainComponentRegistry; import com.example.amazonivsreactnativeplayer.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate; import java.util.ArrayList; import java.util.List; /** * A {@link ReactNativeHost} that helps you load everything needed for the New Architecture, both * TurboModule delegates and the Fabric Renderer. * * <p>Please note that this class is used ONLY if you opt-in for the New Architecture (see the * `newArchEnabled` property). Is ignored otherwise. */ public class MainApplicationReactNativeHost extends ReactNativeHost { public MainApplicationReactNativeHost(Application application) { super(application); } @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); // TurboModules must also be loaded here providing a valid TurboReactPackage implementation: // packages.add(new TurboReactPackage() { ... }); // If you have custom Fabric Components, their ViewManagers should also be loaded here // inside a ReactPackage. return packages; } @Override protected String getJSMainModuleName() { return "index"; } @NonNull @Override protected ReactPackageTurboModuleManagerDelegate.Builder getReactPackageTurboModuleManagerDelegateBuilder() { // Here we provide the ReactPackageTurboModuleManagerDelegate Builder. This is necessary // for the new architecture and to use TurboModules correctly. return new MainApplicationTurboModuleManagerDelegate.Builder(); } @Override protected JSIModulePackage getJSIModulePackage() { return new JSIModulePackage() { @Override public List<JSIModuleSpec> getJSIModules( final ReactApplicationContext reactApplicationContext, final JavaScriptContextHolder jsContext) { final List<JSIModuleSpec> specs = new ArrayList<>(); // Here we provide a new JSIModuleSpec that will be responsible of providing the // custom Fabric Components. specs.add( new JSIModuleSpec() { @Override public JSIModuleType getJSIModuleType() { return JSIModuleType.UIManager; } @Override public JSIModuleProvider<UIManager> getJSIModuleProvider() { final ComponentFactory componentFactory = new ComponentFactory(); CoreComponentsRegistry.register(componentFactory); // Here we register a Components Registry. // The one that is generated with the template contains no components // and just provides you the one from React Native core. MainComponentRegistry.register(componentFactory); final ReactInstanceManager reactInstanceManager = getReactInstanceManager(); ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry( reactInstanceManager.getOrCreateViewManagers(reactApplicationContext)); return new FabricJSIModuleProvider( reactApplicationContext, componentFactory, ReactNativeConfig.DEFAULT_CONFIG, viewManagerRegistry); } }); return specs; } }; } }
5,344
0
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example/amazonivsreactnativeplayer/newarchitecture
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example/amazonivsreactnativeplayer/newarchitecture/components/MainComponentRegistry.java
package com.example.amazonivsreactnativeplayer.newarchitecture.components; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.fabric.ComponentFactory; import com.facebook.soloader.SoLoader; /** * Class responsible to load the custom Fabric Components. This class has native methods and needs a * corresponding C++ implementation/header file to work correctly (already placed inside the jni/ * folder for you). * * <p>Please note that this class is used ONLY if you opt-in for the New Architecture (see the * `newArchEnabled` property). Is ignored otherwise. */ @DoNotStrip public class MainComponentRegistry { static { SoLoader.loadLibrary("fabricjni"); } @DoNotStrip private final HybridData mHybridData; @DoNotStrip private native HybridData initHybrid(ComponentFactory componentFactory); @DoNotStrip private MainComponentRegistry(ComponentFactory componentFactory) { mHybridData = initHybrid(componentFactory); } @DoNotStrip public static MainComponentRegistry register(ComponentFactory componentFactory) { return new MainComponentRegistry(componentFactory); } }
5,345
0
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example/amazonivsreactnativeplayer/newarchitecture
Create_ds/amazon-ivs-react-native-player/example/android/app/src/main/java/com/example/amazonivsreactnativeplayer/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java
package com.example.amazonivsreactnativeplayer.newarchitecture.modules; import com.facebook.jni.HybridData; import com.facebook.react.ReactPackage; import com.facebook.react.ReactPackageTurboModuleManagerDelegate; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.soloader.SoLoader; import java.util.List; /** * Class responsible to load the TurboModules. This class has native methods and needs a * corresponding C++ implementation/header file to work correctly (already placed inside the jni/ * folder for you). * * <p>Please note that this class is used ONLY if you opt-in for the New Architecture (see the * `newArchEnabled` property). Is ignored otherwise. */ public class MainApplicationTurboModuleManagerDelegate extends ReactPackageTurboModuleManagerDelegate { private static volatile boolean sIsSoLibraryLoaded; protected MainApplicationTurboModuleManagerDelegate( ReactApplicationContext reactApplicationContext, List<ReactPackage> packages) { super(reactApplicationContext, packages); } protected native HybridData initHybrid(); native boolean canCreateTurboModule(String moduleName); public static class Builder extends ReactPackageTurboModuleManagerDelegate.Builder { protected MainApplicationTurboModuleManagerDelegate build( ReactApplicationContext context, List<ReactPackage> packages) { return new MainApplicationTurboModuleManagerDelegate(context, packages); } } @Override protected synchronized void maybeLoadOtherSoLibraries() { if (!sIsSoLibraryLoaded) { // If you change the name of your application .so file in the Android.mk file, // make sure you update the name here as well. SoLoader.loadLibrary("example_amazonivsreactnativeplayer_appmodules"); sIsSoLibraryLoaded = true; } } }
5,346
0
Create_ds/amazon-ivs-react-native-player/example/android/app/src/debug/java/com/example
Create_ds/amazon-ivs-react-native-player/example/android/app/src/debug/java/com/example/amazonivsreactnativeplayer/ReactNativeFlipper.java
/** * Copyright (c) Facebook, Inc. and its affiliates. * * <p>This source code is licensed under the MIT license found in the LICENSE file in the root * directory of this source tree. */ package com.example.amazonivsreactnativeplayer; import android.content.Context; import com.facebook.flipper.android.AndroidFlipperClient; import com.facebook.flipper.android.utils.FlipperUtils; import com.facebook.flipper.core.FlipperClient; import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; import com.facebook.flipper.plugins.inspector.DescriptorMapping; import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; import com.facebook.flipper.plugins.react.ReactFlipperPlugin; import com.facebook.react.ReactInstanceEventListener; import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; import com.facebook.react.ReactInstanceManager; import com.facebook.react.bridge.ReactContext; import com.facebook.react.modules.network.NetworkingModule; import okhttp3.OkHttpClient; public class ReactNativeFlipper { public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { if (FlipperUtils.shouldEnableFlipper(context)) { final FlipperClient client = AndroidFlipperClient.getInstance(context); client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); client.addPlugin(new ReactFlipperPlugin()); client.addPlugin(new DatabasesFlipperPlugin(context)); client.addPlugin(new SharedPreferencesFlipperPlugin(context)); client.addPlugin(CrashReporterPlugin.getInstance()); NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); NetworkingModule.setCustomClientBuilder( new NetworkingModule.CustomClientBuilder() { @Override public void apply(OkHttpClient.Builder builder) { builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); } }); client.addPlugin(networkFlipperPlugin); client.start(); // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized // Hence we run if after all native modules have been initialized ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); if (reactContext == null) { reactInstanceManager.addReactInstanceEventListener( new ReactInstanceEventListener() { @Override public void onReactContextInitialized(ReactContext reactContext) { reactInstanceManager.removeReactInstanceEventListener(this); reactContext.runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { client.addPlugin(new FrescoFlipperPlugin()); } }); } }); } else { client.addPlugin(new FrescoFlipperPlugin()); } } } }
5,347
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/SyntheticSourceJob.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJob; import io.mantisrx.runtime.MantisJobProvider; import io.mantisrx.runtime.executor.LocalJobExecutorNetworked; import io.mantisrx.sourcejob.synthetic.core.TaggedData; import io.mantisrx.sourcejob.synthetic.sink.QueryRequestPostProcessor; import io.mantisrx.sourcejob.synthetic.sink.QueryRequestPreProcessor; import io.mantisrx.sourcejob.synthetic.sink.TaggedDataSourceSink; import io.mantisrx.sourcejob.synthetic.source.SyntheticSource; import io.mantisrx.sourcejob.synthetic.stage.TaggingStage; /** * A sample queryable source job that generates synthetic request events. * Clients connect to this job via the Sink port using an MQL expression. The job then sends only the data * that matches the query to the client. The client can be another Mantis Job or a user manually running a GET request. * * Run this sample by executing the main method of this class. Then look for the SSE port where the output of this job * will be available for streaming. E.g Serving modern HTTP SSE server sink on port: 8299 * Usage: curl "localhost:<sseport>?clientId=<myId>&subscriptionId=<someid>&criterion=<valid mql query> * * E.g <code>curl "localhost:8498?subscriptionId=nj&criterion=select%20country%20from%20stream%20where%20status%3D%3D500&clientId=nj2"</code> * Here the user is submitted an MQL query select country from stream where status==500. */ public class SyntheticSourceJob extends MantisJobProvider<TaggedData> { @Override public Job<TaggedData> getJobInstance() { return MantisJob // synthetic source generates random RequestEvents. .source(new SyntheticSource()) // Tags events with queries that match .stage(new TaggingStage(), TaggingStage.config()) // A custom sink that processes query parameters to register and deregister MQL queries .sink(new TaggedDataSourceSink(new QueryRequestPreProcessor(), new QueryRequestPostProcessor())) // required parameters .create(); } public static void main(String[] args) { LocalJobExecutorNetworked.execute(new SyntheticSourceJob().getJobInstance()); } }
5,348
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/core/MQL.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.core; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import io.mantisrx.mql.jvm.core.Query; import io.mantisrx.mql.shaded.clojure.java.api.Clojure; import io.mantisrx.mql.shaded.clojure.lang.IFn; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Func1; /** * The MQL class provides a Java/Scala friendly static interface to MQL functionality which is written in Clojure. * This class provides a few pieces of functionality; * - It wraps the Clojure interop so that the user interacts with typed methods via the static interface. * - It provides methods for accessing individual bits of query functionality, allowing interesting uses * such as aggregator-mql which uses these components to implement the query in a horizontally scalable / distributed * fashion on Mantis. * - It functions as an Rx Transformer of MantisServerSentEvent to MQLResult allowing a user to inline all MQL * functionality quickly as such: `myObservable.compose(MQL.parse(myQuery));` */ public class MQL { // // Clojure Interop // private static IFn require = Clojure.var("io.mantisrx.mql.shaded.clojure.core", "require"); static { require.invoke(Clojure.read("io.mantisrx.mql.jvm.interfaces.core")); require.invoke(Clojure.read("io.mantisrx.mql.jvm.interfaces.server")); } private static IFn cljMakeQuery = Clojure.var("io.mantisrx.mql.jvm.interfaces.server", "make-query"); private static IFn cljSuperset = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "queries->superset-projection"); private static IFn parser = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "parser"); private static IFn parses = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "parses?"); private static IFn getParseError = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "get-parse-error"); private static IFn queryToGroupByFn = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->groupby"); private static IFn queryToHavingPred = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->having-pred"); private static IFn queryToOrderBy = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->orderby"); private static IFn queryToLimit = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->limit"); private static IFn queryToExtrapolationFn = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->extrapolator"); private static IFn queryToAggregateFn = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "agg-query->projection"); private static IFn queryToWindow = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->window"); private static Logger logger = LoggerFactory.getLogger(MQL.class); private static ConcurrentHashMap<HashSet<Query>, IFn> superSetProjectorCache = new ConcurrentHashMap<>(); private final String query; private final boolean threadingEnabled; private final Optional<String> sourceJobName; public static void init() { logger.info("Initializing MQL runtime."); } // // Constructors and Static Factory Methods // public MQL(String query, boolean threadingEnabled) { if (query == null) { throw new IllegalArgumentException("MQL cannot be used as an operator with a null query."); } this.query = transformLegacyQuery(query); if (!parses(query)) { throw new IllegalArgumentException(getParseError(query)); } this.threadingEnabled = threadingEnabled; this.sourceJobName = Optional.empty(); } public MQL(String query, String sourceJobName) { if (query == null) { throw new IllegalArgumentException("MQL cannot be used as an operator with a null query."); } this.query = transformLegacyQuery(query); if (!parses(query)) { throw new IllegalArgumentException(getParseError(query)); } this.threadingEnabled = false; this.sourceJobName = Optional.ofNullable(sourceJobName); } public static MQL parse(String query) { return new MQL(query, false); } public static MQL parse(String query, boolean threadingEnabled) { return new MQL(query, threadingEnabled); } public static MQL parse(String query, String sourceName) { return new MQL(query, sourceName); } // // Source Job Integration // /** * Constructs an object implementing the Query interface. * This includes functions; * matches (Map<String, Object>>) -> Boolean * Returns true iff the data contained within the map parameter satisfies the query's WHERE clause. * project (Map<String, Object>>) -> Map<String, Object>> * Returns the provided map in accordance with the SELECT clause of the query. * sample (Map<String, Object>>) -> Boolean * Returns true if the data should be sampled, this function is a tautology if no SAMPLE clause is provided. * * @param subscriptionId The ID representing the subscription. * @param query The (valid) MQL query to parse. * * @return An object implementing the Query interface. */ public static Query makeQuery(String subscriptionId, String query) { /* if (!parses(query)) { String error = getParseError(query); logger.error("Failed to parse query [" + query + "]\nError: " + error + "."); throw new IllegalArgumentException(error); } */ return (Query) cljMakeQuery.invoke(subscriptionId, query.trim()); } @SuppressWarnings("unchecked") private static IFn computeSuperSetProjector(HashSet<Query> queries) { ArrayList<String> qs = new ArrayList<>(queries.size()); for (Query query : queries) { qs.add(query.getRawQuery()); } return (IFn) cljSuperset.invoke(new ArrayList(qs)); } /** * Projects a single Map<String, Object> which contains a superset of all fields for the provided queries. * This is useful in use cases such as the mantis-realtime-events library in which we desire to minimize the data * egressed off box. This should minimize JSON serialization time as well as network bandwidth used to transmit * the events. * <p> * NOTE: This function caches the projectors for performance reasons, this has implications for memory usage as each * combination of queries results in a new cached function. In practice this has had little impact for <= 100 * queries. * * @param queries A Collection of Query objects generated using #makeQuery(String subscriptionId, String query). * @param datum A Map representing the input event to be projected. * * @return A Map representing the union (superset) of all fields required for processing all queries passed in. */ @SuppressWarnings("unchecked") public static Map<String, Object> projectSuperSet(Collection<Query> queries, Map<String, Object> datum) { IFn superSetProjector = superSetProjectorCache.computeIfAbsent(new HashSet<Query>(queries), (qs) -> { return computeSuperSetProjector(qs); }); return (Map<String, Object>) superSetProjector.invoke(datum); } // // Partial Query Functionality // public static Func1<Map<String, Object>, Object> getGroupByFn(String query) { IFn func = (IFn) queryToGroupByFn.invoke(query); return func::invoke; } @SuppressWarnings("unchecked") public static Func1<Map<String, Object>, Boolean> getHavingPredicate(String query) { IFn func = (IFn) queryToHavingPred.invoke(query); return (datum) -> (Boolean) func.invoke(datum); } @SuppressWarnings("unchecked") public static Func1<Observable<Map<String, Object>>, Observable<Map<String, Object>>> getAggregateFn(String query) { IFn func = (IFn) queryToAggregateFn.invoke(query); return (obs) -> (Observable<Map<String, Object>>) func.invoke(obs); } @SuppressWarnings("unchecked") public static Func1<Map<String, Object>, Map<String, Object>> getExtrapolationFn(String query) { IFn func = (IFn) queryToExtrapolationFn.invoke(query); return (datum) -> (Map<String, Object>) func.invoke(datum); } @SuppressWarnings("unchecked") public static Func1<Observable<Map<String, Object>>, Observable<Map<String, Object>>> getOrderBy(String query) { IFn func = (IFn) queryToOrderBy.invoke(query); return obs -> (Observable<Map<String, Object>>) func.invoke(obs); } // public static List<Long> getWindow(String query) { // clojure.lang.PersistentVector result = (clojure.lang.PersistentVector)queryToWindow.invoke(query); // Long window = (Long)result.nth(0); // Long shift = (Long)result.nth(1); // return Arrays.asList(window, shift); // } public static Long getLimit(String query) { return (Long) queryToLimit.invoke(query); } // // Helper Functions // /** * A predicate which indicates whether or not the MQL parser considers query to be a valid query. * * @param query A String representing the MQL query. * * @return A boolean indicating whether or not the query successfully parses. */ public static Boolean parses(String query) { return (Boolean) parses.invoke(query); } /** * A convenience function allowing a caller to determine what went wrong if a call to #parses(String query) returns * false. * * @param query A String representing the MQL query. * * @return A String representing the parse error for an MQL query, null if no parse error occurred. */ public static String getParseError(String query) { return (String) getParseError.invoke(query); } /** * A helper which converts bare true/false queries to MQL. * * @param criterion A Mantis Query (old query language) query. * * @return A valid MQL query string assuming the input was valid. */ public static String transformLegacyQuery(String criterion) { return criterion.toLowerCase().equals("true") ? "select * where true" : criterion.toLowerCase().equals("false") ? "select * where false" : criterion; } public static void main(String[] args) { System.out.println(MQL.makeQuery("abc", "select * from stream where true")); } }
5,349
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/core/TaggedData.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.core; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.common.codec.Codec; import io.mantisrx.runtime.codec.JsonType; public class TaggedData implements JsonType { private final Set<String> matchedClients = new HashSet<String>(); private Map<String, Object> payLoad; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public TaggedData(@JsonProperty("data") Map<String, Object> data) { this.payLoad = data; } public Set<String> getMatchedClients() { return matchedClients; } public boolean matchesClient(String clientId) { return matchedClients.contains(clientId); } public void addMatchedClient(String clientId) { matchedClients.add(clientId); } public Map<String, Object> getPayload() { return this.payLoad; } public void setPayload(Map<String, Object> newPayload) { this.payLoad = newPayload; } public static Codec<TaggedData> taggedDataCodec() { return new Codec<TaggedData>() { @Override public TaggedData decode(byte[] bytes) { return new TaggedData(new HashMap<>()); } @Override public byte[] encode(final TaggedData value) { return new byte[128]; } }; } }
5,350
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/core/MQLQueryManager.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.core; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import io.mantisrx.mql.jvm.core.Query; public class MQLQueryManager { static class LazyHolder { private static final MQLQueryManager INSTANCE = new MQLQueryManager(); } private ConcurrentHashMap<String, Query> queries = new ConcurrentHashMap<>(); public static MQLQueryManager getInstance() { return LazyHolder.INSTANCE; } private MQLQueryManager() { } public void registerQuery(String id, String query) { query = MQL.transformLegacyQuery(query); Query q = MQL.makeQuery(id, query); queries.put(id, q); } public void deregisterQuery(String id) { queries.remove(id); } public Collection<Query> getRegisteredQueries() { return queries.values(); } public void clear() { queries.clear(); } public static void main(String[] args) throws Exception { MQLQueryManager qm = getInstance(); String query = "SELECT * WHERE true SAMPLE {\"strategy\":\"RANDOM\",\"threshold\":1}"; qm.registerQuery("fake2", query); System.out.println(MQL.parses(MQL.transformLegacyQuery(query))); System.out.println(MQL.getParseError(MQL.transformLegacyQuery(query))); System.out.println(qm.getRegisteredQueries()); } }
5,351
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/proto/RequestEvent.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.proto; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import io.mantisrx.common.codec.Codec; import lombok.Builder; import lombok.Data; /** * Represents a Request Event a service may receive. */ @Data @Builder public class RequestEvent { private static final ObjectMapper mapper = new ObjectMapper(); private static final ObjectReader requestEventReader = mapper.readerFor(RequestEvent.class); private final String userId; private final String uri; private final int status; private final String country; private final String deviceType; public Map<String,Object> toMap() { Map<String,Object> data = new HashMap<>(); data.put("userId", userId); data.put("uri", uri); data.put("status", status); data.put("country", country); data.put("deviceType", deviceType); return data; } public String toJsonString() { try { return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { e.printStackTrace(); return null; } } /** * The codec defines how this class should be serialized before transporting across network. * @return */ public static Codec<RequestEvent> requestEventCodec() { return new Codec<RequestEvent>() { @Override public RequestEvent decode(byte[] bytes) { try { return requestEventReader.readValue(bytes); } catch (IOException e) { throw new RuntimeException(e); } } @Override public byte[] encode(final RequestEvent value) { try { return mapper.writeValueAsBytes(value); } catch (Exception e) { throw new RuntimeException(e); } } }; } }
5,352
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/source/SyntheticSource.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.source; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.parameter.ParameterDefinition; import io.mantisrx.runtime.parameter.type.IntParameter; import io.mantisrx.runtime.parameter.validator.Validators; import io.mantisrx.runtime.source.Index; import io.mantisrx.runtime.source.Source; import io.mantisrx.sourcejob.synthetic.proto.RequestEvent; import lombok.extern.slf4j.Slf4j; import net.andreinc.mockneat.MockNeat; import rx.Observable; /** * Generates random set of RequestEvents at a preconfigured interval. */ @Slf4j public class SyntheticSource implements Source<String> { private static final String DATA_GENERATION_RATE_MSEC_PARAM = "dataGenerationRate"; private MockNeat mockDataGenerator; private int dataGenerateRateMsec = 250; @Override public Observable<Observable<String>> call(Context context, Index index) { return Observable.just(Observable .interval(dataGenerateRateMsec, TimeUnit.MILLISECONDS) .map((tick) -> generateEvent()) .map((event) -> event.toJsonString()) .filter(Objects::nonNull) .doOnNext((event) -> { log.debug("Generated Event {}", event); })); } @Override public void init(Context context, Index index) { mockDataGenerator = MockNeat.threadLocal(); dataGenerateRateMsec = (int)context.getParameters().get(DATA_GENERATION_RATE_MSEC_PARAM,250); } @Override public List<ParameterDefinition<?>> getParameters() { List<ParameterDefinition<?>> params = new ArrayList<>(); params.add(new IntParameter() .name(DATA_GENERATION_RATE_MSEC_PARAM) .description("Rate at which to generate data") .validator(Validators.range(100,1000000)) .defaultValue(250) .build()); return params; } private RequestEvent generateEvent() { String path = mockDataGenerator.probabilites(String.class) .add(0.1, "/login") .add(0.2, "/genre/horror") .add(0.5, "/genre/comedy") .add(0.2, "/mylist") .get(); String deviceType = mockDataGenerator.probabilites(String.class) .add(0.1, "ps4") .add(0.1, "xbox") .add(0.2, "browser") .add(0.3, "ios") .add(0.3, "android") .get(); String userId = mockDataGenerator.strings().size(10).get(); int status = mockDataGenerator.probabilites(Integer.class) .add(0.1,500) .add(0.7,200) .add(0.2,500) .get(); String country = mockDataGenerator.countries().names().get(); return RequestEvent.builder() .status(status) .uri(path) .country(country) .userId(userId) .deviceType(deviceType) .build(); } }
5,353
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/sink/QueryRequestPostProcessor.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.sink; import static com.mantisrx.common.utils.MantisSourceJobConstants.CRITERION_PARAM_NAME; import static com.mantisrx.common.utils.MantisSourceJobConstants.SUBSCRIPTION_ID_PARAM_NAME; import java.util.List; import java.util.Map; import io.mantisrx.runtime.Context; import lombok.extern.slf4j.Slf4j; import org.apache.log4j.Logger; import rx.functions.Func2; /** * This is a callback that is invoked after a client connected to the sink of this job disconnects. This is used * to cleanup the queries the client had registered. */ @Slf4j public class QueryRequestPostProcessor implements Func2<Map<String, List<String>>, Context, Void> { public QueryRequestPostProcessor() { } @Override public Void call(Map<String, List<String>> queryParams, Context context) { log.info("RequestPostProcessor:queryParams: " + queryParams); if (queryParams != null) { if (queryParams.containsKey(SUBSCRIPTION_ID_PARAM_NAME) && queryParams.containsKey(CRITERION_PARAM_NAME)) { final String subId = queryParams.get(SUBSCRIPTION_ID_PARAM_NAME).get(0); final String query = queryParams.get(CRITERION_PARAM_NAME).get(0); final String clientId = queryParams.get("clientId").get(0); if (subId != null && query != null) { try { if (clientId != null && !clientId.isEmpty()) { deregisterQuery(clientId + "_" + subId); } else { deregisterQuery(subId); } } catch (Throwable t) { log.error("Error propagating unsubscription notification", t); } } } } return null; } private void deregisterQuery(String subId) { QueryRefCountMap.INSTANCE.removeQuery(subId); } }
5,354
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/sink/TaggedDataSourceSink.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.sink; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.PortRequest; import io.mantisrx.runtime.sink.ServerSentEventsSink; import io.mantisrx.runtime.sink.Sink; import io.mantisrx.runtime.sink.predicate.Predicate; import io.mantisrx.sourcejob.synthetic.core.TaggedData; import lombok.extern.slf4j.Slf4j; import rx.Observable; import rx.functions.Func2; /** * A custom sink that allows clients to connect to this job with an MQL expression and in turn receive events * matching this expression. */ @Slf4j public class TaggedDataSourceSink implements Sink<TaggedData> { private Func2<Map<String, List<String>>, Context, Void> preProcessor = new NoOpProcessor(); private Func2<Map<String, List<String>>, Context, Void> postProcessor = new NoOpProcessor(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); static class NoOpProcessor implements Func2<Map<String, List<String>>, Context, Void> { @Override public Void call(Map<String, List<String>> t1, Context t2) { return null; } } public TaggedDataSourceSink() { } public TaggedDataSourceSink(Func2<Map<String, List<String>>, Context, Void> preProcessor, Func2<Map<String, List<String>>, Context, Void> postProcessor) { this.postProcessor = postProcessor; this.preProcessor = preProcessor; } @Override public void call(Context context, PortRequest portRequest, Observable<TaggedData> observable) { observable = observable .filter((t1) -> !t1.getPayload().isEmpty()); ServerSentEventsSink<TaggedData> sink = new ServerSentEventsSink.Builder<TaggedData>() .withEncoder((data) -> { try { return OBJECT_MAPPER.writeValueAsString(data.getPayload()); } catch (JsonProcessingException e) { e.printStackTrace(); return "{\"error\":" + e.getMessage() + "}"; } }) .withPredicate(new Predicate<>("description", new TaggedEventFilter())) .withRequestPreprocessor(preProcessor) .withRequestPostprocessor(postProcessor) .build(); observable.subscribe(); sink.call(context, portRequest, observable); } }
5,355
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/sink/TaggedEventFilter.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.sink; import static com.mantisrx.common.utils.MantisSourceJobConstants.CLIENT_ID_PARAMETER_NAME; import static com.mantisrx.common.utils.MantisSourceJobConstants.SUBSCRIPTION_ID_PARAM_NAME; import java.util.ArrayList; import java.util.List; import java.util.Map; import io.mantisrx.sourcejob.synthetic.core.TaggedData; import lombok.extern.slf4j.Slf4j; import rx.functions.Func1; /** * This is a predicate that decides what data to send to the downstream client. The data is tagged with the clientId * and subscriptionId of the intended recipient. */ @Slf4j public class TaggedEventFilter implements Func1<Map<String, List<String>>, Func1<TaggedData, Boolean>> { @Override public Func1<TaggedData, Boolean> call(Map<String, List<String>> parameters) { Func1<TaggedData, Boolean> filter = t1 -> true; if (parameters != null) { if (parameters.containsKey(SUBSCRIPTION_ID_PARAM_NAME)) { String subId = parameters.get(SUBSCRIPTION_ID_PARAM_NAME).get(0); String clientId = parameters.get(CLIENT_ID_PARAMETER_NAME).get(0); List<String> terms = new ArrayList<String>(); if (clientId != null && !clientId.isEmpty()) { terms.add(clientId + "_" + subId); } else { terms.add(subId); } filter = new SourceEventFilter(terms); } return filter; } return filter; } private static class SourceEventFilter implements Func1<TaggedData, Boolean> { private String jobId = "UNKNOWN"; private String jobName = "UNKNOWN"; private List<String> terms; SourceEventFilter(List<String> terms) { this.terms = terms; String jId = System.getenv("JOB_ID"); if (jId != null && !jId.isEmpty()) { jobId = jId; } String jName = System.getenv("JOB_NAME"); if (jName != null && !jName.isEmpty()) { jobName = jName; } log.info("Created SourceEventFilter! for subId " + terms.toString() + " in Job : " + jobName + " with Id " + jobId); } @Override public Boolean call(TaggedData data) { boolean match = true; for (String term : terms) { if (!data.matchesClient(term)) { match = false; break; } } return match; } } }
5,356
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/sink/QueryRequestPreProcessor.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.sink; import static com.mantisrx.common.utils.MantisSourceJobConstants.CRITERION_PARAM_NAME; import static com.mantisrx.common.utils.MantisSourceJobConstants.SUBSCRIPTION_ID_PARAM_NAME; import java.util.List; import java.util.Map; import io.mantisrx.runtime.Context; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func2; /** * This is a callback that is invoked when a new client connects to this sink of this job. * The callback is used to extract useful query parameters the user may have set on the GET request such as * the clientId, subscriptionId and the criterion. * The clientId identifies a group of connections belonging to the same consumer. Data is sent round-robin amongst * all clients with the same clientId * The subscriptionId tracks this particular client. * The criterion is a valid MQL query. It indicates what data this client is interested in. */ @Slf4j public class QueryRequestPreProcessor implements Func2<Map<String, List<String>>, Context, Void> { public QueryRequestPreProcessor() { } @Override public Void call(Map<String, List<String>> queryParams, Context context) { log.info("QueryRequestPreProcessor:queryParams: {}", queryParams); if (queryParams != null) { if (queryParams.containsKey(SUBSCRIPTION_ID_PARAM_NAME) && queryParams.containsKey(CRITERION_PARAM_NAME)) { final String subId = queryParams.get(SUBSCRIPTION_ID_PARAM_NAME).get(0); final String query = queryParams.get(CRITERION_PARAM_NAME).get(0); final String clientId = queryParams.get("clientId").get(0); if (subId != null && query != null) { try { log.info("Registering query {}", query); if (clientId != null && !clientId.isEmpty()) { registerQuery(clientId + "_" + subId, query); } else { registerQuery(subId, query); } } catch (Throwable t) { log.error("Error registering query", t); } } } } return null; } private static synchronized void registerQuery(String subId, String query) { QueryRefCountMap.INSTANCE.addQuery(subId, query); } }
5,357
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/sink/QueryRefCountMap.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.sink; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import io.mantisrx.sourcejob.synthetic.core.MQLQueryManager; import lombok.extern.slf4j.Slf4j; /** * This class keeps track of number of clients that have the exact same query registered for * deduplication purposes. * When all references to a query are gone the query is deregistered. */ @Slf4j final class QueryRefCountMap { public static final QueryRefCountMap INSTANCE = new QueryRefCountMap(); private final ConcurrentHashMap<String, AtomicInteger> refCntMap = new ConcurrentHashMap<>(); private QueryRefCountMap() { } void addQuery(String subId, String query) { log.info("adding query " + subId + " query " + query); if (refCntMap.containsKey(subId)) { int newVal = refCntMap.get(subId).incrementAndGet(); log.info("query exists already incrementing refcnt to " + newVal); } else { MQLQueryManager.getInstance().registerQuery(subId, query); refCntMap.putIfAbsent(subId, new AtomicInteger(1)); log.info("new query registering it"); } } void removeQuery(String subId) { if (refCntMap.containsKey(subId)) { AtomicInteger refCnt = refCntMap.get(subId); int currVal = refCnt.decrementAndGet(); if (currVal == 0) { MQLQueryManager.getInstance().deregisterQuery(subId); refCntMap.remove(subId); log.info("All references to query are gone removing query"); } else { log.info("References to query still exist. decrementing refcnt to " + currVal); } } else { log.warn("No query with subscriptionId " + subId); } } /** * For testing * * @param subId * * @return */ int getQueryRefCount(String subId) { if (refCntMap.containsKey(subId)) { return refCntMap.get(subId).get(); } else { return 0; } } }
5,358
0
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis-examples/synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/stage/TaggingStage.java
/* * Copyright 2019 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 io.mantisrx.sourcejob.synthetic.stage; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import com.mantisrx.common.utils.JsonUtility; import io.mantisrx.common.codec.Codec; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.spectator.MetricGroupId; import io.mantisrx.mql.jvm.core.Query; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.computation.ScalarComputation; import io.mantisrx.sourcejob.synthetic.core.MQLQueryManager; import io.mantisrx.sourcejob.synthetic.core.TaggedData; import lombok.extern.slf4j.Slf4j; import rx.Observable; /** * Tags incoming events with ids of queries that evaluate to true against the data. * * Each event is first transformed into a Map, next each query from the list of Registered MQL queries * is applied against the event. The event is tagged with the ids of queries that matched. * */ @Slf4j public class TaggingStage implements ScalarComputation<String, TaggedData> { public static final String MANTIS_META_SOURCE_NAME = "mantis.meta.sourceName"; public static final String MANTIS_META_SOURCE_TIMESTAMP = "mantis.meta.timestamp"; public static final String MANTIS_QUERY_COUNTER = "mantis_query_out"; public static final String MQL_COUNTER = "mql_out"; public static final String MQL_FAILURE = "mql_failure"; public static final String MQL_CLASSLOADER_ERROR = "mql_classloader_error"; public static final String SYNTHETIC_REQUEST_SOURCE = "SyntheticRequestSource"; private AtomicBoolean errorLogged = new AtomicBoolean(false); @Override public Observable<TaggedData> call(Context context, Observable<String> dataO) { return dataO .map((event) -> { try { return JsonUtility.jsonToMap(event); } catch (Exception e) { log.error(e.getMessage()); return null; } }) .filter(Objects::nonNull) .flatMapIterable(d -> tagData(d, context)); } @Override public void init(Context context) { context.getMetricsRegistry().registerAndGet(new Metrics.Builder() .name("mql") .addCounter(MQL_COUNTER) .addCounter(MQL_FAILURE) .addCounter(MQL_CLASSLOADER_ERROR) .addCounter(MANTIS_QUERY_COUNTER).build()); } private List<TaggedData> tagData(Map<String, Object> d, Context context) { List<TaggedData> taggedDataList = new ArrayList<>(); Metrics metrics = context.getMetricsRegistry().getMetric(new MetricGroupId("mql")); Collection<Query> queries = MQLQueryManager.getInstance().getRegisteredQueries(); Iterator<Query> it = queries.iterator(); while (it.hasNext()) { Query query = it.next(); try { if (query.matches(d)) { Map<String, Object> projected = query.project(d); projected.put(MANTIS_META_SOURCE_NAME, SYNTHETIC_REQUEST_SOURCE); projected.put(MANTIS_META_SOURCE_TIMESTAMP, System.currentTimeMillis()); TaggedData tg = new TaggedData(projected); tg.addMatchedClient(query.getSubscriptionId()); taggedDataList.add(tg); } } catch (Exception ex) { if (ex instanceof ClassNotFoundException) { log.error("Error loading MQL: " + ex.getMessage()); ex.printStackTrace(); metrics.getCounter(MQL_CLASSLOADER_ERROR).increment(); } else { ex.printStackTrace(); metrics.getCounter(MQL_FAILURE).increment(); log.error("MQL Error: " + ex.getMessage()); log.error("MQL Query: " + query.getRawQuery()); log.error("MQL Datum: " + d); } } catch (Error e) { metrics.getCounter(MQL_FAILURE).increment(); if (!errorLogged.get()) { log.error("caught Error when processing MQL {} on {}", query.getRawQuery(), d.toString(), e); errorLogged.set(true); } } } return taggedDataList; } public static ScalarToScalar.Config<String, TaggedData> config() { return new ScalarToScalar.Config<String, TaggedData>() .concurrentInput() .codec(TaggingStage.taggedDataCodec()); } public static Codec<TaggedData> taggedDataCodec() { return new Codec<TaggedData>() { @Override public TaggedData decode(byte[] bytes) { return new TaggedData(new HashMap<>()); } @Override public byte[] encode(final TaggedData value) { return new byte[128]; } }; } }
5,359
0
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/servlet/HelloServlet.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample.web.servlet; import java.io.IOException; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.netflix.mantis.examples.mantispublishsample.web.service.MyService; /** * A simple servlet that looks for the existence of a name parameter in the request and responds * with a Hello message. */ @Singleton public class HelloServlet extends HttpServlet { @Inject MyService myService; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); if (name == null) name = "Universe"; String result = myService.hello(name); response.getWriter().print(result); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); if (name == null) name = "World"; request.setAttribute("user", name); request.getRequestDispatcher("response.jsp").forward(request, response); } }
5,360
0
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/config/DefaultGuiceServletConfig.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample.web.config; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import com.google.inject.servlet.ServletModule; import com.netflix.archaius.guice.ArchaiusModule; import com.netflix.mantis.examples.mantispublishsample.web.filter.CaptureRequestEventFilter; import com.netflix.mantis.examples.mantispublishsample.web.service.MyService; import com.netflix.mantis.examples.mantispublishsample.web.service.MyServiceImpl; import com.netflix.mantis.examples.mantispublishsample.web.servlet.HelloServlet; import com.netflix.spectator.nflx.SpectatorModule; import io.mantisrx.publish.netty.guice.MantisRealtimeEventsPublishModule; /** * Wire up the servlets, filters and other modules. */ public class DefaultGuiceServletConfig extends GuiceServletContextListener { @Override protected Injector getInjector() { return Guice.createInjector( new ArchaiusModule(), new MantisRealtimeEventsPublishModule(), new SpectatorModule(), new ServletModule() { @Override protected void configureServlets() { filter("/*").through(CaptureRequestEventFilter.class); serve("/hello").with(HelloServlet.class); bind(MyService.class).to(MyServiceImpl.class); } } ); } }
5,361
0
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/filter/CaptureRequestEventFilter.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample.web.filter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import io.mantisrx.publish.api.Event; import io.mantisrx.publish.api.EventPublisher; import io.mantisrx.publish.api.PublishStatus; import lombok.extern.slf4j.Slf4j; /** * A sample filter that captures Request and Response headers and sends them to * Mantis using the mantis-publish library. */ @Slf4j @Singleton public class CaptureRequestEventFilter implements Filter { private static final String RESPONSE_HEADER_PREFIX = "response.header."; private static final String REQUEST_HEADER_PREFIX = "request.header."; private static final String VALUE_SEPARATOR = ","; @Inject private EventPublisher publisher; @Override public void init(FilterConfig filterConfig) { log.info("Capture Request data filter inited"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) servletRequest; final HttpServletResponse res = (HttpServletResponse)servletResponse; log.debug("In do filter"); final long startMillis = System.currentTimeMillis(); // Add a wrapper around the Response object to capture headers. final ResponseSpy responseSpy = new ResponseSpy(res); // Send request down the filter chain filterChain.doFilter(servletRequest,responseSpy); // request is complete now gather all the request data and send to mantis. processPostFilter(startMillis, req, responseSpy); } /** * Invoked after the request has been completed. Used to gather all the request and response headers * associated with this request and publish to mantis. * @param startMillis The time processing began for this request. * @param req The servlet request object * @param responseSpy The spy servlet response. */ private void processPostFilter(long startMillis, HttpServletRequest req, ResponseSpy responseSpy) { try { Map<String, Object> event = new HashMap<>(); postProcess(req, responseSpy,event); Event rEvent = new Event(event); final long duration = System.currentTimeMillis() - startMillis; rEvent.set("duration", duration); log.info("sending event {} to stream {}", rEvent); CompletionStage<PublishStatus> sendResult = publisher.publish(rEvent); sendResult.whenCompleteAsync((status,throwable) -> { log.info("Filter send event status=> {}", status); }); } catch (Exception e) { log.error("failed to process event", e); } } /** * Captures the request and response headers associated with this request. * @param httpServletRequest * @param responseSpy * @param event */ private void postProcess(HttpServletRequest httpServletRequest, ResponseSpy responseSpy, Map<String,Object> event) { try { int rdm = ThreadLocalRandom.current().nextInt(); if(rdm < 0) { rdm = rdm * (-1); } event.put("request.uuid", rdm); captureRequestData(event, httpServletRequest); captureResponseData(event, responseSpy); } catch (Exception e) { event.put("exception", e.toString()); log.error("Error capturing data in api.RequestEventInfoCollector filter! uri=" + httpServletRequest.getRequestURI(), e); } } /** * Captures response headers. * @param event * @param res */ private void captureResponseData(Map<String, Object> event, ResponseSpy res ) { log.debug("Capturing response data"); // response headers for (String name : res.headers.keySet()) { final StringBuilder valBuilder = new StringBuilder(); boolean firstValue = true; for (String s : res.headers.get(name)) { // only prepends separator for non-first header values if (firstValue) firstValue = false; else { valBuilder.append(VALUE_SEPARATOR); } valBuilder.append(s); } event.put(RESPONSE_HEADER_PREFIX + name, valBuilder.toString()); } // Set Cookies if (!res.cookies.isEmpty()) { Iterator<Cookie> cookies = res.cookies.iterator(); StringBuilder setCookies = new StringBuilder(); while (cookies.hasNext()) { Cookie cookie = cookies.next(); setCookies.append(cookie.getName()).append("=").append(cookie.getValue()); String domain = cookie.getDomain(); if (domain != null) { setCookies.append("; Domain=").append(domain); } int maxAge = cookie.getMaxAge(); if (maxAge >= 0) { setCookies.append("; Max-Age=").append(maxAge); } String path = cookie.getPath(); if (path != null) { setCookies.append("; Path=").append(path); } if (cookie.getSecure()) { setCookies.append("; Secure"); } if (cookie.isHttpOnly()) { setCookies.append("; HttpOnly"); } if (cookies.hasNext()) { setCookies.append(VALUE_SEPARATOR); } } event.put(RESPONSE_HEADER_PREFIX + "set-cookie", setCookies.toString()); } // status of the request int status = res.statusCode; event.put("status", status); } /** * Captures request headers. * @param event * @param req */ private void captureRequestData(Map<String, Object> event, HttpServletRequest req) { // basic request properties String path = req.getRequestURI(); if (path == null) path = "/"; event.put("path", path); event.put("host", req.getHeader("host")); event.put("query", req.getQueryString()); event.put("method", req.getMethod()); event.put("currentTime", System.currentTimeMillis()); // request headers for (final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) { final String name = (String)names.nextElement(); final StringBuilder valBuilder = new StringBuilder(); boolean firstValue = true; for (final Enumeration<String> vals = req.getHeaders(name); vals.hasMoreElements();) { // only prepends separator for non-first header values if (firstValue) firstValue = false; else { valBuilder.append(VALUE_SEPARATOR); } valBuilder.append(vals.nextElement()); } event.put(REQUEST_HEADER_PREFIX + name, valBuilder.toString()); } // request params // HTTP POSTs send a param with a weird encoded name, so we strip them out with this regex if("GET".equals(req.getMethod())) { final Map<String,String[]> params = req.getParameterMap(); for (final Object key : params.keySet()) { final String keyString = key.toString(); final Object val = params.get(key); String valString; if (val instanceof String[]) { final String[] valArray = (String[]) val; if (valArray.length == 1) valString = valArray[0]; else valString = Arrays.asList((String[]) val).toString(); } else { valString = val.toString(); } event.put("param." + key, valString); } } } @Override public void destroy() { } /** * A simple wrapper for {@link HttpServletResponseWrapper} that is used to capture headers * and cookies associated with the response. */ private static final class ResponseSpy extends HttpServletResponseWrapper { int statusCode = 200; final Map<String, List<String>> headers = new ConcurrentHashMap<>(); final List<Cookie> cookies = new ArrayList<>(); private ResponseSpy(HttpServletResponse response) { super(response); } @Override public void setStatus(int sc) { super.setStatus(sc); this.statusCode = sc; } @Override public void addCookie(Cookie cookie) { cookies.add(cookie); super.addCookie(cookie); } @Override public void setHeader(String name, String value) { List<String> values = new ArrayList<>(); values.add(value); headers.put(name, values); super.setHeader(name, value); } @Override public void addHeader(String name, String value) { List<String> values = headers.computeIfAbsent(name, k -> new ArrayList<>()); values.add(value); super.addHeader(name, value); } @Override public void setDateHeader(String name, long date) { List<String> values = new ArrayList<>(); values.add(Long.toString(date)); headers.put(name, values); super.setDateHeader(name, date); } @Override public void setIntHeader(String name, int val) { List<String> values = new ArrayList<>(); values.add(Integer.toString(val)); headers.put(name, values); super.setIntHeader(name, val); } } }
5,362
0
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/service/MyService.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample.web.service; public interface MyService { String hello(String name); }
5,363
0
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis-examples/mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/service/MyServiceImpl.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample.web.service; public class MyServiceImpl implements MyService { @Override public String hello(String name) { return "Hello, " + name; } }
5,364
0
Create_ds/mantis-examples/core/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/core/src/main/java/com/netflix/mantis/examples/core/WordCountPair.java
/* * Copyright 2019 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.mantis.examples.core; import lombok.Data; /** * A simple class that holds a word and a count of how many times it has occurred. */ @Data public class WordCountPair { private final String word; private final int count; }
5,365
0
Create_ds/mantis-examples/core/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/core/src/main/java/com/netflix/mantis/examples/core/ObservableQueue.java
/* * Copyright 2019 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.mantis.examples.core; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.Subject; /** * An Observable that acts as a blocking queue. It is backed by a <code>Subject</code> * * @param <T> */ public class ObservableQueue<T> implements BlockingQueue<T>, Closeable { private final Subject<T, T> subject = PublishSubject.<T>create().toSerialized(); public Observable<T> observe() { return subject; } @Override public boolean add(T t) { return offer(t); } @Override public boolean offer(T t) { subject.onNext(t); return true; } @Override public void close() throws IOException { subject.onCompleted(); } @Override public T remove() { return noSuchElement(); } @Override public T poll() { return null; } @Override public T element() { return noSuchElement(); } private T noSuchElement() { throw new NoSuchElementException(); } @Override public T peek() { return null; } @Override public void put(T t) throws InterruptedException { offer(t); } @Override public boolean offer(T t, long timeout, TimeUnit unit) throws InterruptedException { return offer(t); } @Override public T take() throws InterruptedException { throw new UnsupportedOperationException("Use observe() instead"); } @Override public T poll(long timeout, TimeUnit unit) throws InterruptedException { return null; } @Override public int remainingCapacity() { return 0; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<? extends T> c) { c.forEach(this::offer); return true; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(Object o) { return false; } @Override public Iterator<T> iterator() { return Collections.emptyIterator(); } @Override public Object[] toArray() { return new Object[0]; } @Override public <T> T[] toArray(T[] a) { return a; } @Override public int drainTo(Collection<? super T> c) { return 0; } @Override public int drainTo(Collection<? super T> c, int maxElements) { return 0; } }
5,366
0
Create_ds/mantis-examples/core/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/core/src/main/java/com/netflix/mantis/examples/config/StageConfigs.java
/* * Copyright 2019 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.mantis.examples.config; import java.util.Map; import io.mantisrx.common.codec.Codecs; import io.mantisrx.runtime.KeyToScalar; import io.mantisrx.runtime.ScalarToKey; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.codec.JacksonCodecs; public class StageConfigs { public static ScalarToScalar.Config<String, String> scalarToScalarConfig() { return new ScalarToScalar.Config<String, String>() .codec(Codecs.string()); } public static KeyToScalar.Config<String, Map<String, Object>, String> keyToScalarConfig() { return new KeyToScalar.Config<String, Map<String, Object>, String>() .description("sum events ") .keyExpireTimeSeconds(10) .codec(Codecs.string()); } public static ScalarToKey.Config<String, String, Map<String, Object>> scalarToKeyConfig() { return new ScalarToKey.Config<String, String, Map<String, Object>>() .description("Group event data by ip") .concurrentInput() .keyExpireTimeSeconds(1) .codec(JacksonCodecs.mapStringObject()); } }
5,367
0
Create_ds/mantis-examples/sine-function/src/main/java/io/mantisrx/mantis/examples
Create_ds/mantis-examples/sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction/SineFunctionJob.java
/* * Copyright 2019 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 io.mantisrx.mantis.examples.sinefunction; import java.util.Random; import java.util.concurrent.TimeUnit; import io.mantisrx.mantis.examples.sinefunction.core.Point; import io.mantisrx.mantis.examples.sinefunction.stages.SinePointGeneratorStage; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJob; import io.mantisrx.runtime.MantisJobProvider; import io.mantisrx.runtime.Metadata; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.codec.JacksonCodecs; import io.mantisrx.runtime.executor.LocalJobExecutorNetworked; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.runtime.parameter.type.BooleanParameter; import io.mantisrx.runtime.parameter.type.DoubleParameter; import io.mantisrx.runtime.parameter.type.IntParameter; import io.mantisrx.runtime.parameter.validator.Validators; import io.mantisrx.runtime.sink.SelfDocumentingSink; import io.mantisrx.runtime.sink.ServerSentEventsSink; import io.mantisrx.runtime.sink.predicate.Predicate; import io.mantisrx.runtime.source.Index; import io.mantisrx.runtime.source.Source; import rx.Observable; import rx.functions.Func1; import rx.schedulers.Schedulers; public class SineFunctionJob extends MantisJobProvider<Point> { public static final String INTERVAL_SEC = "intervalSec"; public static final String RANGE_MAX = "max"; public static final String RANGE_MIN = "min"; public static final String AMPLITUDE = "amplitude"; public static final String FREQUENCY = "frequency"; public static final String PHASE = "phase"; public static final String RANDOM_RATE = "randomRate"; public static final String USE_RANDOM_FLAG = "useRandom"; /** * The SSE sink sets up an SSE server that can be connected to using SSE clients(curl etc.) to see * a real-time stream of (x, y) tuples on a sine curve. */ private final SelfDocumentingSink<Point> sseSink = new ServerSentEventsSink.Builder<Point>() .withEncoder(point -> String.format("{\"x\": %f, \"y\": %f}", point.getX(), point.getY())) .withPredicate(new Predicate<>( "filter=even, returns even x parameters; filter=odd, returns odd x parameters.", parameters -> { Func1<Point, Boolean> filter = point -> { return true; }; if (parameters != null && parameters.containsKey("filter")) { String filterBy = parameters.get("filter").get(0); // create filter function based on parameter value filter = point -> { // filter by evens or odds for x values if ("even".equalsIgnoreCase(filterBy)) { return (point.getX() % 2 == 0); } else if ("odd".equalsIgnoreCase(filterBy)) { return (point.getX() % 2 != 0); } return true; // if not even/odd }; } return filter; } )) .build(); /** * The Stage com.netflix.mantis.examples.config defines how the output of the stage is serialized onto the next stage or sink. */ static ScalarToScalar.Config<Integer, Point> stageConfig() { return new ScalarToScalar.Config<Integer, Point>() .codec(JacksonCodecs.pojo(Point.class)); } /** * Run this in the IDE and look for * {@code AbstractServer:95 main - Rx server started at port: <PORT_NUMBER>} in the console output. * Connect to the port using {@code curl localhost:<PORT_NUMBER>} * to see a stream of (x, y) coordinates on a sine curve. */ public static void main(String[] args) { LocalJobExecutorNetworked.execute(new SineFunctionJob().getJobInstance(), new Parameter("useRandom", "false")); } @Override public Job<Point> getJobInstance() { return MantisJob // Define the data source for this job. .source(new TimerSource()) // Add stages to transform the event stream received from the Source. .stage(new SinePointGeneratorStage(), stageConfig()) // Define a sink to output the transformed stream over SSE or an external system like Cassandra, etc. .sink(sseSink) // Add Job parameters that can be passed in by the user when submitting a job. .parameterDefinition(new BooleanParameter() .name(USE_RANDOM_FLAG) .required() .description("If true, produce a random sequence of integers. If false," + " produce a sequence of integers starting at 0 and increasing by 1.") .build()) .parameterDefinition(new DoubleParameter() .name(RANDOM_RATE) .defaultValue(1.0) .description("The chance a random integer is generated, for the given period") .validator(Validators.range(0, 1)) .build()) .parameterDefinition(new IntParameter() .name(INTERVAL_SEC) .defaultValue(1) .description("Period at which to generate a random integer value to send to sine function") .validator(Validators.range(1, 60)) .build()) .parameterDefinition(new IntParameter() .name(RANGE_MIN) .defaultValue(0) .description("Minimun of random integer value") .validator(Validators.range(0, 100)) .build()) .parameterDefinition(new IntParameter() .name(RANGE_MAX) .defaultValue(100) .description("Maximum of random integer value") .validator(Validators.range(1, 100)) .build()) .parameterDefinition(new DoubleParameter() .name(AMPLITUDE) .defaultValue(10.0) .description("Amplitude for sine function") .validator(Validators.range(1, 100)) .build()) .parameterDefinition(new DoubleParameter() .name(FREQUENCY) .defaultValue(1.0) .description("Frequency for sine function") .validator(Validators.range(1, 100)) .build()) .parameterDefinition(new DoubleParameter() .name(PHASE) .defaultValue(0.0) .description("Phase for sine function") .validator(Validators.range(0, 100)) .build()) .metadata(new Metadata.Builder() .name("Sine function") .description("Produces an infinite stream of points, along the sine function, using the" + " following function definition: f(x) = amplitude * sin(frequency * x + phase)." + " The input to the function is either random between [min, max], or an integer sequence starting " + " at 0. The output is served via HTTP server using SSE protocol.") .build()) .create(); } /** * This source generates a monotonically increasingly value per tick as per INTERVAL_SEC Job parameter. * If USE_RANDOM_FLAG is set, the source generates a random value per tick. */ class TimerSource implements Source<Integer> { @Override public Observable<Observable<Integer>> call(Context context, Index index) { // If you want to be informed of scaleup/scale down of the source stage of this job you can subscribe // to getTotalNumWorkersObservable like the following. index.getTotalNumWorkersObservable().subscribeOn(Schedulers.io()).subscribe((workerCount) -> { System.out.println("Total worker count changed to -> " + workerCount); }); final int period = (int) context.getParameters().get(INTERVAL_SEC); final int max = (int) context.getParameters().get(RANGE_MAX); final int min = (int) context.getParameters().get(RANGE_MIN); final double randomRate = (double) context.getParameters().get(RANDOM_RATE); final boolean useRandom = (boolean) context.getParameters().get(USE_RANDOM_FLAG); final Random randomNumGenerator = new Random(); final Random randomRateVariable = new Random(); return Observable.just( Observable.interval(0, period, TimeUnit.SECONDS) .map(time -> { if (useRandom) { return randomNumGenerator.nextInt((max - min) + 1) + min; } else { return (int) (long) time; } }) .filter(x -> { double value = randomRateVariable.nextDouble(); return (value <= randomRate); }) ); } } }
5,368
0
Create_ds/mantis-examples/sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction
Create_ds/mantis-examples/sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction/core/Point.java
/* * Copyright 2019 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 io.mantisrx.mantis.examples.sinefunction.core; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.runtime.codec.JsonType; public class Point implements JsonType { private double x; private double y; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public Point(@JsonProperty("x") double x, @JsonProperty("y") double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } }
5,369
0
Create_ds/mantis-examples/sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction
Create_ds/mantis-examples/sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction/stages/SinePointGeneratorStage.java
/* * Copyright 2019 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 io.mantisrx.mantis.examples.sinefunction.stages; import io.mantisrx.mantis.examples.sinefunction.SineFunctionJob; import io.mantisrx.mantis.examples.sinefunction.core.Point; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.computation.ScalarComputation; import rx.Observable; /** * This class implements the ScalarComputation type of Mantis Stage and * transforms the value received from the Source into a Point on a sine-function curve * based on AMPLITUDE, FREQUENCY and PHASE job parameters. */ public class SinePointGeneratorStage implements ScalarComputation<Integer, Point> { @Override public Observable<Point> call(Context context, Observable<Integer> o) { final double amplitude = (double) context.getParameters().get(SineFunctionJob.AMPLITUDE); final double frequency = (double) context.getParameters().get(SineFunctionJob.FREQUENCY); final double phase = (double) context.getParameters().get(SineFunctionJob.PHASE); return o .filter(x -> x % 2 == 0) .map(x -> new Point(x, amplitude * Math.sin((frequency * x) + phase))); } }
5,370
0
Create_ds/mantis-examples/wordcount/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/wordcount/src/main/java/com/netflix/mantis/examples/wordcount/WordCountJob.java
/* * Copyright 2019 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.mantis.examples.wordcount; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.concurrent.TimeUnit; import com.netflix.mantis.examples.config.StageConfigs; import com.netflix.mantis.examples.core.WordCountPair; import com.netflix.mantis.examples.wordcount.sources.IlliadSource; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJob; import io.mantisrx.runtime.MantisJobProvider; import io.mantisrx.runtime.Metadata; import io.mantisrx.runtime.executor.LocalJobExecutorNetworked; import io.mantisrx.runtime.sink.Sinks; import lombok.extern.slf4j.Slf4j; import rx.Observable; /** * This sample demonstrates ingesting data from a text file and counting the number of occurrences of words within a 10 * sec hopping window. * Run the main method of this class and then look for a the SSE port in the output * E.g * <code> Serving modern HTTP SSE server sink on port: 8650 </code> * You can curl this port <code> curl localhost:8650</code> to view the output of the job. * * To run via gradle * /gradlew :mantis-examples-wordcount:execute */ @Slf4j public class WordCountJob extends MantisJobProvider<String> { @Override public Job<String> getJobInstance() { return MantisJob .source(new IlliadSource()) // Simply echoes the tweet .stage((context, dataO) -> dataO // Tokenize .flatMap((text) -> Observable.from(tokenize(text))) // On a hopping window of 10 seconds .window(10, TimeUnit.SECONDS) .flatMap((wordCountPairObservable) -> wordCountPairObservable // count how many times a word appears .groupBy(WordCountPair::getWord) .flatMap((groupO) -> groupO.reduce(0, (cnt, wordCntPair) -> cnt + 1) .map((cnt) -> new WordCountPair(groupO.getKey(), cnt)))) .map(WordCountPair::toString) , StageConfigs.scalarToScalarConfig()) // Reuse built in sink that eagerly subscribes and delivers data over SSE .sink(Sinks.eagerSubscribe(Sinks.sse((String data) -> data))) .metadata(new Metadata.Builder() .name("WordCount") .description("Reads Homer's The Illiad faster than we can.") .build()) .create(); } private List<WordCountPair> tokenize(String text) { StringTokenizer tokenizer = new StringTokenizer(text); List<WordCountPair> wordCountPairs = new ArrayList<>(); while(tokenizer.hasMoreTokens()) { String word = tokenizer.nextToken().replaceAll("\\s*", "").toLowerCase(); wordCountPairs.add(new WordCountPair(word,1)); } return wordCountPairs; } public static void main(String[] args) { LocalJobExecutorNetworked.execute(new WordCountJob().getJobInstance()); } }
5,371
0
Create_ds/mantis-examples/wordcount/src/main/java/com/netflix/mantis/examples/wordcount
Create_ds/mantis-examples/wordcount/src/main/java/com/netflix/mantis/examples/wordcount/sources/IlliadSource.java
/* * Copyright 2019 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.mantis.examples.wordcount.sources; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.source.Index; import io.mantisrx.runtime.source.Source; import lombok.extern.log4j.Log4j; import rx.Observable; /** * Ignore the contents of this file for the tutorial. The purpose is just to generate a stream of interesting data * on which we can word count. */ @Log4j public class IlliadSource implements Source<String> { @Override public Observable<Observable<String>> call(Context context, Index index) { return Observable.interval(10, TimeUnit.SECONDS) .map(__ -> { try { Path path = Paths.get(getClass().getClassLoader() .getResource("illiad.txt").toURI()); return Observable.from(() -> { try { return Files.lines(path).iterator(); } catch (IOException ex) { log.error("IOException while reading illiad.txt from resources", ex); } return Stream.<String>empty().iterator(); } ); } catch (URISyntaxException ex) { log.error("URISyntaxException while loading illiad.txt from resources.", ex); } return Observable.empty(); }); } }
5,372
0
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples/core/WordCountPair.java
/* * Copyright 2019 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.mantis.examples.core; import lombok.Data; /** * A simple class that holds a word and a count of how many times it has occurred. */ @Data public class WordCountPair { private final String word; private final int count; }
5,373
0
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples/core/ObservableQueue.java
/* * Copyright 2019 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.mantis.examples.core; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.Subject; /** * An Observable that acts as a blocking queue. It is backed by a <code>Subject</code> * * @param <T> */ public class ObservableQueue<T> implements BlockingQueue<T>, Closeable { private final Subject<T, T> subject = PublishSubject.<T>create().toSerialized(); public Observable<T> observe() { return subject; } @Override public boolean add(T t) { return offer(t); } @Override public boolean offer(T t) { subject.onNext(t); return true; } @Override public void close() throws IOException { subject.onCompleted(); } @Override public T remove() { return noSuchElement(); } @Override public T poll() { return null; } @Override public T element() { return noSuchElement(); } private T noSuchElement() { throw new NoSuchElementException(); } @Override public T peek() { return null; } @Override public void put(T t) throws InterruptedException { offer(t); } @Override public boolean offer(T t, long timeout, TimeUnit unit) throws InterruptedException { return offer(t); } @Override public T take() throws InterruptedException { throw new UnsupportedOperationException("Use observe() instead"); } @Override public T poll(long timeout, TimeUnit unit) throws InterruptedException { return null; } @Override public int remainingCapacity() { return 0; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<? extends T> c) { c.forEach(this::offer); return true; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(Object o) { return false; } @Override public Iterator<T> iterator() { return Collections.emptyIterator(); } @Override public Object[] toArray() { return new Object[0]; } @Override public <T> T[] toArray(T[] a) { return a; } @Override public int drainTo(Collection<? super T> c) { return 0; } @Override public int drainTo(Collection<? super T> c, int maxElements) { return 0; } }
5,374
0
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples/wordcount/TwitterJob.java
/* * Copyright 2019 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.mantis.examples.wordcount; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.concurrent.TimeUnit; import com.mantisrx.common.utils.JsonUtility; import com.netflix.mantis.examples.config.StageConfigs; import com.netflix.mantis.examples.core.WordCountPair; import com.netflix.mantis.examples.wordcount.sources.TwitterSource; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJob; import io.mantisrx.runtime.MantisJobProvider; import io.mantisrx.runtime.Metadata; import io.mantisrx.runtime.executor.LocalJobExecutorNetworked; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.runtime.sink.Sinks; import lombok.extern.slf4j.Slf4j; import rx.Observable; /** * This sample demonstrates connecting to a twitter feed and counting the number of occurrences of words within a 10 * sec hopping window. * Run the main method of this class and then look for a the SSE port in the output * E.g * <code> Serving modern HTTP SSE server sink on port: 8650 </code> * You can curl this port <code> curl localhost:8650</code> to view the output of the job. * * To run via gradle * ../gradlew execute --args='consumerKey consumerSecret token tokensecret' */ @Slf4j public class TwitterJob extends MantisJobProvider<String> { @Override public Job<String> getJobInstance() { return MantisJob .source(new TwitterSource()) // Simply echoes the tweet .stage((context, dataO) -> dataO .map(JsonUtility::jsonToMap) // filter out english tweets .filter((eventMap) -> { if(eventMap.containsKey("lang") && eventMap.containsKey("text")) { String lang = (String)eventMap.get("lang"); return "en".equalsIgnoreCase(lang); } return false; }).map((eventMap) -> (String)eventMap.get("text")) // tokenize the tweets into words .flatMap((text) -> Observable.from(tokenize(text))) // On a hopping window of 10 seconds .window(10, TimeUnit.SECONDS) .flatMap((wordCountPairObservable) -> wordCountPairObservable // count how many times a word appears .groupBy(WordCountPair::getWord) .flatMap((groupO) -> groupO.reduce(0, (cnt, wordCntPair) -> cnt + 1) .map((cnt) -> new WordCountPair(groupO.getKey(), cnt)))) .map(WordCountPair::toString) .doOnNext((cnt) -> log.info(cnt)) , StageConfigs.scalarToScalarConfig()) // Reuse built in sink that eagerly subscribes and delivers data over SSE .sink(Sinks.eagerSubscribe(Sinks.sse((String data) -> data))) .metadata(new Metadata.Builder() .name("TwitterSample") .description("Connects to a Twitter feed") .build()) .create(); } private List<WordCountPair> tokenize(String text) { StringTokenizer tokenizer = new StringTokenizer(text); List<WordCountPair> wordCountPairs = new ArrayList<>(); while(tokenizer.hasMoreTokens()) { String word = tokenizer.nextToken().replaceAll("\\s*", "").toLowerCase(); wordCountPairs.add(new WordCountPair(word,1)); } return wordCountPairs; } public static void main(String[] args) { String consumerKey = null; String consumerSecret = null; String token = null; String tokenSecret = null; if(args.length != 4) { System.out.println("Usage: java com.netflix.mantis.examples.TwitterJob <consumerKey> <consumerSecret> <token> <tokenSecret"); System.exit(0); } else { consumerKey = args[0].trim(); consumerSecret = args[1].trim(); token = args[2].trim(); tokenSecret = args[3].trim(); } LocalJobExecutorNetworked.execute(new TwitterJob().getJobInstance(), new Parameter(TwitterSource.CONSUMER_KEY_PARAM,consumerKey), new Parameter(TwitterSource.CONSUMER_SECRET_PARAM, consumerSecret), new Parameter(TwitterSource.TOKEN_PARAM, token), new Parameter(TwitterSource.TOKEN_SECRET_PARAM, tokenSecret) ); } }
5,375
0
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples/wordcount
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples/wordcount/sources/TwitterSource.java
/* * Copyright 2019 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.mantis.examples.wordcount.sources; import java.util.Arrays; import java.util.List; import com.google.common.collect.Lists; import com.netflix.mantis.examples.core.ObservableQueue; import com.twitter.hbc.ClientBuilder; import com.twitter.hbc.core.Constants; import com.twitter.hbc.core.endpoint.StatusesFilterEndpoint; import com.twitter.hbc.core.processor.StringDelimitedProcessor; import com.twitter.hbc.httpclient.BasicClient; import com.twitter.hbc.httpclient.auth.Authentication; import com.twitter.hbc.httpclient.auth.OAuth1; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.parameter.ParameterDefinition; import io.mantisrx.runtime.parameter.type.StringParameter; import io.mantisrx.runtime.parameter.validator.Validators; import io.mantisrx.runtime.source.Index; import io.mantisrx.runtime.source.Source; import rx.Observable; /** * A Mantis Source that wraps an underlying Twitter source based on the HorseBirdClient. */ public class TwitterSource implements Source<String> { public static final String CONSUMER_KEY_PARAM = "consumerKey"; public static final String CONSUMER_SECRET_PARAM = "consumerSecret"; public static final String TOKEN_PARAM = "token"; public static final String TOKEN_SECRET_PARAM = "tokenSecret"; public static final String TERMS_PARAM = "terms"; private final ObservableQueue<String> twitterObservable = new ObservableQueue<>(); private transient BasicClient client; @Override public Observable<Observable<String>> call(Context context, Index index) { return Observable.just(twitterObservable.observe()); } /** * Define parameters required by this source. * * @return */ @Override public List<ParameterDefinition<?>> getParameters() { List<ParameterDefinition<?>> params = Lists.newArrayList(); // Consumer key params.add(new StringParameter() .name(CONSUMER_KEY_PARAM) .description("twitter consumer key") .validator(Validators.notNullOrEmpty()) .required() .build()); params.add(new StringParameter() .name(CONSUMER_SECRET_PARAM) .description("twitter consumer secret") .validator(Validators.notNullOrEmpty()) .required() .build()); params.add(new StringParameter() .name(TOKEN_PARAM) .description("twitter token") .validator(Validators.notNullOrEmpty()) .required() .build()); params.add(new StringParameter() .name(TOKEN_SECRET_PARAM) .description("twitter token secret") .validator(Validators.notNullOrEmpty()) .required() .build()); params.add(new StringParameter() .name(TERMS_PARAM) .description("terms to follow") .validator(Validators.notNullOrEmpty()) .defaultValue("Netflix,Dark") .build()); return params; } /** * Init method is called only once during initialization. It is the ideal place to perform one time * configuration actions. * * @param context Provides access to Mantis system information like JobId, Job parameters etc * @param index This provides access to the unique workerIndex assigned to this container. It also provides * the total number of workers of this job. */ @Override public void init(Context context, Index index) { String consumerKey = (String) context.getParameters().get(CONSUMER_KEY_PARAM); String consumerSecret = (String) context.getParameters().get(CONSUMER_SECRET_PARAM); String token = (String) context.getParameters().get(TOKEN_PARAM); String tokenSecret = (String) context.getParameters().get(TOKEN_SECRET_PARAM); String terms = (String) context.getParameters().get(TERMS_PARAM); Authentication auth = new OAuth1(consumerKey, consumerSecret, token, tokenSecret); StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint(); String[] termArray = terms.split(","); List<String> termsList = Arrays.asList(termArray); endpoint.trackTerms(termsList); client = new ClientBuilder() .name("twitter-source") .hosts(Constants.STREAM_HOST) .endpoint(endpoint) .authentication(auth) .processor(new StringDelimitedProcessor(twitterObservable)) .build(); client.connect(); } }
5,376
0
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/twitter-sample/src/main/java/com/netflix/mantis/examples/config/StageConfigs.java
/* * Copyright 2019 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.mantis.examples.config; import java.util.Map; import io.mantisrx.common.codec.Codecs; import io.mantisrx.runtime.KeyToScalar; import io.mantisrx.runtime.ScalarToKey; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.codec.JacksonCodecs; public class StageConfigs { public static ScalarToScalar.Config<String, String> scalarToScalarConfig() { return new ScalarToScalar.Config<String, String>() .codec(Codecs.string()); } public static KeyToScalar.Config<String, Map<String, Object>, String> keyToScalarConfig() { return new KeyToScalar.Config<String, Map<String, Object>, String>() .description("sum events ") .keyExpireTimeSeconds(10) .codec(Codecs.string()); } public static ScalarToKey.Config<String, String, Map<String, Object>> scalarToKeyConfig() { return new ScalarToKey.Config<String, String, Map<String, Object>>() .description("Group event data by ip") .concurrentInput() .keyExpireTimeSeconds(1) .codec(JacksonCodecs.mapStringObject()); } }
5,377
0
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples/RequestAggregationJob.java
/* * Copyright 2019 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.mantis.samples; import com.netflix.mantis.samples.source.RandomRequestSource; import com.netflix.mantis.samples.stage.AggregationStage; import com.netflix.mantis.samples.stage.CollectStage; import com.netflix.mantis.samples.stage.GroupByStage; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJob; import io.mantisrx.runtime.MantisJobProvider; import io.mantisrx.runtime.Metadata; import io.mantisrx.runtime.executor.LocalJobExecutorNetworked; import io.mantisrx.runtime.sink.Sinks; import lombok.extern.slf4j.Slf4j; /** * This sample demonstrates the use of a multi-stage job in Mantis. Multi-stage jobs are useful when a single * container is incapable of processing the entire stream of events. * Each stage represents one of these types of * computations Scalar->Scalar, Scalar->Group, Group->Scalar, Group->Group. * * At deploy time the user can configure the number workers for each stage and the resource requirements for each worker. * This sample has 3 stages * 1. {@link GroupByStage} Receives the raw events, groups them by their category and sends it to the workers of stage 2 in such a way * that all events for a particular group will land on the exact same worker of stage 2. * 2. {@link AggregationStage} Receives events tagged by their group from the previous stage. Windows over them and * sums up the counts of each group it has seen. * 3. {@link CollectStage} Recieves the aggregates generated by the previous stage, collects them over a window and * generates a consolidated report which is sent to the default Server Sent Event (SSE) sink. * * Run this sample by executing the main method of this class. Then look for the SSE port where the output of this job * will be available for streaming. E.g Serving modern HTTP SSE server sink on port: 8299 * via command line do ../gradlew execute */ @Slf4j public class RequestAggregationJob extends MantisJobProvider<String> { @Override public Job<String> getJobInstance() { return MantisJob // Stream Request Events from our random data generator source .source(new RandomRequestSource()) // Groups requests by path .stage(new GroupByStage(), GroupByStage.config()) // Computes count per path over a window .stage(new AggregationStage(), AggregationStage.config()) // Collects the data and makes it availabe over SSE .stage(new CollectStage(), CollectStage.config()) // Reuse built in sink that eagerly subscribes and delivers data over SSE .sink(Sinks.eagerSubscribe( Sinks.sse((String data) -> data))) .metadata(new Metadata.Builder() .name("GroupByPath") .description("Connects to a random data generator source" + " and counts the number of requests for each uri within a window") .build()) .create(); } public static void main(String[] args) { // To run locally we use the LocalJobExecutor LocalJobExecutorNetworked.execute(new RequestAggregationJob().getJobInstance()); } }
5,378
0
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples/proto/RequestEvent.java
/* * Copyright 2019 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.mantis.samples.proto; import java.io.IOException; import io.mantisrx.common.codec.Codec; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import lombok.Builder; import lombok.Data; /** * A simple POJO that holds data about a request event. */ @Data @Builder public class RequestEvent { private static final ObjectMapper mapper = new ObjectMapper(); private static final ObjectReader requestEventReader = mapper.readerFor(RequestEvent.class); private final String requestPath; private final String ipAddress; /** * The codec defines how this class should be serialized before transporting across network. * @return */ public static Codec<RequestEvent> requestEventCodec() { return new Codec<RequestEvent>() { @Override public RequestEvent decode(byte[] bytes) { try { return requestEventReader.readValue(bytes); } catch (IOException e) { throw new RuntimeException(e); } } @Override public byte[] encode(final RequestEvent value) { try { return mapper.writeValueAsBytes(value); } catch (Exception e) { throw new RuntimeException(e); } } }; } }
5,379
0
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples/proto/RequestAggregation.java
/* * Copyright 2019 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.mantis.samples.proto; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import io.mantisrx.common.codec.Codec; import lombok.Builder; import lombok.Data; /** * A simple POJO that holds the count of how many times a particular request path was invoked. */ @Data @Builder public class RequestAggregation { private static final ObjectMapper mapper = new ObjectMapper(); private static final ObjectReader requestAggregationReader = mapper.readerFor(RequestAggregation.class); private final String path; private final int count; /** * Codec is used to customize how data is serialized before transporting across network boundaries. * @return */ public static Codec<RequestAggregation> requestAggregationCodec() { return new Codec<RequestAggregation>() { @Override public RequestAggregation decode(byte[] bytes) { try { return requestAggregationReader.readValue(bytes); } catch (IOException e) { throw new RuntimeException(e); } } @Override public byte[] encode(final RequestAggregation value) { try { return mapper.writeValueAsBytes(value); } catch (Exception e) { throw new RuntimeException(e); } } }; } }
5,380
0
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples/proto/AggregationReport.java
/* * Copyright 2019 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.mantis.samples.proto; import java.util.Map; import lombok.Data; /** * A simple POJO which holds the result of aggregating counts per request path. */ @Data public class AggregationReport { private final Map<String, Integer> pathToCountMap; }
5,381
0
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples/source/RandomRequestSource.java
/* * Copyright 2019 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.mantis.samples.source; import java.util.concurrent.TimeUnit; import com.netflix.mantis.samples.proto.RequestEvent; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.source.Index; import io.mantisrx.runtime.source.Source; import lombok.extern.slf4j.Slf4j; import net.andreinc.mockneat.MockNeat; import rx.Observable; /** * Generates random set of RequestEvents at a preconfigured interval. */ @Slf4j public class RandomRequestSource implements Source<RequestEvent> { private MockNeat mockDataGenerator; @Override public Observable<Observable<RequestEvent>> call(Context context, Index index) { return Observable.just(Observable.interval(250, TimeUnit.MILLISECONDS).map((tick) -> { String ip = mockDataGenerator.ipv4s().get(); String path = mockDataGenerator.probabilites(String.class) .add(0.1, "/login") .add(0.2, "/genre/horror") .add(0.5, "/genre/comedy") .add(0.2, "/mylist") .get(); return RequestEvent.builder().ipAddress(ip).requestPath(path).build(); }).doOnNext((event) -> { log.debug("Generated Event {}", event); })); } @Override public void init(Context context, Index index) { mockDataGenerator = MockNeat.threadLocal(); } }
5,382
0
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples/stage/AggregationStage.java
/* * Copyright 2019 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.mantis.samples.stage; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import com.netflix.mantis.samples.proto.RequestAggregation; import com.netflix.mantis.samples.proto.RequestEvent; import io.mantisrx.common.MantisGroup; import io.mantisrx.common.codec.Codec; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.GroupToScalar; import io.mantisrx.runtime.computation.GroupToScalarComputation; import io.mantisrx.runtime.parameter.ParameterDefinition; import io.mantisrx.runtime.parameter.type.IntParameter; import io.mantisrx.runtime.parameter.validator.Validators; import lombok.extern.slf4j.Slf4j; import rx.Observable; /** * This is the 2nd stage of this three stage job. It receives events from {@link GroupByStage} * This stage converts Grouped Events to Scalar events {@link GroupToScalarComputation} Typically used in the * reduce portion of a map reduce computation. * * This stage receives an <code>Observable<MantisGroup<String,RequestEvent>></code>. This represents a stream of * request events tagged by the URI Path they belong to. * This stage then groups the events by the path and and counts the number of invocations of each path over a window. */ @Slf4j public class AggregationStage implements GroupToScalarComputation<String, RequestEvent, RequestAggregation> { public static final String AGGREGATION_DURATION_MSEC_PARAM = "AggregationDurationMsec"; int aggregationDurationMsec; /** * The call method is invoked by the Mantis runtime while executing the job. * @param context Provides metadata information related to the current job. * @param mantisGroupO This is an Observable of {@link MantisGroup} events. Each event is a pair of the Key -> uri Path and * the {@link RequestEvent} event itself. * @return */ @Override public Observable<RequestAggregation> call(Context context, Observable<MantisGroup<String, RequestEvent>> mantisGroupO) { return mantisGroupO .window(aggregationDurationMsec, TimeUnit.MILLISECONDS) .flatMap((omg) -> omg.groupBy(MantisGroup::getKeyValue) .flatMap((go) -> go.reduce(0, (accumulator, value) -> accumulator = accumulator + 1) .map((count) -> RequestAggregation.builder().count(count).path(go.getKey()).build()) .doOnNext((aggregate) -> { log.debug("Generated aggregate {}", aggregate); }) )); } /** * Invoked only once during job startup. A good place to add one time initialization actions. * @param context */ @Override public void init(Context context) { aggregationDurationMsec = (int)context.getParameters().get(AGGREGATION_DURATION_MSEC_PARAM, 1000); } /** * Provides the Mantis runtime configuration information about the type of computation done by this stage. * E.g in this case it specifies this is a GroupToScalar computation and also provides a {@link Codec} on how to * serialize the {@link RequestAggregation} events before sending it to the {@link CollectStage} * @return */ public static GroupToScalar.Config<String, RequestEvent, RequestAggregation> config(){ return new GroupToScalar.Config<String, RequestEvent,RequestAggregation>() .description("sum events for a path") .codec(RequestAggregation.requestAggregationCodec()) .withParameters(getParameters()); } /** * Here we declare stage specific parameters. * @return */ public static List<ParameterDefinition<?>> getParameters() { List<ParameterDefinition<?>> params = new ArrayList<>(); // Aggregation duration params.add(new IntParameter() .name(AGGREGATION_DURATION_MSEC_PARAM) .description("window size for aggregation") .validator(Validators.range(100, 10000)) .defaultValue(5000) .build()) ; return params; } }
5,383
0
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples/stage/CollectStage.java
/* * Copyright 2019 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.mantis.samples.stage; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.mantis.samples.proto.RequestAggregation; import com.netflix.mantis.samples.proto.AggregationReport; import io.mantisrx.common.codec.Codecs; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.computation.ScalarComputation; import lombok.extern.slf4j.Slf4j; import rx.Observable; /** * This is the final stage of this 3 stage job. It receives events from {@link AggregationStage} * The role of this stage is to collect aggregates generated by the previous stage for all the groups within * a window and generate a unified report of them. */ @Slf4j public class CollectStage implements ScalarComputation<RequestAggregation,String> { private static final ObjectMapper mapper = new ObjectMapper(); @Override public Observable<String> call(Context context, Observable<RequestAggregation> requestAggregationO) { return requestAggregationO .window(5, TimeUnit.SECONDS) .flatMap((requestAggO) -> requestAggO .reduce(new RequestAggregationAccumulator(),(acc, requestAgg) -> acc.addAggregation(requestAgg)) .map(RequestAggregationAccumulator::generateReport) .doOnNext((report) -> { log.debug("Generated Collection report {}", report); }) ) .map((report) -> { try { return mapper.writeValueAsString(report); } catch (JsonProcessingException e) { log.error(e.getMessage()); return null; } }).filter(Objects::nonNull); } @Override public void init(Context context) { } public static ScalarToScalar.Config<RequestAggregation,String> config(){ return new ScalarToScalar.Config<RequestAggregation,String>() .codec(Codecs.string()); } /** * The accumulator class as the name suggests accumulates all aggregates seen during a window and * generates a consolidated report at the end. */ static class RequestAggregationAccumulator { private final Map<String, Integer> pathToCountMap = new HashMap<>(); public RequestAggregationAccumulator() {} public RequestAggregationAccumulator addAggregation(RequestAggregation agg) { pathToCountMap.put(agg.getPath(), agg.getCount()); return this; } public AggregationReport generateReport() { log.info("Generated report from=> {}", pathToCountMap); return new AggregationReport(pathToCountMap); } } }
5,384
0
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples
Create_ds/mantis-examples/groupby-sample/src/main/java/com/netflix/mantis/samples/stage/GroupByStage.java
/* * Copyright 2019 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.mantis.samples.stage; import java.util.ArrayList; import java.util.List; import com.netflix.mantis.samples.proto.RequestEvent; import io.mantisrx.common.MantisGroup; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.ScalarToGroup; import io.mantisrx.runtime.computation.ToGroupComputation; import io.mantisrx.runtime.parameter.ParameterDefinition; import io.mantisrx.runtime.parameter.type.StringParameter; import io.mantisrx.runtime.parameter.validator.Validators; import lombok.extern.slf4j.Slf4j; import rx.Observable; /** * This is the first stage of this 3 stage job. It is at the head of the computation DAG * This stage converts Scalar Events to Grouped Events {@link ToGroupComputation}. The grouped events are then * send to the next stage of the Mantis Job in a way such that all events belonging to a particular group will * land on the same worker of the next stage. * * It receives a stream of {@link RequestEvent} and groups them by either the path or the IP address * based on the parameters passed by the user. */ @Slf4j public class GroupByStage implements ToGroupComputation<RequestEvent, String, RequestEvent> { private static final String GROUPBY_FIELD_PARAM = "groupByField"; private boolean groupByPath = true; @Override public Observable<MantisGroup<String, RequestEvent>> call(Context context, Observable<RequestEvent> requestEventO) { return requestEventO .map((requestEvent) -> { if(groupByPath) { return new MantisGroup<>(requestEvent.getRequestPath(), requestEvent); } else { return new MantisGroup<>(requestEvent.getIpAddress(), requestEvent); } }); } @Override public void init(Context context) { String groupByField = (String)context.getParameters().get(GROUPBY_FIELD_PARAM,"path"); groupByPath = groupByField.equalsIgnoreCase("path") ? true : false; } /** * Here we declare stage specific parameters. * @return */ public static List<ParameterDefinition<?>> getParameters() { List<ParameterDefinition<?>> params = new ArrayList<>(); // Group by field params.add(new StringParameter() .name(GROUPBY_FIELD_PARAM) .description("The key to group events by") .validator(Validators.notNullOrEmpty()) .defaultValue("path") .build()) ; return params; } public static ScalarToGroup.Config<RequestEvent, String, RequestEvent> config(){ return new ScalarToGroup.Config<RequestEvent, String, RequestEvent>() .description("Group event data by path/ip") .concurrentInput() // signifies events can be processed parallely .withParameters(getParameters()) .codec(RequestEvent.requestEventCodec()); } }
5,385
0
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/Application.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.archaius.guice.ArchaiusModule; import com.netflix.spectator.nflx.SpectatorModule; import io.mantisrx.publish.api.EventPublisher; import io.mantisrx.publish.netty.guice.MantisRealtimeEventsPublishModule; /** * A simple example that uses Guice to inject the {@link EventPublisher} part of the mantis-publish library * to send events to Mantis. * * The mantis-publish library provides on-demand source side filtering via MQL. When a user publishes * events via this library the events may not be actually shipped to Mantis. A downstream consumer needs * to first register a query and the query needs to match events published by the user. */ public class Application { public static void main(String [] args) { Injector injector = Guice.createInjector(new BasicModule(), new ArchaiusModule(), new MantisRealtimeEventsPublishModule(), new SpectatorModule()); IDataPublisher publisher = injector.getInstance(IDataPublisher.class); publisher.generateAndSendEventsToMantis(); } }
5,386
0
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/BasicModule.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample; import com.google.inject.AbstractModule; public class BasicModule extends AbstractModule { @Override protected void configure() { bind(IDataPublisher.class).to(SampleDataPublisher.class); bind(IDataGenerator.class).to(DataGenerator.class); } }
5,387
0
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/SampleDataPublisher.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample; import com.google.inject.Inject; import io.mantisrx.publish.api.Event; import io.mantisrx.publish.api.EventPublisher; import io.mantisrx.publish.api.PublishStatus; import lombok.extern.slf4j.Slf4j; import rx.Observable; /** * A simple example that uses Guice to inject the {@link EventPublisher} part of the mantis-publish library * to send events to Mantis. * * The mantis-publish library provides on-demand source side filtering via MQL. When a user publishes * events via this library the events may not be actually shipped to Mantis. A downstream consumer needs * to first register a query and the query needs to match events published by the user. * */ @Slf4j public class SampleDataPublisher implements IDataPublisher{ @Inject EventPublisher publisher; @Inject DataGenerator dataGenerator; /** * Generates random events at a fixed rate and publishes them to the mantis-publish library. * Here the events are published to the defaultStream. */ @Override public void generateAndSendEventsToMantis() { dataGenerator .generateEvents() .map((requestEvent) -> new Event(requestEvent.toMap())) .flatMap((event) -> Observable.from(publisher.publish(event) .toCompletableFuture())) .toBlocking() .subscribe((status) -> { log.info("Mantis publish JavaApp send event status => {}", status); }); } }
5,388
0
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/IDataPublisher.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample; public interface IDataPublisher { void generateAndSendEventsToMantis(); }
5,389
0
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/IDataGenerator.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample; import com.netflix.mantis.examples.mantispublishsample.proto.RequestEvent; import rx.Observable; /** * A data generator that generates a stream of {@link RequestEvent} at a fixed interval. */ public interface IDataGenerator { Observable<RequestEvent> generateEvents(); }
5,390
0
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/DataGenerator.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample; import java.util.concurrent.TimeUnit; import com.netflix.mantis.examples.mantispublishsample.proto.RequestEvent; import net.andreinc.mockneat.MockNeat; import rx.Observable; /** * Uses MockNeat to generate a random stream of events. Each event represents a hypothetical request * made by an end user to this service. */ public class DataGenerator implements IDataGenerator { private final int rateMs = 1000; private final MockNeat mockDataGenerator = MockNeat.threadLocal(); @Override public Observable<RequestEvent> generateEvents() { return Observable .interval(rateMs, TimeUnit.MILLISECONDS) .map((tick) -> generateEvent()); } private RequestEvent generateEvent() { String path = mockDataGenerator.probabilites(String.class) .add(0.1, "/login") .add(0.2, "/genre/horror") .add(0.5, "/genre/comedy") .add(0.2, "/mylist") .get(); String deviceType = mockDataGenerator.probabilites(String.class) .add(0.1, "ps4") .add(0.1, "xbox") .add(0.2, "browser") .add(0.3, "ios") .add(0.3, "android") .get(); String userId = mockDataGenerator.strings().size(10).get(); int status = mockDataGenerator.probabilites(Integer.class) .add(0.1,500) .add(0.7,200) .add(0.2,500) .get(); String country = mockDataGenerator.countries().names().get(); return RequestEvent.builder() .status(status) .uri(path) .country(country) .userId(userId) .deviceType(deviceType) .build(); } }
5,391
0
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample
Create_ds/mantis-examples/mantis-publish-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/proto/RequestEvent.java
/* * Copyright 2019 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.mantis.examples.mantispublishsample.proto; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import lombok.Builder; import lombok.Data; /** * Represents a Request Event a service may receive. */ @Data @Builder public class RequestEvent { private static final ObjectMapper mapper = new ObjectMapper(); private static final ObjectReader requestEventReader = mapper.readerFor(RequestEvent.class); private final String userId; private final String uri; private final int status; private final String country; private final String deviceType; public Map<String,Object> toMap() { Map<String,Object> data = new HashMap<>(); data.put("userId", userId); data.put("uri", uri); data.put("status", status); data.put("country", country); data.put("deviceType", deviceType); return data; } public String toJsonString() { try { return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { e.printStackTrace(); return null; } } }
5,392
0
Create_ds/mantis-examples/jobconnector-sample/src/main/java/com/netflix/mantis
Create_ds/mantis-examples/jobconnector-sample/src/main/java/com/netflix/mantis/samples/JobConnectorJob.java
/* * Copyright 2019 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.mantis.samples; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.mantis.samples.stage.EchoStage; import io.mantisrx.connector.job.core.MantisSourceJobConnector; import io.mantisrx.connector.job.source.JobSource; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJob; import io.mantisrx.runtime.MantisJobProvider; import io.mantisrx.runtime.Metadata; import io.mantisrx.runtime.executor.LocalJobExecutorNetworked; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.runtime.sink.Sinks; import lombok.extern.slf4j.Slf4j; /** * This sample demonstrates how to connect to the output of another job using the {@link JobSource} * If the target job is a source job then you can request a filtered stream of events from the source job * by passing an MQL query. * In this example we connect to the latest running instance of SyntheticSourceJob using the query * select country from stream where status==500 and simply echo the output. * * Run this sample by executing the main method of this class. Then look for the SSE port where the output of this job * will be available for streaming. E.g Serving modern HTTP SSE server sink on port: 8299 * via command line do ../gradlew execute * * Note: this sample may not work in your IDE as the Mantis runtime needs to discover the location of the * SyntheticSourceJob. */ @Slf4j public class JobConnectorJob extends MantisJobProvider<String> { @Override public Job<String> getJobInstance() { return MantisJob // Stream Events from a job specified via job parameters .source(new JobSource()) // Simple echoes the data .stage(new EchoStage(), EchoStage.config()) // Reuse built in sink that eagerly subscribes and delivers data over SSE .sink(Sinks.eagerSubscribe( Sinks.sse((String data) -> data))) .metadata(new Metadata.Builder() .name("ConnectToJob") .description("Connects to the output of another job" + " and simply echoes the data") .build()) .create(); } public static void main(String[] args) throws JsonProcessingException { Map<String,Object> targetMap = new HashMap<>(); List<JobSource.TargetInfo> targetInfos = new ArrayList<>(); JobSource.TargetInfo targetInfo = new JobSource.TargetInfoBuilder().withClientId("abc") .withSourceJobName("SyntheticSourceJob") .withQuery("select country from stream where status==500") .build(); targetInfos.add(targetInfo); targetMap.put("targets",targetInfos); ObjectMapper mapper = new ObjectMapper(); String target = mapper.writeValueAsString(targetMap); // To run locally we use the LocalJobExecutor LocalJobExecutorNetworked.execute(new JobConnectorJob().getJobInstance(), new Parameter(MantisSourceJobConnector.MANTIS_SOURCEJOB_TARGET_KEY, target)); } }
5,393
0
Create_ds/mantis-examples/jobconnector-sample/src/main/java/com/netflix/mantis/samples
Create_ds/mantis-examples/jobconnector-sample/src/main/java/com/netflix/mantis/samples/stage/EchoStage.java
/* * Copyright 2019 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.mantis.samples.stage; import com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.common.MantisServerSentEvent; import io.mantisrx.common.codec.Codecs; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.computation.ScalarComputation; import lombok.extern.slf4j.Slf4j; import rx.Observable; /** * A simple stage that extracts data from the incoming {@link MantisServerSentEvent} and echoes it. */ @Slf4j public class EchoStage implements ScalarComputation<MantisServerSentEvent,String> { private static final ObjectMapper mapper = new ObjectMapper(); @Override public Observable<String> call(Context context, Observable<MantisServerSentEvent> eventsO) { return eventsO .map(MantisServerSentEvent::getEventAsString) .map((event) -> { log.info("Received: {}", event); return event; }); } @Override public void init(Context context) { } public static ScalarToScalar.Config<MantisServerSentEvent,String> config(){ return new ScalarToScalar.Config<MantisServerSentEvent,String>() .codec(Codecs.string()); } }
5,394
0
Create_ds/frigga/src/main/java/com/netflix
Create_ds/frigga/src/main/java/com/netflix/frigga/NameValidation.java
/** * Copyright 2012 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.frigga; import java.util.regex.Pattern; /** * Contains static validation methods for checking if a name conforms to Asgard naming standards. */ public class NameValidation { private static final Pattern NAME_HYPHEN_CHARS_PATTERN = Pattern.compile("^[" + NameConstants.NAME_HYPHEN_CHARS + "]+"); private static final Pattern NAME_CHARS_PATTERN = Pattern.compile("^[" + NameConstants.NAME_CHARS + "]+"); private static final Pattern PUSH_FORMAT_PATTERN = Pattern.compile(".*?" + NameConstants.PUSH_FORMAT); private static final Pattern LABELED_VARIABLE_PATTERN = Pattern.compile("^(.*?-)?" + NameConstants.LABELED_VARIABLE + ".*?$"); private NameValidation() { } /** * Validates if provided value is non-null and non-empty. * * @param value the string to validate * @param variableName name of the variable to include in error messages * @return the value parameter if valid, throws an exception otherwise */ public static String notEmpty(String value, String variableName) { if (value == null) { throw new NullPointerException("ERROR: Trying to use String with null " + variableName); } if (value.isEmpty()) { throw new IllegalArgumentException("ERROR: Illegal empty string for " + variableName); } return value; } /** * Validates a name of a cloud object. The name can contain letters, numbers, dots, and underscores. * * @param name the string to validate * @return true if the name is valid */ public static boolean checkName(String name) { return checkMatch(name, NAME_CHARS_PATTERN); } /** * Validates a name of a cloud object. The name can contain hyphens in addition to letters, numbers, dots, and * underscores. * * @param name the string to validate * @return true if the name is valid */ public static boolean checkNameWithHyphen(String name) { return checkMatch(name, NAME_HYPHEN_CHARS_PATTERN); } /** * The detail part of an auto scaling group name can include letters, numbers, dots, underscores, and hyphens. * Restricting the ASG name this way allows safer assumptions in other code about ASG names, like a promise of no * spaces, hash marks, percent signs, or dollar signs. * * @deprecated use checkNameWithHyphen * @param detail the detail string to validate * @return true if the detail is valid */ @Deprecated public static boolean checkDetail(String detail) { return checkMatch(detail, NAME_HYPHEN_CHARS_PATTERN); } /** * Determines whether a name ends with the reserved format -v000 where 0 represents any digit, or starts with the * reserved format z0 where z is any letter, or contains a hyphen-separated token that starts with the z0 format. * * @param name to inspect * @return true if the name ends with the reserved format */ public static Boolean usesReservedFormat(String name) { return checkMatch(name, PUSH_FORMAT_PATTERN) || checkMatch(name, LABELED_VARIABLE_PATTERN); } private static boolean checkMatch(String input, Pattern pattern) { return input != null && pattern.matcher(input).matches(); } }
5,395
0
Create_ds/frigga/src/main/java/com/netflix
Create_ds/frigga/src/main/java/com/netflix/frigga/NameConstants.java
/** * Copyright 2012 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.frigga; /** * Constants used in name parsing, name construction, and name validation. */ public interface NameConstants { String NAME_CHARS = "a-zA-Z0-9._"; String EXTENDED_NAME_CHARS = NAME_CHARS + "~\\^"; String NAME_HYPHEN_CHARS = "-" + EXTENDED_NAME_CHARS; String PUSH_FORMAT = "v([0-9]{3,6})"; String COUNTRIES_KEY = "c"; String DEV_PHASE_KEY = "d"; String HARDWARE_KEY = "h"; String PARTNERS_KEY = "p"; String REVISION_KEY = "r"; String USED_BY_KEY = "u"; String RED_BLACK_SWAP_KEY = "w"; String ZONE_KEY = "z"; String EXISTING_LABELS = "[" + COUNTRIES_KEY + DEV_PHASE_KEY + HARDWARE_KEY + PARTNERS_KEY + REVISION_KEY + USED_BY_KEY + RED_BLACK_SWAP_KEY + ZONE_KEY + "]"; String LABELED_VAR_SEPARATOR = "0"; String LABELED_VAR_VALUES = "[a-zA-Z0-9]"; String LABELED_VARIABLE = EXISTING_LABELS + "[" + LABELED_VAR_SEPARATOR + "]" + LABELED_VAR_VALUES + "+"; }
5,396
0
Create_ds/frigga/src/main/java/com/netflix
Create_ds/frigga/src/main/java/com/netflix/frigga/NameBuilder.java
/** * Copyright 2012 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.frigga; /** * Abstract class for classes in charge of constructing Asgard names. */ public abstract class NameBuilder { protected String combineAppStackDetail(String appName, String stack, String detail) { NameValidation.notEmpty(appName, "appName"); // Use empty strings, not null references that output "null" stack = stack != null ? stack : ""; if (detail != null && !detail.isEmpty()) { return appName + "-" + stack + "-" + detail; } if (!stack.isEmpty()) { return appName + "-" + stack; } return appName; } }
5,397
0
Create_ds/frigga/src/main/java/com/netflix
Create_ds/frigga/src/main/java/com/netflix/frigga/Names.java
/** * Copyright 2012 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.frigga; import com.netflix.frigga.conventions.labeledvariables.LabeledVariables; import com.netflix.frigga.conventions.labeledvariables.LabeledVariablesNamingConvention; import com.netflix.frigga.conventions.labeledvariables.LabeledVariablesNamingResult; import com.netflix.frigga.extensions.NamingConvention; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class that can deconstruct information about AWS Auto Scaling Groups, Load Balancers, Launch Configurations, and * Security Groups created by Asgard based on their name. */ public class Names { private static final Pattern PUSH_PATTERN = Pattern.compile( "^([" + NameConstants.NAME_HYPHEN_CHARS + "]*)-(" + NameConstants.PUSH_FORMAT + ")$"); private static final Pattern NAME_PATTERN = Pattern.compile( "^([" + NameConstants.NAME_CHARS + "]+)(?:-([" + NameConstants.NAME_CHARS + "]*)(?:-([" + NameConstants.NAME_HYPHEN_CHARS + "]*?))?)?$"); private static final LabeledVariablesNamingConvention LABELED_VARIABLES_CONVENTION = new LabeledVariablesNamingConvention(); private final String group; private final String cluster; private final String app; private final String stack; private final String detail; private final String push; private final Integer sequence; private final AtomicReference<LabeledVariablesNamingResult> labeledVariables = new AtomicReference<>(); protected Names(String name) { String group = null; String cluster = null; String app = null; String stack = null; String detail = null; String push = null; Integer sequence = null; if (name != null && !name.trim().isEmpty()) { Matcher pushMatcher = PUSH_PATTERN.matcher(name); boolean hasPush = pushMatcher.matches(); String theCluster = hasPush ? pushMatcher.group(1) : name; Matcher nameMatcher = NAME_PATTERN.matcher(theCluster); if (nameMatcher.matches()) { group = name; cluster = theCluster; push = hasPush ? pushMatcher.group(2) : null; String sequenceString = hasPush ? pushMatcher.group(3) : null; if (sequenceString != null) { sequence = Integer.parseInt(sequenceString); } app = nameMatcher.group(1); stack = checkEmpty(nameMatcher.group(2)); detail = checkEmpty(nameMatcher.group(3)); } } this.group = group; this.cluster = cluster; this.app = app; this.stack = stack; this.detail = detail; this.push = push; this.sequence = sequence; } /** * Breaks down the name of an auto scaling group, security group, or load balancer created by Asgard into its * component parts. * * @param name the name of an auto scaling group, security group, or load balancer * @return bean containing the component parts of the compound name */ public static Names parseName(String name) { return new Names(name); } private String checkEmpty(String input) { return (input != null && !input.isEmpty()) ? input : null; } public String getGroup() { return group; } public String getCluster() { return cluster; } public String getApp() { return app; } public String getStack() { return stack; } public String getDetail() { return detail; } public String getPush() { return push; } public Integer getSequence() { return sequence; } public String getCountries() { return getLabeledVariable(LabeledVariables::getCountries); } public String getDevPhase() { return getLabeledVariable(LabeledVariables::getDevPhase); } public String getHardware() { return getLabeledVariable(LabeledVariables::getHardware); } public String getPartners() { return getLabeledVariable(LabeledVariables::getPartners); } public String getRevision() { return getLabeledVariable(LabeledVariables::getRevision); } public String getUsedBy() { return getLabeledVariable(LabeledVariables::getUsedBy); } public String getRedBlackSwap() { return getLabeledVariable(LabeledVariables::getRedBlackSwap); } public String getZone() { return getLabeledVariable(LabeledVariables::getZone); } private <T> T getLabeledVariable(Function<LabeledVariables, T> extractor) { LabeledVariablesNamingResult result = labeledVariables.get(); if (result == null) { LabeledVariablesNamingResult applied = LABELED_VARIABLES_CONVENTION.extractNamingConvention(cluster); if (labeledVariables.compareAndSet(null, applied)) { result = applied; } else { result = labeledVariables.get(); } } return result.getResult().map(extractor).orElse(null); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Names names = (Names) o; return Objects.equals(group, names.group); } @Override public int hashCode() { return Objects.hash(group); } @Override public String toString() { return "Names{" + "group='" + group + '\'' + ", cluster='" + cluster + '\'' + ", app='" + app + '\'' + ", stack='" + stack + '\'' + ", detail='" + detail + '\'' + ", push='" + push + '\'' + ", sequence=" + sequence + '}'; } }
5,398
0
Create_ds/frigga/src/main/java/com/netflix/frigga
Create_ds/frigga/src/main/java/com/netflix/frigga/ami/AppVersion.java
/** * Copyright 2012 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.frigga.ami; import com.netflix.frigga.NameConstants; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Java bean containing the various pieces of information contained in the appversion tag of an AMI formatted with * Netflix standards. Construct using the {@link parseName} factory method. */ public class AppVersion implements Comparable<AppVersion> { /** * Valid app patterns. For example, all of these are valid: * subscriberha-1.0.0-586499 * subscriberha-1.0.0-586499.h150 * subscriberha-1.0.0-586499.h150/WE-WAPP-subscriberha/150 */ private static final Pattern APP_VERSION_PATTERN = Pattern.compile( "([" + NameConstants.NAME_HYPHEN_CHARS + "]+)-([0-9.a-zA-Z~]+)-(\\w+)(?:[.](\\w+))?(?:~[" + NameConstants.NAME_HYPHEN_CHARS + "]+)?(?:\\/([" + NameConstants.NAME_HYPHEN_CHARS + "]+)\\/([0-9]+))?"); private String packageName; private String version; private String buildJobName; private String buildNumber; private String commit; private AppVersion() { } /** * Parses the appversion tag into its component parts. * * @param amiName the text of the AMI's appversion tag * @return bean representing the component parts of the appversion tag */ public static AppVersion parseName(String amiName) { if (amiName == null) { return null; } Matcher matcher = APP_VERSION_PATTERN.matcher(amiName); if (!matcher.matches()) { return null; } AppVersion parsedName = new AppVersion(); parsedName.packageName = matcher.group(1); parsedName.version = matcher.group(2); // Historically we put the change number first because with Perforce it was a number we could use to sort. // This broke when we started using git, since hashes have no order. For a while the stash builds ommited the // commit id, but eventually we began appending it after the build number. boolean buildFirst = matcher.group(3) != null && matcher.group(3).startsWith("h"); // 'h' is for Hudson String buildString = matcher.group(buildFirst ? 3 : 4); parsedName.buildNumber = buildString != null ? buildString.substring(1) : null; parsedName.commit = matcher.group(buildFirst ? 4 : 3); parsedName.buildJobName = matcher.group(5); return parsedName; } @Override public int compareTo(AppVersion other) { if (this == other) { // if x.equals(y), then x.compareTo(y) should be 0 return 0; } if (other == null) { return 1; // equals(null) can never be true, so compareTo(null) should never be 0 } int comparison = nullSafeStringComparator(packageName, other.packageName); if (comparison != 0) { return comparison; } comparison = nullSafeStringComparator(version, other.version); if (comparison != 0) { return comparison; } comparison = nullSafeStringComparator(buildJobName, other.buildJobName); if (comparison != 0) { return comparison; } comparison = nullSafeStringComparator(buildNumber, other.buildNumber); if (comparison != 0) { return comparison; } comparison = nullSafeStringComparator(commit, other.commit); return comparison; } private int nullSafeStringComparator(final String one, final String two) { if (one == null && two == null) { return 0; } if (one == null || two == null) { return (one == null) ? -1 : 1; } return one.compareTo(two); } /** * The regex used for deconstructing the appversion string. */ public static Pattern getAppVersionPattern() { return APP_VERSION_PATTERN; } /** * The name of the RPM package used to create this AMI. */ public String getPackageName() { return packageName; } /** * The version of the RPM package used to create this AMI. */ public String getVersion() { return version; } /** * The Jenkins job that generated the binary deployed on this AMI. */ public String getBuildJobName() { return buildJobName; } /** * The Jenkins build number that generated the binary on this AMI. */ public String getBuildNumber() { return buildNumber; } /** * Identifier of the commit used in the Jenkins builds. Works with both Perforce CLs or git hashes. * @since 0.4 */ public String getCommit() { return commit; } /** * @deprecated As of version 0.4, replaced by {@link getCommit()} */ @Deprecated public String getChangelist() { return commit; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AppVersion [packageName=").append(packageName).append(", version=").append(version) .append(", buildJobName=").append(buildJobName).append(", buildNumber=").append(buildNumber) .append(", changelist=").append(commit).append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((buildJobName == null) ? 0 : buildJobName.hashCode()); result = prime * result + ((buildNumber == null) ? 0 : buildNumber.hashCode()); result = prime * result + ((commit == null) ? 0 : commit.hashCode()); result = prime * result + ((packageName == null) ? 0 : packageName.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AppVersion other = (AppVersion) obj; if (buildJobName == null) { if (other.buildJobName != null) return false; } else if (!buildJobName.equals(other.buildJobName)) return false; if (buildNumber == null) { if (other.buildNumber != null) return false; } else if (!buildNumber.equals(other.buildNumber)) return false; if (commit == null) { if (other.commit != null) return false; } else if (!commit.equals(other.commit)) return false; if (packageName == null) { if (other.packageName != null) return false; } else if (!packageName.equals(other.packageName)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } }
5,399