index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__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/S3Manager.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.manager; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailLog; import com.amazonaws.services.cloudtrail.processinglibrary.model.CloudTrailSource; import com.amazonaws.services.s3.model.S3Object; /** * Manages Amazon S3 service-related operations. */ public interface S3Manager { /** * Downloads an AWS CloudTrail log from the specified source. * * @param ctLog The {@link CloudTrailLog} to download * @param source The {@link CloudTrailSource} to download the log from. * @return A byte array containing the log data. */ byte[] downloadLog(CloudTrailLog ctLog, CloudTrailSource source); /** * Download an S3 object. * * @param bucketName The S3 bucket name from which to download the object. * @param objectKey The S3 key name of the object to download. * @return The downloaded * <a href="http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/model/S3Object.html">S3Object</a>. */ S3Object getObject(String bucketName, String objectKey); }
5,900
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/SqsManager.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.manager; import com.amazonaws.AmazonServiceException; 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.model.CloudTrailSource; import com.amazonaws.services.cloudtrail.processinglibrary.model.SourceAttributeKeys; import com.amazonaws.services.cloudtrail.processinglibrary.model.internal.SourceType; import com.amazonaws.services.cloudtrail.processinglibrary.progress.BasicParseMessageInfo; import com.amazonaws.services.cloudtrail.processinglibrary.progress.BasicPollQueueInfo; import com.amazonaws.services.cloudtrail.processinglibrary.progress.ProgressState; import com.amazonaws.services.cloudtrail.processinglibrary.progress.ProgressStatus; import com.amazonaws.services.cloudtrail.processinglibrary.serializer.SourceSerializer; import com.amazonaws.services.cloudtrail.processinglibrary.utils.LibraryUtils; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.model.DeleteMessageRequest; import com.amazonaws.services.sqs.model.Message; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.ReceiveMessageResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; /** * A convenient class to manage Amazon SQS Service related operations. */ public class SqsManager { private static final Log logger = LogFactory.getLog(SqsManager.class); private static final String ALL_ATTRIBUTES = "All"; /** * Pull 10 messages from SQS queue at a time. */ private static final int DEFAULT_SQS_MESSAGE_SIZE_LIMIT = 10; /** * Enable long pulling, wait at most 20 seconds for a incoming messages for a single poll queue request. */ private static final int DEFAULT_WAIT_TIME_SECONDS = 20; /** * An instance of ProcessingConfiguration. */ private ProcessingConfiguration config; /** * An instance of AmazonSQSClient. */ private AmazonSQS sqsClient; /** * An instance of SourceSerializer. */ private SourceSerializer sourceSerializer; /** * User implementation of ExceptionHandler, used to handle error case. */ private ExceptionHandler exceptionHandler; /** * User implementation of ProgressReporter, used to report progress. */ private ProgressReporter progressReporter; /** * SqsManager constructor. * * @param sqsClient used to poll message from SQS. * @param config user provided ProcessingConfiguration. * @param exceptionHandler user provided exceptionHandler. * @param progressReporter user provided progressReporter. * @param sourceSerializer user provided SourceSerializer. */ public SqsManager(AmazonSQS sqsClient, ProcessingConfiguration config, ExceptionHandler exceptionHandler, ProgressReporter progressReporter, SourceSerializer sourceSerializer) { this.config = config; this.exceptionHandler = exceptionHandler; this.progressReporter = progressReporter; this.sqsClient = sqsClient; this.sourceSerializer = sourceSerializer; validate(); } /** * Poll SQS queue for incoming messages, filter them, and return a list of SQS Messages. * * @return a list of SQS messages. */ public List<Message> pollQueue() { boolean success = false; ProgressStatus pollQueueStatus = new ProgressStatus(ProgressState.pollQueue, new BasicPollQueueInfo(0, success)); final Object reportObject = progressReporter.reportStart(pollQueueStatus); ReceiveMessageRequest request = new ReceiveMessageRequest().withAttributeNames(ALL_ATTRIBUTES); request.setQueueUrl(config.getSqsUrl()); request.setVisibilityTimeout(config.getVisibilityTimeout()); request.setMaxNumberOfMessages(DEFAULT_SQS_MESSAGE_SIZE_LIMIT); request.setWaitTimeSeconds(DEFAULT_WAIT_TIME_SECONDS); List<Message> sqsMessages = new ArrayList<Message>(); try { ReceiveMessageResult result = sqsClient.receiveMessage(request); sqsMessages = result.getMessages(); logger.info("Polled " + sqsMessages.size() + " sqs messages from " + config.getSqsUrl()); success = true; } catch (AmazonServiceException e) { LibraryUtils.handleException(exceptionHandler, pollQueueStatus, e, "Failed to poll sqs message."); } finally { LibraryUtils.endToProcess(progressReporter, success, pollQueueStatus, reportObject); } return sqsMessages; } /** * Given a list of raw SQS message parse each of them, and return a list of CloudTrailSource. * * @param sqsMessages list of SQS messages. * @return list of CloudTrailSource. */ public List<CloudTrailSource> parseMessage(List<Message> sqsMessages) { List<CloudTrailSource> sources = new ArrayList<>(); for (Message sqsMessage : sqsMessages) { boolean parseMessageSuccess = false; ProgressStatus parseMessageStatus = new ProgressStatus(ProgressState.parseMessage, new BasicParseMessageInfo(sqsMessage, parseMessageSuccess)); final Object reportObject = progressReporter.reportStart(parseMessageStatus); CloudTrailSource ctSource = null; try { ctSource = sourceSerializer.getSource(sqsMessage); if (containsCloudTrailLogs(ctSource)) { sources.add(ctSource); parseMessageSuccess = true; } } catch (Exception e) { LibraryUtils.handleException(exceptionHandler, parseMessageStatus, e, "Failed to parse sqs message."); } finally { if (containsCloudTrailValidationMessage(ctSource) || shouldDeleteMessageUponFailure(parseMessageSuccess)) { deleteMessageFromQueue(sqsMessage, new ProgressStatus(ProgressState.deleteMessage, new BasicParseMessageInfo(sqsMessage, false))); } LibraryUtils.endToProcess(progressReporter, parseMessageSuccess, parseMessageStatus, reportObject); } } return sources; } /** * Delete a message from the SQS queue that you specified in the configuration file. * * @param sqsMessage the {@link Message} that you want to delete. * @param progressStatus {@link ProgressStatus} tracks the start and end status. * */ public void deleteMessageFromQueue(Message sqsMessage, ProgressStatus progressStatus) { final Object reportObject = progressReporter.reportStart(progressStatus); boolean deleteMessageSuccess = false; try { sqsClient.deleteMessage(new DeleteMessageRequest(config.getSqsUrl(), sqsMessage.getReceiptHandle())); deleteMessageSuccess = true; } catch (AmazonServiceException e) { LibraryUtils.handleException(exceptionHandler, progressStatus, e, "Failed to delete sqs message."); } LibraryUtils.endToProcess(progressReporter, deleteMessageSuccess, progressStatus, reportObject); } /** * Check whether <code>ctSource</code> contains CloudTrail log files. * @param ctSource a {@link CloudTrailSource}. * @return <code>true</code> if contains CloudTrail log files, <code>false</code> otherwise. * */ private boolean containsCloudTrailLogs(CloudTrailSource ctSource) { SourceType sourceType = SourceType.valueOf(ctSource.getSourceAttributes().get(SourceAttributeKeys.SOURCE_TYPE.getAttributeKey())); switch(sourceType) { case CloudTrailLog: return true; case CloudTrailValidationMessage: logger.warn(String.format("Delete CloudTrail validation message: %s.", ctSource.toString())); return false; case Other: default: logger.info(String.format("Skip Non CloudTrail Log File: %s.", ctSource.toString())); return false; } } /** * Check whether <code>ctSource</code> contains CloudTrail validation message. * @param ctSource a {@link CloudTrailSource}. * @return <code>true</code> if contains CloudTrail validation message, <code>false</code> otherwise. * */ private boolean containsCloudTrailValidationMessage(CloudTrailSource ctSource) { if (ctSource == null){ return false; } SourceType sourceType = SourceType.valueOf(ctSource.getSourceAttributes().get(SourceAttributeKeys.SOURCE_TYPE.getAttributeKey())); return sourceType == SourceType.CloudTrailValidationMessage; } /** * Delete the message if the CPL failed to process the message and {@link ProcessingConfiguration#isDeleteMessageUponFailure()} * is enabled. * @param processSuccess Indicates whether the CPL processing is successful, such as parsing message, or * consuming the events in the CloudTrail log file. * @return <code>true</code> if the message is removable. Otherwise, <code>false</code>. */ public boolean shouldDeleteMessageUponFailure(boolean processSuccess) { return !processSuccess && config.isDeleteMessageUponFailure(); } /** * Convenient function to validate input. */ private void validate() { LibraryUtils.checkArgumentNotNull(config, "configuration is null"); LibraryUtils.checkArgumentNotNull(exceptionHandler, "exceptionHandler is null"); LibraryUtils.checkArgumentNotNull(progressReporter, "progressReporter is null"); LibraryUtils.checkArgumentNotNull(sqsClient, "sqsClient is null"); LibraryUtils.checkArgumentNotNull(sourceSerializer, "sourceSerializer is null"); } }
5,901
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,902
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,903
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,904
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,905
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,906
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,907
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,908
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,909
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,910
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,911
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,912
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,913
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,914
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,915
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,916
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,917
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,918
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,919
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,920
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,921
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,922
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,923
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,924
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,925
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,926
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,927
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,928
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,929
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,930
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,931
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,932
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,933
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,934
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,935
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,936
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,937
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,938
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/transaction/RecordingTransactionTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.transaction; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.TreeMap; import com.google.common.collect.Iterators; import org.apache.fluo.api.client.Transaction; import org.apache.fluo.api.client.scanner.CellScanner; import org.apache.fluo.api.client.scanner.ColumnScanner; import org.apache.fluo.api.client.scanner.RowScanner; import org.apache.fluo.api.client.scanner.RowScannerBuilder; import org.apache.fluo.api.client.scanner.ScannerBuilder; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.ColumnValue; import org.apache.fluo.api.data.RowColumnValue; import org.apache.fluo.recipes.core.types.StringEncoder; import org.apache.fluo.recipes.core.types.TypeLayer; import org.apache.fluo.recipes.core.types.TypedTransaction; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.mock; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; public class RecordingTransactionTest { private Transaction tx; private RecordingTransaction rtx; private TypeLayer tl = new TypeLayer(new StringEncoder()); @Before public void setUp() { tx = mock(Transaction.class); rtx = RecordingTransaction.wrap(tx); } @Test public void testTx() { rtx.set(Bytes.of("r1"), new Column("cf1"), Bytes.of("v1")); rtx.set(Bytes.of("r2"), new Column("cf2", "cq2"), Bytes.of("v2")); rtx.delete(Bytes.of("r3"), new Column("cf3")); expect(tx.get(Bytes.of("r4"), new Column("cf4"))).andReturn(Bytes.of("v4")); replay(tx); rtx.get(Bytes.of("r4"), new Column("cf4")); List<LogEntry> entries = rtx.getTxLog().getLogEntries(); Assert.assertEquals(4, entries.size()); Assert.assertEquals("LogEntry{op=SET, row=r1, col=cf1 , value=v1}", entries.get(0).toString()); Assert.assertEquals("LogEntry{op=SET, row=r2, col=cf2 cq2 , value=v2}", entries.get(1).toString()); Assert.assertEquals("LogEntry{op=DELETE, row=r3, col=cf3 , value=}", entries.get(2).toString()); Assert.assertEquals("LogEntry{op=GET, row=r4, col=cf4 , value=v4}", entries.get(3).toString()); Assert.assertEquals("{r4 cf4 =v4}", rtx.getTxLog().getOperationMap(LogEntry.Operation.GET).toString()); Assert.assertEquals("{r1 cf1 =v1, r2 cf2 cq2 =v2}", new TreeMap<>(rtx.getTxLog().getOperationMap(LogEntry.Operation.SET)).toString()); Assert.assertEquals("{r3 cf3 =}", rtx.getTxLog().getOperationMap(LogEntry.Operation.DELETE).toString()); } @Test public void testTypedTx() { TypedTransaction ttx = tl.wrap(rtx); ttx.mutate().row("r5").fam("cf5").qual("cq5").set("1"); ttx.mutate().row("r6").fam("cf6").qual("cq6").set("1"); List<LogEntry> entries = rtx.getTxLog().getLogEntries(); Assert.assertEquals(2, entries.size()); Assert.assertEquals("LogEntry{op=SET, row=r5, col=cf5 cq5 , value=1}", entries.get(0).toString()); Assert.assertEquals("LogEntry{op=SET, row=r6, col=cf6 cq6 , value=1}", entries.get(1).toString()); } @Test public void testFilter() { rtx = RecordingTransaction.wrap(tx, le -> le.getColumn().getFamily().toString().equals("cfa")); TypedTransaction ttx = tl.wrap(rtx); ttx.mutate().row("r1").fam("cfa").qual("cq1").set("1"); ttx.mutate().row("r2").fam("cfb").qual("cq2").set("2"); ttx.mutate().row("r3").fam("cfa").qual("cq3").set("3"); List<LogEntry> entries = rtx.getTxLog().getLogEntries(); Assert.assertEquals(2, entries.size()); Assert.assertEquals("LogEntry{op=SET, row=r1, col=cfa cq1 , value=1}", entries.get(0).toString()); Assert.assertEquals("LogEntry{op=SET, row=r3, col=cfa cq3 , value=3}", entries.get(1).toString()); } @Test public void testClose() { tx.close(); replay(tx); rtx.close(); verify(tx); } @Test public void testCommit() { tx.commit(); replay(tx); rtx.commit(); verify(tx); } @Test public void testDelete() { tx.delete(Bytes.of("r"), Column.EMPTY); replay(tx); rtx.delete(Bytes.of("r"), Column.EMPTY); verify(tx); } @Test public void testGet() { expect(tx.get(Bytes.of("r"), Column.EMPTY)).andReturn(Bytes.of("v")); replay(tx); Assert.assertEquals(Bytes.of("v"), rtx.get(Bytes.of("r"), Column.EMPTY)); verify(tx); } @Test public void testGetColumns() { expect(tx.get(Bytes.of("r"), Collections.emptySet())).andReturn(Collections.emptyMap()); replay(tx); Assert.assertEquals(Collections.emptyMap(), rtx.get(Bytes.of("r"), Collections.emptySet())); verify(tx); } @Test public void testGetRows() { expect(tx.get(Collections.emptyList(), Collections.emptySet())) .andReturn(Collections.emptyMap()); replay(tx); Assert.assertEquals(Collections.emptyMap(), rtx.get(Collections.emptyList(), Collections.emptySet())); verify(tx); } @Test public void testGetScanIter() { ScannerBuilder sb = mock(ScannerBuilder.class); expect(sb.build()).andReturn(() -> Iterators .singletonIterator(new RowColumnValue("r7", new Column("cf7", "cq7"), "v7"))); expect(tx.scanner()).andReturn(sb); replay(tx, sb); Iterator<RowColumnValue> iter = rtx.scanner().build().iterator(); Assert.assertTrue(rtx.getTxLog().isEmpty()); Assert.assertTrue(iter.hasNext()); Assert.assertEquals(new RowColumnValue("r7", new Column("cf7", "cq7"), "v7"), iter.next()); Assert.assertFalse(rtx.getTxLog().isEmpty()); List<LogEntry> entries = rtx.getTxLog().getLogEntries(); Assert.assertEquals(1, entries.size()); Assert.assertEquals("LogEntry{op=GET, row=r7, col=cf7 cq7 , value=v7}", entries.get(0).toString()); verify(tx, sb); } @Test public void testGetRowScanner() { ColumnScanner cs = mock(ColumnScanner.class); RowScanner rs = mock(RowScanner.class); RowScannerBuilder rsb = mock(RowScannerBuilder.class); ScannerBuilder sb = mock(ScannerBuilder.class); expect(cs.getRow()).andReturn(Bytes.of("r7")).times(2); expect(cs.iterator()) .andReturn(Iterators.singletonIterator(new ColumnValue(new Column("cf7", "cq7"), "v7"))); expect(rs.iterator()).andReturn(Iterators.singletonIterator(cs)); expect(rsb.build()).andReturn(rs); expect(sb.byRow()).andReturn(rsb); expect(tx.scanner()).andReturn(sb); replay(tx, sb, rsb, rs, cs); Iterator<ColumnScanner> riter = rtx.scanner().byRow().build().iterator(); Assert.assertTrue(riter.hasNext()); ColumnScanner cscanner = riter.next(); Assert.assertEquals(Bytes.of("r7"), cscanner.getRow()); Iterator<ColumnValue> citer = cscanner.iterator(); Assert.assertTrue(citer.hasNext()); Assert.assertTrue(rtx.getTxLog().isEmpty()); Assert.assertEquals(new ColumnValue(new Column("cf7", "cq7"), "v7"), citer.next()); List<LogEntry> entries = rtx.getTxLog().getLogEntries(); Assert.assertEquals(1, entries.size()); Assert.assertEquals("LogEntry{op=GET, row=r7, col=cf7 cq7 , value=v7}", entries.get(0).toString()); verify(tx, sb, rsb, rs, cs); } @Test public void testGetTimestamp() { expect(tx.getStartTimestamp()).andReturn(5L); replay(tx); Assert.assertEquals(5L, rtx.getStartTimestamp()); verify(tx); } }
5,939
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/types/MockSnapshot.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import org.apache.fluo.api.client.Snapshot; public class MockSnapshot extends MockSnapshotBase implements Snapshot { MockSnapshot(String... entries) { super(entries); } @Override public void close() { // no resources need to be closed } }
5,940
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/types/MockSnapshotBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.fluo.api.client.AbstractSnapshotBase; import org.apache.fluo.api.client.SnapshotBase; import org.apache.fluo.api.client.scanner.ScannerBuilder; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.RowColumn; public class MockSnapshotBase extends AbstractSnapshotBase implements SnapshotBase { final Map<Bytes, Map<Column, Bytes>> getData; /** * Initializes {@link #getData} using {@link #toRCVM(String...)} */ MockSnapshotBase(String... entries) { getData = toRCVM(entries); } @Override public Bytes get(Bytes row, Column column) { Map<Column, Bytes> cols = getData.get(row); if (cols != null) { return cols.get(column); } return null; } @Override public Map<Column, Bytes> get(Bytes row, Set<Column> columns) { Map<Column, Bytes> ret = new HashMap<>(); Map<Column, Bytes> cols = getData.get(row); if (cols != null) { for (Column column : columns) { Bytes val = cols.get(column); if (val != null) { ret.put(column, val); } } } return ret; } @Override public Map<Bytes, Map<Column, Bytes>> get(Collection<Bytes> rows, Set<Column> columns) { Map<Bytes, Map<Column, Bytes>> ret = new HashMap<>(); for (Bytes row : rows) { Map<Column, Bytes> colMap = get(row, columns); if (colMap != null && colMap.size() > 0) { ret.put(row, colMap); } } return ret; } @Override public ScannerBuilder scanner() { throw new UnsupportedOperationException(); } /** * toRCVM stands for "To Row Column Value Map". This is a convenience function that takes strings * of the format {@code <row>,<col fam>:<col qual>[:col vis], * <value>} and generates a row, column, value map. */ public static Map<Bytes, Map<Column, Bytes>> toRCVM(String... entries) { Map<Bytes, Map<Column, Bytes>> ret = new HashMap<>(); for (String entry : entries) { String[] rcv = entry.split(","); if (rcv.length != 3 && !(rcv.length == 2 && entry.trim().endsWith(","))) { throw new IllegalArgumentException( "expected <row>,<col fam>:<col qual>[:col vis],<value> but saw : " + entry); } Bytes row = Bytes.of(rcv[0]); String[] colFields = rcv[1].split(":"); Column col; if (colFields.length == 3) { col = new Column(colFields[0], colFields[1], colFields[2]); } else if (colFields.length == 2) { col = new Column(colFields[0], colFields[1]); } else { throw new IllegalArgumentException( "expected <row>,<col fam>:<col qual>[:col vis],<value> but saw : " + entry); } Bytes val; if (rcv.length == 2) { val = Bytes.EMPTY; } else { val = Bytes.of(rcv[2]); } Map<Column, Bytes> cols = ret.get(row); if (cols == null) { cols = new HashMap<>(); ret.put(row, cols); } cols.put(col, val); } return ret; } /** * toRCM stands for "To Row Column Map". This is a convenience function that takes strings of the * format {@code <row>,<col fam>:<col qual>[:col vis]} and generates a row, column map. */ public static Map<Bytes, Set<Column>> toRCM(String... entries) { Map<Bytes, Set<Column>> ret = new HashMap<>(); for (String entry : entries) { String[] rcv = entry.split(","); if (rcv.length != 2) { throw new IllegalArgumentException( "expected <row>,<col fam>:<col qual>[:col vis] but saw : " + entry); } Bytes row = Bytes.of(rcv[0]); String[] colFields = rcv[1].split(":"); Column col; if (colFields.length == 3) { col = new Column(colFields[0], colFields[1], colFields[2]); } else if (colFields.length == 2) { col = new Column(colFields[0], colFields[1]); } else { throw new IllegalArgumentException( "expected <row>,<col fam>:<col qual>[:col vis],<value> but saw : " + entry); } Set<Column> cols = ret.get(row); if (cols == null) { cols = new HashSet<>(); ret.put(row, cols); } cols.add(col); } return ret; } @Override public long getStartTimestamp() { throw new UnsupportedOperationException(); } @Override public Map<RowColumn, Bytes> get(Collection<RowColumn> rowColumns) { throw new UnsupportedOperationException(); } }
5,941
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/types/MockTransactionBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.exceptions.AlreadySetException; /** * A very simple implementation of {@link TransactionBase} used for testing. All reads are serviced * from {@link #getData}. Updates are stored in {@link #setData}, {@link #deletes}, or * {@link #weakNotifications} depending on the update type. */ public class MockTransactionBase extends MockSnapshotBase implements TransactionBase { final Map<Bytes, Map<Column, Bytes>> setData = new HashMap<>(); final Map<Bytes, Set<Column>> deletes = new HashMap<>(); final Map<Bytes, Set<Column>> weakNotifications = new HashMap<>(); MockTransactionBase(String... entries) { super(entries); } @Override public void setWeakNotification(Bytes row, Column col) { Set<Column> cols = weakNotifications.get(row); if (cols == null) { cols = new HashSet<>(); weakNotifications.put(row, cols); } cols.add(col); } @Override public void set(Bytes row, Column col, Bytes value) { Map<Column, Bytes> cols = setData.get(row); if (cols == null) { cols = new HashMap<>(); setData.put(row, cols); } cols.put(col, value); } @Override public void delete(Bytes row, Column col) { Set<Column> cols = deletes.get(row); if (cols == null) { cols = new HashSet<>(); deletes.put(row, cols); } cols.add(col); } @Override public void delete(CharSequence row, Column col) { delete(Bytes.of(row), col); } @Override public void set(CharSequence row, Column col, CharSequence value) throws AlreadySetException { set(Bytes.of(row), col, Bytes.of(value)); } @Override public void setWeakNotification(CharSequence row, Column col) { setWeakNotification(Bytes.of(row), col); } }
5,942
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/types/TypeLayerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map; import java.util.Set; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; import org.apache.fluo.recipes.core.types.TypedSnapshotBase.Value; import org.junit.Assert; import org.junit.Test; public class TypeLayerTest { @Test public void testColumns() throws Exception { TypeLayer tl = new TypeLayer(new StringEncoder()); MockTransactionBase tt = new MockTransactionBase("r1,cf1:cq1,v1", "r1,cf1:cq2,v2", "r1,cf1:cq3,9", "r2,cf2:7,12", "r2,cf2:8,13", "13,9:17,20", "13,9:18,20", "13,9:19,20", "13,9:20,20"); TypedTransactionBase ttx = tl.wrap(tt); Map<Column, Value> results = ttx.get().row("r2").columns(Set.of(new Column("cf2", "6"), new Column("cf2", "7"))); Assert.assertNull(results.get(new Column("cf2", "6")).toInteger()); Assert.assertEquals(0, results.get(new Column("cf2", "6")).toInteger(0)); Assert.assertEquals(12, (int) results.get(new Column("cf2", "7")).toInteger()); Assert.assertEquals(12, results.get(new Column("cf2", "7")).toInteger(0)); Assert.assertEquals(1, results.size()); results = ttx.get().row("r2") .columns(Set.of(new Column("cf2", "6"), new Column("cf2", "7"), new Column("cf2", "8"))); Assert.assertNull(results.get(new Column("cf2", "6")).toInteger()); Assert.assertEquals(0, results.get(new Column("cf2", "6")).toInteger(0)); Assert.assertEquals(12, (int) results.get(new Column("cf2", "7")).toInteger()); Assert.assertEquals(12, results.get(new Column("cf2", "7")).toInteger(0)); Assert.assertEquals(13, (int) results.get(new Column("cf2", "8")).toInteger()); Assert.assertEquals(13, results.get(new Column("cf2", "8")).toInteger(0)); Assert.assertEquals(2, results.size()); // test var args Map<Column, Value> results2 = ttx.get().row("r2").columns(new Column("cf2", "6"), new Column("cf2", "7"), new Column("cf2", "8")); Assert.assertEquals(results, results2); } @Test public void testVis() throws Exception { TypeLayer tl = new TypeLayer(new StringEncoder()); MockTransactionBase tt = new MockTransactionBase("r1,cf1:cq1:A,v1", "r1,cf1:cq2:A&B,v2"); TypedTransactionBase ttx = tl.wrap(tt); Assert.assertNull(ttx.get().row("r1").fam("cf1").qual("cq1").toString()); Assert.assertEquals("v1", ttx.get().row("r1").fam("cf1").qual("cq1").vis("A").toString()); Assert.assertEquals("v1", ttx.get().row("r1").fam("cf1").qual("cq1").vis("A".getBytes()).toString()); Assert.assertEquals("v1", ttx.get().row("r1").fam("cf1").qual("cq1").vis(Bytes.of("A")).toString()); Assert.assertEquals("v1", ttx.get().row("r1").fam("cf1").qual("cq1").vis(ByteBuffer.wrap("A".getBytes())).toString()); Assert.assertNull("v1", ttx.get().row("r1").fam("cf1").qual("cq1").vis("A&B").toString()); Assert.assertNull("v1", ttx.get().row("r1").fam("cf1").qual("cq1").vis("A&B".getBytes()).toString()); Assert.assertNull("v1", ttx.get().row("r1").fam("cf1").qual("cq1").vis(Bytes.of("A&B")).toString()); Assert.assertNull("v1", ttx.get().row("r1").fam("cf1").qual("cq1") .vis(ByteBuffer.wrap("A&B".getBytes())).toString()); Assert.assertEquals("v3", ttx.get().row("r1").fam("cf1").qual("cq1").vis("A&B").toString("v3")); Assert.assertEquals("v3", ttx.get().row("r1").fam("cf1").qual("cq1").vis("A&B".getBytes()).toString("v3")); Assert.assertEquals("v3", ttx.get().row("r1").fam("cf1").qual("cq1").vis(Bytes.of("A&B")).toString("v3")); Assert.assertEquals("v3", ttx.get().row("r1").fam("cf1").qual("cq1") .vis(ByteBuffer.wrap("A&B".getBytes())).toString("v3")); ttx.mutate().row("r1").fam("cf1").qual("cq1").vis("A&B").set(3); ttx.mutate().row("r1").fam("cf1").qual("cq1").vis("A&C".getBytes()).set(4); ttx.mutate().row("r1").fam("cf1").qual("cq1").vis(Bytes.of("A&D")).set(5); ttx.mutate().row("r1").fam("cf1").qual("cq1").vis(ByteBuffer.wrap("A&F".getBytes())).set(7); Assert.assertEquals(MockTransactionBase.toRCVM("r1,cf1:cq1:A&B,3", "r1,cf1:cq1:A&C,4", "r1,cf1:cq1:A&D,5", "r1,cf1:cq1:A&F,7"), tt.setData); tt.setData.clear(); ttx.mutate().row("r1").fam("cf1").qual("cq1").vis("A&B").delete(); ttx.mutate().row("r1").fam("cf1").qual("cq1").vis("A&C".getBytes()).delete(); ttx.mutate().row("r1").fam("cf1").qual("cq1").vis(Bytes.of("A&D")).delete(); ttx.mutate().row("r1").fam("cf1").qual("cq1").vis(ByteBuffer.wrap("A&F".getBytes())).delete(); Assert.assertEquals(MockTransactionBase.toRCM("r1,cf1:cq1:A&B", "r1,cf1:cq1:A&C", "r1,cf1:cq1:A&D", "r1,cf1:cq1:A&F"), tt.deletes); tt.deletes.clear(); Assert.assertEquals(0, tt.setData.size()); Assert.assertEquals(0, tt.weakNotifications.size()); } @Test public void testBuildColumn() { TypeLayer tl = new TypeLayer(new StringEncoder()); Assert.assertEquals(new Column("f0", "q0"), tl.bc().fam("f0".getBytes()).qual("q0".getBytes()).vis()); Assert.assertEquals(new Column("f0", "q0"), tl.bc().fam("f0").qual("q0").vis()); Assert.assertEquals(new Column("5", "7"), tl.bc().fam(5).qual(7).vis()); Assert.assertEquals(new Column("5", "7"), tl.bc().fam(5l).qual(7l).vis()); Assert.assertEquals(new Column("5", "7"), tl.bc().fam(Bytes.of("5")).qual(Bytes.of("7")).vis()); Assert.assertEquals(new Column("5", "7"), tl.bc().fam(ByteBuffer.wrap("5".getBytes())).qual(ByteBuffer.wrap("7".getBytes())).vis()); Assert.assertEquals(new Column("f0", "q0", "A&B"), tl.bc().fam("f0".getBytes()).qual("q0".getBytes()).vis("A&B")); Assert.assertEquals(new Column("f0", "q0", "A&C"), tl.bc().fam("f0").qual("q0").vis("A&C".getBytes())); Assert.assertEquals(new Column("5", "7", "A&D"), tl.bc().fam(5).qual(7).vis(Bytes.of("A&D"))); Assert.assertEquals(new Column("5", "7", "A&D"), tl.bc().fam(5).qual(7).vis(ByteBuffer.wrap("A&D".getBytes()))); } @Test public void testRead() throws Exception { TypeLayer tl = new TypeLayer(new StringEncoder()); MockSnapshot ms = new MockSnapshot("r1,cf1:cq1,v1", "r1,cf1:cq2,v2", "r1,cf1:cq3,9", "r2,cf2:7,12", "r2,cf2:8,13", "13,9:17,20", "13,9:18,20", "13,9:19,20", "13,9:20,20", "r3,cf3:cq3,28.195", "r4,cf4:cq4,true"); TypedSnapshot tts = tl.wrap(ms); Assert.assertEquals("v1", tts.get().row("r1").fam("cf1").qual("cq1").toString()); Assert.assertEquals("v1", tts.get().row("r1").fam("cf1").qual("cq1").toString("b")); Assert.assertEquals("13", tts.get().row("r2").fam("cf2").qual("8").toString()); Assert.assertEquals("13", tts.get().row("r2").fam("cf2").qual("8").toString("b")); Assert.assertEquals("28.195", tts.get().row("r3").fam("cf3").qual("cq3").toString()); Assert.assertEquals("28.195", tts.get().row("r3").fam("cf3").qual("cq3").toString("b")); Assert.assertEquals("true", tts.get().row("r4").fam("cf4").qual("cq4").toString()); Assert.assertEquals("true", tts.get().row("r4").fam("cf4").qual("cq4").toString("b")); // try converting to different types Assert.assertEquals("13", tts.get().row("r2").fam("cf2").qual(8).toString()); Assert.assertEquals("13", tts.get().row("r2").fam("cf2").qual(8).toString("b")); Assert.assertEquals((Integer) 13, tts.get().row("r2").fam("cf2").qual(8).toInteger()); Assert.assertEquals(13, tts.get().row("r2").fam("cf2").qual(8).toInteger(14)); Assert.assertEquals((Long) 13l, tts.get().row("r2").fam("cf2").qual(8).toLong()); Assert.assertEquals(13l, tts.get().row("r2").fam("cf2").qual(8).toLong(14l)); Assert.assertEquals("13", new String(tts.get().row("r2").fam("cf2").qual(8).toBytes())); Assert.assertEquals("13", new String(tts.get().row("r2").fam("cf2").qual(8).toBytes("14".getBytes()))); Assert.assertEquals("13", new String(tts.get().row("r2").col(new Column("cf2", "8")).toBytes())); Assert.assertEquals("13", new String(tts.get().row("r2").col(new Column("cf2", "8")).toBytes("14".getBytes()))); Assert.assertEquals("13", Bytes.of(tts.get().row("r2").col(new Column("cf2", "8")).toByteBuffer()).toString()); Assert.assertEquals("13", Bytes.of(tts.get().row("r2").col(new Column("cf2", "8")) .toByteBuffer(ByteBuffer.wrap("14".getBytes()))).toString()); // test non-existent Assert.assertNull(tts.get().row("r2").fam("cf3").qual(8).toInteger()); Assert.assertEquals(14, tts.get().row("r2").fam("cf3").qual(8).toInteger(14)); Assert.assertNull(tts.get().row("r2").fam("cf3").qual(8).toLong()); Assert.assertEquals(14l, tts.get().row("r2").fam("cf3").qual(8).toLong(14l)); Assert.assertNull(tts.get().row("r2").fam("cf3").qual(8).toString()); Assert.assertEquals("14", tts.get().row("r2").fam("cf3").qual(8).toString("14")); Assert.assertNull(tts.get().row("r2").fam("cf3").qual(8).toBytes()); Assert.assertEquals("14", new String(tts.get().row("r2").fam("cf3").qual(8).toBytes("14".getBytes()))); Assert.assertNull(tts.get().row("r2").col(new Column("cf3", "8")).toBytes()); Assert.assertEquals("14", new String(tts.get().row("r2").col(new Column("cf3", "8")).toBytes("14".getBytes()))); Assert.assertNull(tts.get().row("r2").col(new Column("cf3", "8")).toByteBuffer()); Assert.assertEquals("14", Bytes.of(tts.get().row("r2").col(new Column("cf3", "8")) .toByteBuffer(ByteBuffer.wrap("14".getBytes()))).toString()); // test float & double Assert.assertEquals((Float) 28.195f, tts.get().row("r3").fam("cf3").qual("cq3").toFloat()); Assert.assertEquals(28.195f, tts.get().row("r3").fam("cf3").qual("cq3").toFloat(39.383f), 0.0); Assert.assertEquals((Double) 28.195d, tts.get().row("r3").fam("cf3").qual("cq3").toDouble()); Assert.assertEquals(28.195d, tts.get().row("r3").fam("cf3").qual("cq3").toDouble(39.383d), 0.0); // test boolean Assert.assertEquals(true, tts.get().row("r4").fam("cf4").qual("cq4").toBoolean()); Assert.assertEquals(true, tts.get().row("r4").fam("cf4").qual("cq4").toBoolean()); Assert.assertEquals(true, tts.get().row("r4").fam("cf4").qual("cq4").toBoolean(false)); Assert.assertEquals(true, tts.get().row("r4").fam("cf4").qual("cq4").toBoolean(false)); // try different types for row Assert.assertEquals("20", tts.get().row(13).fam("9").qual("17").toString()); Assert.assertEquals("20", tts.get().row(13l).fam("9").qual("17").toString()); Assert.assertEquals("20", tts.get().row("13").fam("9").qual("17").toString()); Assert.assertEquals("20", tts.get().row("13".getBytes()).fam("9").qual("17").toString()); Assert.assertEquals("20", tts.get().row(ByteBuffer.wrap("13".getBytes())).fam("9").qual("17").toString()); // try different types for cf Assert.assertEquals("20", tts.get().row("13").fam(9).qual("17").toString()); Assert.assertEquals("20", tts.get().row("13").fam(9l).qual("17").toString()); Assert.assertEquals("20", tts.get().row("13").fam("9").qual("17").toString()); Assert.assertEquals("20", tts.get().row("13").fam("9".getBytes()).qual("17").toString()); Assert.assertEquals("20", tts.get().row("13").fam(ByteBuffer.wrap("9".getBytes())).qual("17").toString()); // try different types for cq Assert.assertEquals("20", tts.get().row("13").fam("9").qual("17").toString()); Assert.assertEquals("20", tts.get().row("13").fam("9").qual(17l).toString()); Assert.assertEquals("20", tts.get().row("13").fam("9").qual(17).toString()); Assert.assertEquals("20", tts.get().row("13").fam("9").qual("17".getBytes()).toString()); Assert.assertEquals("20", tts.get().row("13").fam("9").qual(ByteBuffer.wrap("17".getBytes())).toString()); ms.close(); tts.close(); } @Test public void testWrite() throws Exception { TypeLayer tl = new TypeLayer(new StringEncoder()); MockTransactionBase tt = new MockTransactionBase("r1,cf1:cq1,v1", "r1,cf1:cq2,v2", "r1,cf1:cq3,9", "r2,cf2:7,12", "r2,cf2:8,13", "13,9:17,20", "13,9:18,30", "13,9:19,40", "13,9:20,50"); TypedTransactionBase ttx = tl.wrap(tt); // test increments data Assert.assertEquals(20, ttx.mutate().row("13").fam("9").qual("17").increment(1)); Assert.assertEquals(30, ttx.mutate().row("13").fam("9").qual(18).increment(2)); Assert.assertEquals(40, ttx.mutate().row("13").fam("9").qual(19l).increment(3)); Assert.assertEquals(50, ttx.mutate().row("13").fam("9").qual("20".getBytes()).increment(4)); // increment non existent Assert.assertEquals(0, ttx.mutate().row("13").fam("9").qual(Bytes.of("21")).increment(5)); // increment non existent Assert.assertEquals(0, ttx.mutate().row("13").col(new Column("9", "22")).increment(6)); // increment non existent Assert.assertEquals(0, ttx.mutate().row("13").fam("9").qual(ByteBuffer.wrap("23".getBytes())).increment(7)); Assert.assertEquals(MockTransactionBase.toRCVM("13,9:17,21", "13,9:18,32", "13,9:19,43", "13,9:20,54", "13,9:21,5", "13,9:22,6", "13,9:23,7"), tt.setData); tt.setData.clear(); // test increments long Assert.assertEquals(20l, ttx.mutate().row("13").fam("9").qual("17").increment(1l)); Assert.assertEquals(30l, ttx.mutate().row("13").fam("9").qual(18).increment(2l)); Assert.assertEquals(40l, ttx.mutate().row("13").fam("9").qual(19l).increment(3l)); Assert.assertEquals(50l, ttx.mutate().row("13").fam("9").qual("20".getBytes()).increment(4l)); // increment non existent Assert.assertEquals(0l, ttx.mutate().row("13").fam("9").qual(Bytes.of("21")).increment(5l)); // increment non existent Assert.assertEquals(0l, ttx.mutate().row("13").col(new Column("9", "22")).increment(6l)); // increment non existent Assert.assertEquals(0l, ttx.mutate().row("13").fam("9").qual(ByteBuffer.wrap("23".getBytes())).increment(7l)); Assert.assertEquals(MockTransactionBase.toRCVM("13,9:17,21", "13,9:18,32", "13,9:19,43", "13,9:20,54", "13,9:21,5", "13,9:22,6", "13,9:23,7"), tt.setData); tt.setData.clear(); // test setting data ttx.mutate().row("13").fam("9").qual("16").set(); ttx.mutate().row("13").fam("9").qual("17").set(3); ttx.mutate().row("13").fam("9").qual(18).set(4l); ttx.mutate().row("13").fam("9").qual(19l).set("5"); ttx.mutate().row("13").fam("9").qual("20".getBytes()).set("6".getBytes()); ttx.mutate().row("13").col(new Column("9", "21")).set("7".getBytes()); ttx.mutate().row("13").fam("9").qual(ByteBuffer.wrap("22".getBytes())) .set(ByteBuffer.wrap("8".getBytes())); ttx.mutate().row("13").fam("9").qual("23").set(2.54f); ttx.mutate().row("13").fam("9").qual("24").set(-6.135d); ttx.mutate().row("13").fam("9").qual("25").set(false); Assert.assertEquals( MockTransactionBase.toRCVM("13,9:16,", "13,9:17,3", "13,9:18,4", "13,9:19,5", "13,9:20,6", "13,9:21,7", "13,9:22,8", "13,9:23,2.54", "13,9:24,-6.135", "13,9:25,false"), tt.setData); tt.setData.clear(); // test deleting data ttx.mutate().row("13").fam("9").qual("17").delete(); ttx.mutate().row("13").fam("9").qual(18).delete(); ttx.mutate().row("13").fam("9").qual(19l).delete(); ttx.mutate().row("13").fam("9").qual("20".getBytes()).delete(); ttx.mutate().row("13").col(new Column("9", "21")).delete(); ttx.mutate().row("13").fam("9").qual(ByteBuffer.wrap("22".getBytes())).delete(); Assert.assertEquals( MockTransactionBase.toRCM("13,9:17", "13,9:18", "13,9:19", "13,9:20", "13,9:21", "13,9:22"), tt.deletes); tt.deletes.clear(); Assert.assertEquals(0, tt.setData.size()); Assert.assertEquals(0, tt.weakNotifications.size()); // test weak notifications ttx.mutate().row("13").fam("9").qual("17").weaklyNotify(); ttx.mutate().row("13").fam("9").qual(18).weaklyNotify(); ttx.mutate().row("13").fam("9").qual(19l).weaklyNotify(); ttx.mutate().row("13").fam("9").qual("20".getBytes()).weaklyNotify(); ttx.mutate().row("13").col(new Column("9", "21")).weaklyNotify(); ttx.mutate().row("13").fam("9").qual(ByteBuffer.wrap("22".getBytes())).weaklyNotify(); Assert.assertEquals( MockTransactionBase.toRCM("13,9:17", "13,9:18", "13,9:19", "13,9:20", "13,9:21", "13,9:22"), tt.weakNotifications); tt.weakNotifications.clear(); Assert.assertEquals(0, tt.setData.size()); Assert.assertEquals(0, tt.deletes.size()); } @Test public void testMultiRow() throws Exception { TypeLayer tl = new TypeLayer(new StringEncoder()); MockTransactionBase tt = new MockTransactionBase("11,cf1:cq1,1", "11,cf1:cq2,2", "12,cf1:cq1,3", "12,cf1:cq2,4", "13,cf1:cq1,5", "13,cf1:cq2,6"); TypedTransactionBase ttx = tl.wrap(tt); Bytes br1 = Bytes.of("11"); Bytes br2 = Bytes.of("12"); Bytes br3 = Bytes.of("13"); Column c1 = new Column("cf1", "cq1"); Column c2 = new Column("cf1", "cq2"); Map<Bytes, Map<Column, Value>> map1 = ttx.get().rows(Arrays.asList(br1, br2)).columns(c1).toBytesMap(); Assert.assertEquals(map1, ttx.get().rows(br1, br2).columns(c1).toBytesMap()); Assert.assertEquals("1", map1.get(br1).get(c1).toString()); Assert.assertEquals("1", map1.get(br1).get(c1).toString("5")); Assert.assertEquals((Long) (1l), map1.get(br1).get(c1).toLong()); Assert.assertEquals(1l, map1.get(br1).get(c1).toLong(5)); Assert.assertEquals((Integer) (1), map1.get(br1).get(c1).toInteger()); Assert.assertEquals(1, map1.get(br1).get(c1).toInteger(5)); Assert.assertEquals("5", map1.get(br3).get(c1).toString("5")); Assert.assertNull(map1.get(br3).get(c1).toString()); Assert.assertEquals(5l, map1.get(br3).get(c1).toLong(5l)); Assert.assertNull(map1.get(br3).get(c1).toLong()); Assert.assertEquals(5, map1.get(br1).get(c2).toInteger(5)); Assert.assertNull(map1.get(br1).get(c2).toInteger()); Assert.assertEquals(2, map1.size()); Assert.assertEquals(1, map1.get(br1).size()); Assert.assertEquals(1, map1.get(br2).size()); Assert.assertEquals("3", map1.get(br2).get(c1).toString()); Map<String, Map<Column, Value>> map2 = ttx.get().rowsString(Arrays.asList("11", "13")).columns(c1).toStringMap(); Assert.assertEquals(map2, ttx.get().rowsString("11", "13").columns(c1).toStringMap()); Assert.assertEquals(2, map2.size()); Assert.assertEquals(1, map2.get("11").size()); Assert.assertEquals(1, map2.get("13").size()); Assert.assertEquals((Long) (1l), map2.get("11").get(c1).toLong()); Assert.assertEquals(5l, map2.get("13").get(c1).toLong(6)); Map<Long, Map<Column, Value>> map3 = ttx.get().rowsLong(Arrays.asList(11l, 13l)).columns(c1).toLongMap(); Assert.assertEquals(map3, ttx.get().rowsLong(11l, 13l).columns(c1).toLongMap()); Assert.assertEquals(2, map3.size()); Assert.assertEquals(1, map3.get(11l).size()); Assert.assertEquals(1, map3.get(13l).size()); Assert.assertEquals((Long) (1l), map3.get(11l).get(c1).toLong()); Assert.assertEquals(5l, map3.get(13l).get(c1).toLong(6)); Map<Integer, Map<Column, Value>> map4 = ttx.get().rowsInteger(Arrays.asList(11, 13)).columns(c1).toIntegerMap(); Assert.assertEquals(map4, ttx.get().rowsInteger(11, 13).columns(c1).toIntegerMap()); Assert.assertEquals(2, map4.size()); Assert.assertEquals(1, map4.get(11).size()); Assert.assertEquals(1, map4.get(13).size()); Assert.assertEquals((Long) (1l), map4.get(11).get(c1).toLong()); Assert.assertEquals(5l, map4.get(13).get(c1).toLong(6)); Map<Integer, Map<Column, Value>> map5 = ttx.get() .rowsBytes(Arrays.asList("11".getBytes(), "13".getBytes())).columns(c1).toIntegerMap(); Assert.assertEquals(map5, ttx.get().rowsBytes("11".getBytes(), "13".getBytes()).columns(c1).toIntegerMap()); Assert.assertEquals(2, map5.size()); Assert.assertEquals(1, map5.get(11).size()); Assert.assertEquals(1, map5.get(13).size()); Assert.assertEquals((Long) (1l), map5.get(11).get(c1).toLong()); Assert.assertEquals(5l, map5.get(13).get(c1).toLong(6)); Map<Integer, Map<Column, Value>> map6 = ttx.get() .rowsByteBuffers( Arrays.asList(ByteBuffer.wrap("11".getBytes()), ByteBuffer.wrap("13".getBytes()))) .columns(c1).toIntegerMap(); Assert.assertEquals(map6, ttx.get() .rowsByteBuffers(ByteBuffer.wrap("11".getBytes()), ByteBuffer.wrap("13".getBytes())) .columns(c1).toIntegerMap()); Assert.assertEquals(2, map6.size()); Assert.assertEquals(1, map6.get(11).size()); Assert.assertEquals(1, map6.get(13).size()); Assert.assertEquals((Long) (1l), map6.get(11).get(c1).toLong()); Assert.assertEquals(5l, map6.get(13).get(c1).toLong(6)); } @Test public void testBasic() throws Exception { TypeLayer tl = new TypeLayer(new StringEncoder()); MockTransactionBase tt = new MockTransactionBase("r1,cf1:cq1,v1", "r1,cf1:cq2,v2", "r1,cf1:cq3,9", "r2,cf2:7,12", "r2,cf2:8,13", "13,9:17,20", "13,9:18,20", "13,9:19,20", "13,9:20,20"); TypedTransactionBase ttx = tl.wrap(tt); Assert.assertEquals(Bytes.of("12"), ttx.get(Bytes.of("r2"), new Column("cf2", "7"))); Assert.assertNull(ttx.get(Bytes.of("r2"), new Column("cf2", "9"))); Map<Column, Bytes> map = ttx.get(Bytes.of("r2"), Set.of(new Column("cf2", "7"), new Column("cf2", "8"))); Assert.assertEquals(2, map.size()); Assert.assertEquals("12", map.get(new Column("cf2", "7")).toString()); Assert.assertEquals("13", map.get(new Column("cf2", "8")).toString()); map = ttx.get(Bytes.of("r6"), Set.of(new Column("cf2", "7"), new Column("cf2", "8"))); Assert.assertEquals(0, map.size()); ttx.set(Bytes.of("r6"), new Column("cf2", "7"), Bytes.of("3")); Assert.assertEquals(MockTransactionBase.toRCVM("r6,cf2:7,3"), tt.setData); tt.setData.clear(); Map<Bytes, Map<Column, Bytes>> map2 = ttx.get(Set.of(Bytes.of("r1"), Bytes.of("r2")), Set.of(new Column("cf1", "cq1"), new Column("cf2", "8"))); Assert.assertEquals(MockTransactionBase.toRCVM("r1,cf1:cq1,v1", "r2,cf2:8,13"), map2); ttx.delete(Bytes.of("r6"), new Column("cf2", "7")); Assert.assertEquals(MockTransactionBase.toRCM("r6,cf2:7"), tt.deletes); tt.deletes.clear(); ttx.setWeakNotification(Bytes.of("r6"), new Column("cf2", "8")); Assert.assertEquals(MockTransactionBase.toRCM("r6,cf2:8"), tt.weakNotifications); tt.weakNotifications.clear(); } }
5,943
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/types/MockTransaction.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import org.apache.fluo.api.client.Transaction; import org.apache.fluo.api.exceptions.CommitException; public class MockTransaction extends MockTransactionBase implements Transaction { MockTransaction(String... entries) { super(entries); } @Override public void commit() throws CommitException { // does nothing } @Override public void close() { // no resources to close } }
5,944
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/combine/SplitsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.google.common.collect.Lists; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.recipes.core.combine.CombineQueue.Optimizer; import org.apache.fluo.recipes.core.common.TableOptimizations; import org.junit.Assert; import org.junit.Test; public class SplitsTest { private static List<Bytes> sort(List<Bytes> in) { ArrayList<Bytes> out = new ArrayList<>(in); Collections.sort(out); return out; } @Test public void testSplits() { FluoConfiguration fluoConfig = new FluoConfiguration(); CombineQueue.configure("foo").keyType(String.class).valueType(Long.class).buckets(3) .bucketsPerTablet(1).save(fluoConfig); TableOptimizations tableOptim1 = new Optimizer().getTableOptimizations("foo", fluoConfig.getAppConfiguration()); List<Bytes> expected1 = Lists.transform( Arrays.asList("foo:d:1", "foo:d:2", "foo:d:~", "foo:u:1", "foo:u:2", "foo:u:~"), Bytes::of); Assert.assertEquals(expected1, sort(tableOptim1.getSplits())); CombineQueue.configure("bar").keyType(String.class).valueType(Long.class).buckets(6) .bucketsPerTablet(2).save(fluoConfig); TableOptimizations tableOptim2 = new Optimizer().getTableOptimizations("bar", fluoConfig.getAppConfiguration()); List<Bytes> expected2 = Lists.transform( Arrays.asList("bar:d:2", "bar:d:4", "bar:d:~", "bar:u:2", "bar:u:4", "bar:u:~"), Bytes::of); Assert.assertEquals(expected2, sort(tableOptim2.getSplits())); } }
5,945
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/combine/OptionsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; import org.junit.Assert; import org.junit.Test; public class OptionsTest { @Test public void testExportQueueOptions() { FluoConfiguration conf = new FluoConfiguration(); CombineQueue.configure("Q1").keyType("KT").valueType("VT").buckets(100).save(conf); CombineQueue.configure("Q2").keyType("KT2").valueType("VT2").buckets(200).bucketsPerTablet(20) .bufferSize(1000000).save(conf); SimpleConfiguration appConfig = conf.getAppConfiguration(); Assert.assertEquals(CqConfigurator.getKeyType("Q1", appConfig), "KT"); Assert.assertEquals(CqConfigurator.getValueType("Q1", appConfig), "VT"); Assert.assertEquals(CqConfigurator.getNumBucket("Q1", appConfig), 100); Assert.assertEquals(CqConfigurator.getBucketsPerTablet("Q1", appConfig), CqConfigurator.DEFAULT_BUCKETS_PER_TABLET); Assert.assertEquals(CqConfigurator.getBufferSize("Q1", appConfig), CqConfigurator.DEFAULT_BUFFER_SIZE); Assert.assertEquals(CqConfigurator.getKeyType("Q2", appConfig), "KT2"); Assert.assertEquals(CqConfigurator.getValueType("Q2", appConfig), "VT2"); Assert.assertEquals(CqConfigurator.getNumBucket("Q2", appConfig), 200); Assert.assertEquals(CqConfigurator.getBucketsPerTablet("Q2", appConfig), 20); Assert.assertEquals(CqConfigurator.getBufferSize("Q2", appConfig), 1000000); } }
5,946
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/combine
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/combine/it/CombineQueueTreeIT.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine.it; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.fluo.api.client.FluoClient; import org.apache.fluo.api.client.FluoFactory; import org.apache.fluo.api.client.Snapshot; import org.apache.fluo.api.client.Transaction; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.RowColumnValue; import org.apache.fluo.api.data.Span; import org.apache.fluo.api.mini.MiniFluo; import org.apache.fluo.api.observer.ObserverProvider; import org.apache.fluo.recipes.core.combine.ChangeObserver.Change; import org.apache.fluo.recipes.core.combine.CombineQueue; import org.apache.fluo.recipes.core.combine.SummingCombiner; import org.apache.fluo.recipes.core.map.it.TestSerializer; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class CombineQueueTreeIT { private static final String CQ_XYT_ID = "xyt"; private static final String CQ_XY_ID = "xy"; private static final String CQ_XT_ID = "xt"; private static final String CQ_YT_ID = "yt"; private static final String CQ_X_ID = "x"; private static final String CQ_T_ID = "t"; private static final String CQ_Y_ID = "y"; public static class CqitObserverProvider implements ObserverProvider { @Override public void provide(Registry or, Context ctx) { // Link combine queues into a tree of combine queues. SimpleConfiguration appCfg = ctx.getAppConfiguration(); CombineQueue<String, Long> xytCq = CombineQueue.getInstance(CQ_XYT_ID, appCfg); CombineQueue<String, Long> xyCq = CombineQueue.getInstance(CQ_XY_ID, appCfg); CombineQueue<String, Long> ytCq = CombineQueue.getInstance(CQ_YT_ID, appCfg); CombineQueue<String, Long> xtCq = CombineQueue.getInstance(CQ_XT_ID, appCfg); CombineQueue<String, Long> xCq = CombineQueue.getInstance(CQ_X_ID, appCfg); CombineQueue<String, Long> tCq = CombineQueue.getInstance(CQ_T_ID, appCfg); CombineQueue<String, Long> yCq = CombineQueue.getInstance(CQ_Y_ID, appCfg); xytCq.registerObserver(or, new SummingCombiner<>(), (tx, changes) -> { Map<String, Long> xtUpdates = new HashMap<>(); Map<String, Long> ytUpdates = new HashMap<>(); Map<String, Long> xyUpdates = new HashMap<>(); for (Change<String, Long> change : changes) { String[] fields = change.getKey().split(":"); long delta = change.getNewValue().orElse(0L) - change.getOldValue().orElse(0L); xtUpdates.merge(fields[0] + ":" + fields[2], delta, Long::sum); ytUpdates.merge(fields[1] + ":" + fields[2], delta, Long::sum); xyUpdates.merge(fields[0] + ":" + fields[1], delta, Long::sum); } xtCq.addAll(tx, xtUpdates); ytCq.addAll(tx, ytUpdates); xyCq.addAll(tx, xyUpdates); invert("xyt", tx, changes); }); xyCq.registerObserver(or, new SummingCombiner<>(), (tx, changes) -> { Map<String, Long> xUpdates = new HashMap<>(); Map<String, Long> yUpdates = new HashMap<>(); for (Change<String, Long> change : changes) { String[] fields = change.getKey().split(":"); long delta = change.getNewValue().orElse(0L) - change.getOldValue().orElse(0L); xUpdates.merge(fields[0], delta, Long::sum); yUpdates.merge(fields[1], delta, Long::sum); } xCq.addAll(tx, xUpdates); yCq.addAll(tx, yUpdates); invert("xy", tx, changes); }); xtCq.registerObserver(or, new SummingCombiner<>(), (tx, changes) -> { Map<String, Long> tUpdates = new HashMap<>(); for (Change<String, Long> change : changes) { String[] fields = change.getKey().split(":"); long delta = change.getNewValue().orElse(0L) - change.getOldValue().orElse(0L); tUpdates.merge(fields[1], delta, Long::sum); } tCq.addAll(tx, tUpdates); invert("xt", tx, changes); }); ytCq.registerObserver(or, new SummingCombiner<>(), (tx, changes) -> { invert("yt", tx, changes); }); xCq.registerObserver(or, new SummingCombiner<>(), (tx, changes) -> { invert("x", tx, changes); }); tCq.registerObserver(or, new SummingCombiner<>(), (tx, changes) -> { invert("t", tx, changes); }); yCq.registerObserver(or, new SummingCombiner<>(), (tx, changes) -> { invert("y", tx, changes); }); } private static void invert(String prefix, TransactionBase tx, Iterable<Change<String, Long>> changes) { for (Change<String, Long> change : changes) { change.getOldValue().ifPresent( val -> tx.delete("inv:" + prefix + ":" + val, new Column("inv", change.getKey()))); change.getNewValue().ifPresent( val -> tx.set("inv:" + prefix + ":" + val, new Column("inv", change.getKey()), "")); } } } private MiniFluo miniFluo; @Before public void setUpFluo() throws Exception { FileUtils.deleteQuietly(new File("target/mini")); FluoConfiguration props = new FluoConfiguration(); props.setApplicationName("eqt"); props.setWorkerThreads(20); props.setMiniDataDir("target/mini"); CombineQueue.configure(CQ_XYT_ID).keyType(String.class).valueType(Long.class).buckets(7) .save(props); CombineQueue.configure(CQ_XT_ID).keyType(String.class).valueType(Long.class).buckets(7) .save(props); CombineQueue.configure(CQ_XY_ID).keyType(String.class).valueType(Long.class).buckets(7) .save(props); CombineQueue.configure(CQ_YT_ID).keyType(String.class).valueType(Long.class).buckets(7) .save(props); CombineQueue.configure(CQ_X_ID).keyType(String.class).valueType(Long.class).buckets(7) .save(props); CombineQueue.configure(CQ_T_ID).keyType(String.class).valueType(Long.class).buckets(7) .save(props); CombineQueue.configure(CQ_Y_ID).keyType(String.class).valueType(Long.class).buckets(7) .save(props); props.setObserverProvider(CqitObserverProvider.class); SimpleSerializer.setSerializer(props, TestSerializer.class); miniFluo = FluoFactory.newMiniFluo(props); } private static Map<String, Long> merge(Map<String, Long> m1, Map<String, Long> m2) { Map<String, Long> ret = new HashMap<>(m1); m2.forEach((k, v) -> ret.merge(k, v, Long::sum)); return ret; } private static Map<String, Long> rollup(Map<String, Long> m, String rollupFields) { boolean useX = rollupFields.contains("x"); boolean useY = rollupFields.contains("y"); boolean useTime = rollupFields.contains("t"); Map<String, Long> ret = new HashMap<>(); m.forEach((k, v) -> { String[] fields = k.split(":"); String nk = (useX ? fields[0] : "") + (useY ? ((useX ? ":" : "") + fields[1]) : "") + (useTime ? ((useX || useY ? ":" : "") + fields[2]) : ""); ret.merge(nk, v, Long::sum); }); return ret; } private static Map<String, Long> readRollup(Snapshot snap, String rollupFields) { Map<String, Long> ret = new HashMap<>(); String prefix = "inv:" + rollupFields + ":"; for (RowColumnValue rcv : snap.scanner().over(Span.prefix("inv:" + rollupFields + ":")) .build()) { String row = rcv.getsRow(); long count = Long.valueOf(row.substring(prefix.length(), row.length())); Assert.assertNull(ret.put(rcv.getColumn().getsQualifier(), count)); } return ret; } @Test public void testCqTree() { try (FluoClient fc = FluoFactory.newClient(miniFluo.getClientConfiguration())) { CombineQueue<String, Long> xytCq = CombineQueue.getInstance(CQ_XYT_ID, fc.getAppConfiguration()); Map<String, Long> updates1 = new HashMap<>(); updates1.put("5:4:23", 1L); updates1.put("5:5:23", 1L); updates1.put("7:5:23", 1L); updates1.put("9:2:23", 1L); updates1.put("5:4:29", 1L); updates1.put("6:6:29", 1L); updates1.put("7:5:29", 1L); updates1.put("9:3:29", 1L); updates1.put("3:3:31", 1L); try (Transaction tx = fc.newTransaction()) { xytCq.addAll(tx, updates1); tx.commit(); } miniFluo.waitForObservers(); try (Snapshot snap = fc.newSnapshot()) { for (String fieldsNames : new String[] {"x", "y", "t", "xy", "xt", "yt", "xyt"}) { Map<String, Long> expected = rollup(updates1, fieldsNames); Map<String, Long> actual = readRollup(snap, fieldsNames); Assert.assertEquals(expected, actual); } } Map<String, Long> updates2 = new HashMap<>(); updates2.put("7:5:23", 1L); updates2.put("6:6:7", 1L); updates2.put("4:3:31", 1L); updates2.put("9:1:23", 1L); updates2.put("1:2:3", 1L); try (Transaction tx = fc.newTransaction()) { xytCq.addAll(tx, updates2); tx.commit(); } miniFluo.waitForObservers(); try (Snapshot snap = fc.newSnapshot()) { for (String fieldsNames : new String[] {"x", "y", "t", "xy", "xt", "yt", "xyt"}) { Map<String, Long> expected = rollup(merge(updates1, updates2), fieldsNames); Map<String, Long> actual = readRollup(snap, fieldsNames); Assert.assertEquals(expected, actual); } } } } @After public void tearDownFluo() throws Exception { if (miniFluo != null) { miniFluo.close(); } } }
5,947
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/common/TestGrouping.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.common; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.recipes.core.combine.CombineQueue; import org.apache.fluo.recipes.core.combine.CombineQueue.Optimizer; import org.apache.fluo.recipes.core.export.ExportQueue; import org.junit.Assert; import org.junit.Test; public class TestGrouping { @Test public void testTabletGrouping() { FluoConfiguration conf = new FluoConfiguration(); CombineQueue.configure("m1").keyType("kt").valueType("vt").buckets(119).save(conf); CombineQueue.configure("m2").keyType("kt").valueType("vt").buckets(3).save(conf); ExportQueue.configure("eq1").keyType("kt").valueType("vt").buckets(7).save(conf); ExportQueue.configure("eq2").keyType("kt").valueType("vt").buckets(3).save(conf); SimpleConfiguration appConfg = conf.getAppConfiguration(); TableOptimizations tableOptim = new Optimizer().getTableOptimizations("m1", appConfg); tableOptim.merge(new Optimizer().getTableOptimizations("m2", appConfg)); tableOptim.merge(new ExportQueue.Optimizer().getTableOptimizations("eq1", appConfg)); tableOptim.merge(new ExportQueue.Optimizer().getTableOptimizations("eq2", appConfg)); Pattern pattern = Pattern.compile(tableOptim.getTabletGroupingRegex()); Assert.assertEquals("m1:u:", group(pattern, "m1:u:f0c")); Assert.assertEquals("m1:d:", group(pattern, "m1:d:f0c")); Assert.assertEquals("m2:u:", group(pattern, "m2:u:abc")); Assert.assertEquals("m2:d:", group(pattern, "m2:d:590")); Assert.assertEquals("none", group(pattern, "m3:d:590")); Assert.assertEquals("eq1:", group(pattern, "eq1:f0c")); Assert.assertEquals("eq2:", group(pattern, "eq2:f0c")); Assert.assertEquals("none", group(pattern, "eq3:f0c")); // validate the assumptions this test is making Assert.assertTrue(tableOptim.getSplits().contains(Bytes.of("eq1#"))); Assert.assertTrue(tableOptim.getSplits().contains(Bytes.of("eq2#"))); Assert.assertTrue(tableOptim.getSplits().contains(Bytes.of("eq1:~"))); Assert.assertTrue(tableOptim.getSplits().contains(Bytes.of("eq2:~"))); Assert.assertTrue(tableOptim.getSplits().contains(Bytes.of("m1:u:~"))); Assert.assertTrue(tableOptim.getSplits().contains(Bytes.of("m1:d:~"))); Assert.assertTrue(tableOptim.getSplits().contains(Bytes.of("m2:u:~"))); Assert.assertTrue(tableOptim.getSplits().contains(Bytes.of("m2:d:~"))); Set<String> expectedGroups = Set.of("m1:u:", "m1:d:", "m2:u:", "m2:d:", "eq1:", "eq2:"); // ensure all splits group as expected for (Bytes split : tableOptim.getSplits()) { String g = group(pattern, split.toString()); if (expectedGroups.contains(g)) { Assert.assertTrue(split.toString().startsWith(g)); } else { Assert.assertEquals("none", g); Assert.assertTrue(split.toString().equals("eq1#") || split.toString().equals("eq2#")); } } } private String group(Pattern pattern, String endRow) { Matcher m = pattern.matcher(endRow); if (m.matches() && m.groupCount() == 1) { return m.group(1); } return "none"; } }
5,948
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/common/TransientRegistryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.common; import java.util.HashSet; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.data.Bytes; import org.junit.Assert; import org.junit.Test; public class TransientRegistryTest { @Test public void testBasic() { FluoConfiguration fluoConfig = new FluoConfiguration(); HashSet<RowRange> expected = new HashSet<>(); TransientRegistry tr = new TransientRegistry(fluoConfig.getAppConfiguration()); RowRange rr1 = new RowRange(Bytes.of("pr1:g"), Bytes.of("pr1:q")); tr.addTransientRange("foo", rr1); expected.add(rr1); tr = new TransientRegistry(fluoConfig.getAppConfiguration()); Assert.assertEquals(expected, new HashSet<>(tr.getTransientRanges())); RowRange rr2 = new RowRange(Bytes.of("pr2:j"), Bytes.of("pr2:m")); tr.addTransientRange("bar", rr2); expected.add(rr2); tr = new TransientRegistry(fluoConfig.getAppConfiguration()); Assert.assertEquals(expected, new HashSet<>(tr.getTransientRanges())); } }
5,949
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map/SplitsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.google.common.collect.Lists; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.recipes.core.common.TableOptimizations; import org.junit.Assert; import org.junit.Test; @Deprecated public class SplitsTest { private static List<Bytes> sort(List<Bytes> in) { ArrayList<Bytes> out = new ArrayList<>(in); Collections.sort(out); return out; } @Test public void testSplits() { org.apache.fluo.recipes.core.map.CollisionFreeMap.Options opts = new org.apache.fluo.recipes.core.map.CollisionFreeMap.Options("foo", org.apache.fluo.recipes.core.map.it.WordCountCombiner.class, String.class, Long.class, 3); opts.setBucketsPerTablet(1); FluoConfiguration fluoConfig = new FluoConfiguration(); CollisionFreeMap.configure(fluoConfig, opts); TableOptimizations tableOptim1 = new CollisionFreeMap.Optimizer().getTableOptimizations("foo", fluoConfig.getAppConfiguration()); List<Bytes> expected1 = Lists.transform( Arrays.asList("foo:d:1", "foo:d:2", "foo:d:~", "foo:u:1", "foo:u:2", "foo:u:~"), Bytes::of); Assert.assertEquals(expected1, sort(tableOptim1.getSplits())); org.apache.fluo.recipes.core.map.CollisionFreeMap.Options opts2 = new org.apache.fluo.recipes.core.map.CollisionFreeMap.Options("bar", org.apache.fluo.recipes.core.map.it.WordCountCombiner.class, String.class, Long.class, 6); opts2.setBucketsPerTablet(2); CollisionFreeMap.configure(fluoConfig, opts2); TableOptimizations tableOptim2 = new CollisionFreeMap.Optimizer().getTableOptimizations("bar", fluoConfig.getAppConfiguration()); List<Bytes> expected2 = Lists.transform( Arrays.asList("bar:d:2", "bar:d:4", "bar:d:~", "bar:u:2", "bar:u:4", "bar:u:~"), Bytes::of); Assert.assertEquals(expected2, sort(tableOptim2.getSplits())); } }
5,950
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map/OptionsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map; import org.apache.fluo.api.config.FluoConfiguration; import org.junit.Assert; import org.junit.Test; @Deprecated public class OptionsTest { @Test public void testExportQueueOptions() { FluoConfiguration conf = new FluoConfiguration(); CollisionFreeMap.configure(conf, new org.apache.fluo.recipes.core.map.CollisionFreeMap.Options("Q1", "CT", "KT", "VT", 100)); CollisionFreeMap.configure(conf, new org.apache.fluo.recipes.core.map.CollisionFreeMap.Options("Q2", "CT2", "KT2", "VT2", 200).setBucketsPerTablet(20).setBufferSize(1000000)); org.apache.fluo.recipes.core.map.CollisionFreeMap.Options opts1 = new org.apache.fluo.recipes.core.map.CollisionFreeMap.Options("Q1", conf.getAppConfiguration()); Assert.assertEquals(opts1.combinerType, "CT"); Assert.assertEquals(opts1.keyType, "KT"); Assert.assertEquals(opts1.valueType, "VT"); Assert.assertEquals(opts1.numBuckets, 100); Assert.assertEquals(opts1.bucketsPerTablet.intValue(), org.apache.fluo.recipes.core.map.CollisionFreeMap.Options.DEFAULT_BUCKETS_PER_TABLET); Assert.assertEquals(opts1.bufferSize.intValue(), org.apache.fluo.recipes.core.map.CollisionFreeMap.Options.DEFAULT_BUFFER_SIZE); org.apache.fluo.recipes.core.map.CollisionFreeMap.Options opts2 = new org.apache.fluo.recipes.core.map.CollisionFreeMap.Options("Q2", conf.getAppConfiguration()); Assert.assertEquals(opts2.combinerType, "CT2"); Assert.assertEquals(opts2.keyType, "KT2"); Assert.assertEquals(opts2.valueType, "VT2"); Assert.assertEquals(opts2.numBuckets, 200); Assert.assertEquals(opts2.bucketsPerTablet.intValue(), 20); Assert.assertEquals(opts2.bufferSize.intValue(), 1000000); } }
5,951
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map/it/CollisionFreeMapIT.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map.it; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.apache.commons.io.FileUtils; import org.apache.fluo.api.client.FluoClient; import org.apache.fluo.api.client.FluoFactory; import org.apache.fluo.api.client.LoaderExecutor; import org.apache.fluo.api.client.Snapshot; import org.apache.fluo.api.client.Transaction; import org.apache.fluo.api.client.scanner.CellScanner; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.RowColumnValue; import org.apache.fluo.api.data.Span; import org.apache.fluo.api.mini.MiniFluo; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @Deprecated // TODO migrate to CombineQueue test when removing CFM public class CollisionFreeMapIT { private MiniFluo miniFluo; private org.apache.fluo.recipes.core.map.CollisionFreeMap<String, Long> wcMap; static final String MAP_ID = "wcm"; @Before public void setUpFluo() throws Exception { FileUtils.deleteQuietly(new File("target/mini")); FluoConfiguration props = new FluoConfiguration(); props.setApplicationName("eqt"); props.setWorkerThreads(20); props.setMiniDataDir("target/mini"); props.addObserver( new org.apache.fluo.api.config.ObserverSpecification(DocumentObserver.class.getName())); SimpleSerializer.setSerializer(props, TestSerializer.class); org.apache.fluo.recipes.core.map.CollisionFreeMap.configure(props, new org.apache.fluo.recipes.core.map.CollisionFreeMap.Options(MAP_ID, WordCountCombiner.class, WordCountObserver.class, String.class, Long.class, 17)); miniFluo = FluoFactory.newMiniFluo(props); wcMap = org.apache.fluo.recipes.core.map.CollisionFreeMap.getInstance(MAP_ID, props.getAppConfiguration()); } @After public void tearDownFluo() throws Exception { if (miniFluo != null) { miniFluo.close(); } } private Map<String, Long> getComputedWordCounts(FluoClient fc) { Map<String, Long> counts = new HashMap<>(); try (Snapshot snap = fc.newSnapshot()) { CellScanner scanner = snap.scanner().over(Span.prefix("iwc:")).build(); for (RowColumnValue rcv : scanner) { String[] tokens = rcv.getsRow().split(":"); String word = tokens[2]; Long count = Long.valueOf(tokens[1]); Assert.assertFalse("Word seen twice in index " + word, counts.containsKey(word)); counts.put(word, count); } } return counts; } private Map<String, Long> computeWordCounts(FluoClient fc) { Map<String, Long> counts = new HashMap<>(); try (Snapshot snap = fc.newSnapshot()) { CellScanner scanner = snap.scanner().over(Span.prefix("d:")).fetch(new Column("content", "current")).build(); for (RowColumnValue rcv : scanner) { String[] words = rcv.getsValue().split("\\s+"); for (String word : words) { if (word.isEmpty()) { continue; } counts.merge(word, 1L, Long::sum); } } } return counts; } @Test public void testGet() { try (FluoClient fc = FluoFactory.newClient(miniFluo.getClientConfiguration())) { try (Transaction tx = fc.newTransaction()) { wcMap.update(tx, Map.of("cat", 2L, "dog", 5L)); tx.commit(); } try (Transaction tx = fc.newTransaction()) { wcMap.update(tx, Map.of("cat", 1L, "dog", 1L)); tx.commit(); } try (Transaction tx = fc.newTransaction()) { wcMap.update(tx, Map.of("cat", 1L, "dog", 1L, "fish", 2L)); tx.commit(); } // try reading possibly before observer combines... will either see outstanding updates or a // current value try (Snapshot snap = fc.newSnapshot()) { Assert.assertEquals((Long) 4L, wcMap.get(snap, "cat")); Assert.assertEquals((Long) 7L, wcMap.get(snap, "dog")); Assert.assertEquals((Long) 2L, wcMap.get(snap, "fish")); } miniFluo.waitForObservers(); // in this case there should be no updates, only a current value try (Snapshot snap = fc.newSnapshot()) { Assert.assertEquals((Long) 4L, wcMap.get(snap, "cat")); Assert.assertEquals((Long) 7L, wcMap.get(snap, "dog")); Assert.assertEquals((Long) 2L, wcMap.get(snap, "fish")); } Map<String, Long> expectedCounts = new HashMap<>(); expectedCounts.put("cat", 4L); expectedCounts.put("dog", 7L); expectedCounts.put("fish", 2L); Assert.assertEquals(expectedCounts, getComputedWordCounts(fc)); try (Transaction tx = fc.newTransaction()) { wcMap.update(tx, Map.of("cat", 1L, "dog", -7L)); tx.commit(); } // there may be outstanding update and a current value for the key in this case try (Snapshot snap = fc.newSnapshot()) { Assert.assertEquals((Long) 5L, wcMap.get(snap, "cat")); Assert.assertNull(wcMap.get(snap, "dog")); Assert.assertEquals((Long) 2L, wcMap.get(snap, "fish")); } miniFluo.waitForObservers(); try (Snapshot snap = fc.newSnapshot()) { Assert.assertEquals((Long) 5L, wcMap.get(snap, "cat")); Assert.assertNull(wcMap.get(snap, "dog")); Assert.assertEquals((Long) 2L, wcMap.get(snap, "fish")); } expectedCounts.put("cat", 5L); expectedCounts.remove("dog"); Assert.assertEquals(expectedCounts, getComputedWordCounts(fc)); } } @Test public void testBasic() { try (FluoClient fc = FluoFactory.newClient(miniFluo.getClientConfiguration())) { try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0001", "dog cat")); loader.execute(new DocumentLoader("0002", "cat hamster")); loader.execute(new DocumentLoader("0003", "milk bread cat food")); loader.execute(new DocumentLoader("0004", "zoo big cat")); } miniFluo.waitForObservers(); try (Snapshot snap = fc.newSnapshot()) { Assert.assertEquals((Long) 4L, wcMap.get(snap, "cat")); Assert.assertEquals((Long) 1L, wcMap.get(snap, "milk")); } Map<String, Long> expectedCounts = new HashMap<>(); expectedCounts.put("dog", 1L); expectedCounts.put("cat", 4L); expectedCounts.put("hamster", 1L); expectedCounts.put("milk", 1L); expectedCounts.put("bread", 1L); expectedCounts.put("food", 1L); expectedCounts.put("zoo", 1L); expectedCounts.put("big", 1L); Assert.assertEquals(expectedCounts, getComputedWordCounts(fc)); try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0001", "dog feline")); } miniFluo.waitForObservers(); expectedCounts.put("cat", 3L); expectedCounts.put("feline", 1L); Assert.assertEquals(expectedCounts, getComputedWordCounts(fc)); try (LoaderExecutor loader = fc.newLoaderExecutor()) { // swap contents of two documents... should not change doc counts loader.execute(new DocumentLoader("0003", "zoo big cat")); loader.execute(new DocumentLoader("0004", "milk bread cat food")); } miniFluo.waitForObservers(); Assert.assertEquals(expectedCounts, getComputedWordCounts(fc)); try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0003", "zoo big cat")); loader.execute(new DocumentLoader("0004", "zoo big cat")); } miniFluo.waitForObservers(); expectedCounts.put("zoo", 2L); expectedCounts.put("big", 2L); expectedCounts.remove("milk"); expectedCounts.remove("bread"); expectedCounts.remove("food"); Assert.assertEquals(expectedCounts, getComputedWordCounts(fc)); try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0002", "cat cat hamster hamster")); } miniFluo.waitForObservers(); expectedCounts.put("cat", 4L); expectedCounts.put("hamster", 2L); Assert.assertEquals(expectedCounts, getComputedWordCounts(fc)); try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0002", "dog hamster")); } miniFluo.waitForObservers(); expectedCounts.put("cat", 2L); expectedCounts.put("hamster", 1L); expectedCounts.put("dog", 2L); Assert.assertEquals(expectedCounts, getComputedWordCounts(fc)); } } private static String randDocId(Random rand) { return String.format("%04d", rand.nextInt(5000)); } private static String randomDocument(Random rand) { StringBuilder sb = new StringBuilder(); String sep = ""; for (int i = 2; i < rand.nextInt(18); i++) { sb.append(sep); sep = " "; sb.append(String.format("%05d", rand.nextInt(50000))); } return sb.toString(); } public void diff(Map<String, Long> m1, Map<String, Long> m2) { for (String word : m1.keySet()) { Long v1 = m1.get(word); Long v2 = m2.get(word); if (v2 == null || !v1.equals(v2)) { System.out.println(word + " " + v1 + " != " + v2); } } for (String word : m2.keySet()) { Long v1 = m1.get(word); Long v2 = m2.get(word); if (v1 == null) { System.out.println(word + " null != " + v2); } } } @Test public void testStress() throws Exception { try (FluoClient fc = FluoFactory.newClient(miniFluo.getClientConfiguration())) { Random rand = new Random(); try (LoaderExecutor loader = fc.newLoaderExecutor()) { for (int i = 0; i < 1000; i++) { loader.execute(new DocumentLoader(randDocId(rand), randomDocument(rand))); } } miniFluo.waitForObservers(); assertWordCountsEqual(fc); try (LoaderExecutor loader = fc.newLoaderExecutor()) { for (int i = 0; i < 100; i++) { loader.execute(new DocumentLoader(randDocId(rand), randomDocument(rand))); } } miniFluo.waitForObservers(); assertWordCountsEqual(fc); } } private void assertWordCountsEqual(FluoClient fc) { Map<String, Long> expected = computeWordCounts(fc); Map<String, Long> actual = getComputedWordCounts(fc); if (!expected.equals(actual)) { diff(expected, actual); Assert.fail(); } } }
5,952
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map/it/WordCountObserver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map.it; import java.util.Iterator; import java.util.Optional; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; @Deprecated // TODO move to CombineQueue test when removing CFM public class WordCountObserver extends org.apache.fluo.recipes.core.map.UpdateObserver<String, Long> { @Override public void updatingValues(TransactionBase tx, Iterator<org.apache.fluo.recipes.core.map.Update<String, Long>> updates) { while (updates.hasNext()) { org.apache.fluo.recipes.core.map.Update<String, Long> update = updates.next(); Optional<Long> oldVal = update.getOldValue(); Optional<Long> newVal = update.getNewValue(); if (oldVal.isPresent()) { String oldRow = String.format("iwc:%09d:%s", oldVal.get(), update.getKey()); tx.delete(Bytes.of(oldRow), new Column(Bytes.EMPTY, Bytes.EMPTY)); } if (newVal.isPresent()) { String newRow = String.format("iwc:%09d:%s", newVal.get(), update.getKey()); tx.set(Bytes.of(newRow), new Column(Bytes.EMPTY, Bytes.EMPTY), Bytes.EMPTY); } } } }
5,953
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map/it/DocumentLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map.it; import org.apache.fluo.recipes.core.types.TypedLoader; import org.apache.fluo.recipes.core.types.TypedTransactionBase; public class DocumentLoader extends TypedLoader { String docid; String doc; DocumentLoader(String docid, String doc) { this.docid = docid; this.doc = doc; } @Override public void load(TypedTransactionBase tx, Context context) throws Exception { tx.mutate().row("d:" + docid).fam("content").qual("new").set(doc); } }
5,954
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map/it/DocumentObserver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map.it; import java.util.HashMap; import java.util.Map; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; import org.apache.fluo.recipes.core.types.TypedObserver; import org.apache.fluo.recipes.core.types.TypedTransactionBase; @Deprecated // TODO move to CombineQueue test when removing CFM public class DocumentObserver extends TypedObserver { org.apache.fluo.recipes.core.map.CollisionFreeMap<String, Long> wcm; @Override public void init(Context context) throws Exception { wcm = org.apache.fluo.recipes.core.map.CollisionFreeMap.getInstance(CollisionFreeMapIT.MAP_ID, context.getAppConfiguration()); } @Override public ObservedColumn getObservedColumn() { return new ObservedColumn(new Column("content", "new"), NotificationType.STRONG); } static Map<String, Long> getWordCounts(String doc) { Map<String, Long> wordCounts = new HashMap<>(); String[] words = doc.split(" "); for (String word : words) { if (word.isEmpty()) { continue; } wordCounts.merge(word, 1L, Long::sum); } return wordCounts; } @Override public void process(TypedTransactionBase tx, Bytes row, Column col) { String newContent = tx.get().row(row).col(col).toString(); String currentContent = tx.get().row(row).fam("content").qual("current").toString(""); Map<String, Long> newWordCounts = getWordCounts(newContent); Map<String, Long> currentWordCounts = getWordCounts(currentContent); Map<String, Long> changes = calculateChanges(newWordCounts, currentWordCounts); wcm.update(tx, changes); tx.mutate().row(row).fam("content").qual("current").set(newContent); } private static Map<String, Long> calculateChanges(Map<String, Long> newCounts, Map<String, Long> currCounts) { Map<String, Long> changes = new HashMap<>(); // guava Maps class MapDifference<String, Long> diffs = Maps.difference(currCounts, newCounts); // compute the diffs for words that changed changes.putAll(Maps.transformValues(diffs.entriesDiffering(), vDiff -> vDiff.rightValue() - vDiff.leftValue())); // add all new words changes.putAll(diffs.entriesOnlyOnRight()); // subtract all words no longer present changes.putAll(Maps.transformValues(diffs.entriesOnlyOnLeft(), l -> l * -1)); return changes; } }
5,955
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map/it/TestSerializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map.it; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; public class TestSerializer implements SimpleSerializer { @Override public <T> byte[] serialize(T obj) { return obj.toString().getBytes(); } @SuppressWarnings("unchecked") @Override public <T> T deserialize(byte[] serObj, Class<T> clazz) { if (clazz.equals(Long.class)) { return (T) Long.valueOf(new String(serObj)); } if (clazz.equals(String.class)) { return (T) new String(serObj); } throw new IllegalArgumentException(); } @Override public void init(SimpleConfiguration appConfig) {} }
5,956
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map/it/WordCountCombiner.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map.it; import java.util.Iterator; import java.util.Optional; @Deprecated // TODO move to CombineQueue test when removing CFM public class WordCountCombiner implements org.apache.fluo.recipes.core.map.Combiner<String, Long> { @Override public Optional<Long> combine(String key, Iterator<Long> updates) { long sum = 0; while (updates.hasNext()) { sum += updates.next(); } if (sum == 0) { return Optional.empty(); } else { return Optional.of(sum); } } }
5,957
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/map/it/BigUpdateIT.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map.it; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import org.apache.commons.io.FileUtils; import org.apache.fluo.api.client.FluoClient; import org.apache.fluo.api.client.FluoFactory; import org.apache.fluo.api.client.Transaction; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.client.scanner.ColumnScanner; import org.apache.fluo.api.client.scanner.RowScanner; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.ColumnValue; import org.apache.fluo.api.data.Span; import org.apache.fluo.api.mini.MiniFluo; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; import org.apache.fluo.recipes.core.types.StringEncoder; import org.apache.fluo.recipes.core.types.TypeLayer; import org.apache.fluo.recipes.core.types.TypedSnapshot; import org.apache.fluo.recipes.core.types.TypedTransactionBase; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * This test configures a small buffer size and verifies that multiple passes are made to process * updates. */ @Deprecated // TODO migrate to CombineQueue test when removing CFM public class BigUpdateIT { private static final TypeLayer tl = new TypeLayer(new StringEncoder()); private MiniFluo miniFluo; private org.apache.fluo.recipes.core.map.CollisionFreeMap<String, Long> wcMap; static final String MAP_ID = "bu"; public static class LongCombiner implements org.apache.fluo.recipes.core.map.Combiner<String, Long> { @Override public Optional<Long> combine(String key, Iterator<Long> updates) { long[] count = new long[] {0}; updates.forEachRemaining(l -> count[0] += l); return Optional.of(count[0]); } } static final Column DSCOL = new Column("debug", "sum"); private static AtomicInteger globalUpdates = new AtomicInteger(0); public static class MyObserver extends org.apache.fluo.recipes.core.map.UpdateObserver<String, Long> { @Override public void updatingValues(TransactionBase tx, Iterator<org.apache.fluo.recipes.core.map.Update<String, Long>> updates) { TypedTransactionBase ttx = tl.wrap(tx); Map<String, Long> expectedOld = new HashMap<>(); while (updates.hasNext()) { org.apache.fluo.recipes.core.map.Update<String, Long> update = updates.next(); if (update.getOldValue().isPresent()) { expectedOld.put("side:" + update.getKey(), update.getOldValue().get()); } ttx.mutate().row("side:" + update.getKey()).col(DSCOL).set(update.getNewValue().get()); } // get last values set to verify same as passed in old value Map<String, Long> actualOld = Maps.transformValues( ttx.get().rowsString(expectedOld.keySet()).columns(Set.of(DSCOL)).toStringMap(), m -> m.get(DSCOL).toLong()); MapDifference<String, Long> diff = Maps.difference(expectedOld, actualOld); Assert.assertTrue(diff.toString(), diff.areEqual()); globalUpdates.incrementAndGet(); } } @Before public void setUpFluo() throws Exception { FileUtils.deleteQuietly(new File("target/mini")); FluoConfiguration props = new FluoConfiguration(); props.setApplicationName("eqt"); props.setWorkerThreads(20); props.setMiniDataDir("target/mini"); SimpleSerializer.setSerializer(props, TestSerializer.class); org.apache.fluo.recipes.core.map.CollisionFreeMap .configure(props, new org.apache.fluo.recipes.core.map.CollisionFreeMap.Options(MAP_ID, LongCombiner.class, MyObserver.class, String.class, Long.class, 2) .setBufferSize(1 << 10)); miniFluo = FluoFactory.newMiniFluo(props); wcMap = org.apache.fluo.recipes.core.map.CollisionFreeMap.getInstance(MAP_ID, props.getAppConfiguration()); globalUpdates.set(0); } @After public void tearDownFluo() throws Exception { if (miniFluo != null) { miniFluo.close(); } } @Test public void testBigUpdates() { try (FluoClient fc = FluoFactory.newClient(miniFluo.getClientConfiguration())) { updateMany(fc); miniFluo.waitForObservers(); int numUpdates = 0; try (TypedSnapshot snap = tl.wrap(fc.newSnapshot())) { checkUpdates(snap, 1, 1000); numUpdates = globalUpdates.get(); // there are two buckets, expect update processing at least twice per bucket Assert.assertTrue(numUpdates >= 4); } updateMany(fc); updateMany(fc); miniFluo.waitForObservers(); try (TypedSnapshot snap = tl.wrap(fc.newSnapshot())) { checkUpdates(snap, 3, 1000); numUpdates = globalUpdates.get() - numUpdates; Assert.assertTrue(numUpdates >= 4); } for (int i = 0; i < 10; i++) { updateMany(fc); } miniFluo.waitForObservers(); try (TypedSnapshot snap = tl.wrap(fc.newSnapshot())) { checkUpdates(snap, 13, 1000); numUpdates = globalUpdates.get() - numUpdates; Assert.assertTrue(numUpdates >= 4); } } } private void checkUpdates(TypedSnapshot snap, long expectedVal, long expectedRows) { RowScanner rows = snap.scanner().over(Span.prefix("side:")).byRow().build(); int row = 0; for (ColumnScanner columns : rows) { Assert.assertEquals(String.format("side:%06d", row++), columns.getsRow()); for (ColumnValue columnValue : columns) { Assert.assertEquals(new Column("debug", "sum"), columnValue.getColumn()); Assert.assertEquals("row : " + columns.getsRow(), "" + expectedVal, columnValue.getsValue()); } } Assert.assertEquals(expectedRows, row); } private void updateMany(FluoClient fc) { try (Transaction tx = fc.newTransaction()) { Map<String, Long> updates = new HashMap<>(); for (int i = 0; i < 1000; i++) { updates.put(String.format("%06d", i), 1L); } wcMap.update(tx, updates); tx.commit(); } } }
5,958
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export/OptionsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.export; import java.util.List; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; import org.junit.Assert; import org.junit.Test; public class OptionsTest { @Test @Deprecated public void testDeprecatedExportQueueOptions() { FluoConfiguration conf = new FluoConfiguration(); SimpleConfiguration ec1 = new SimpleConfiguration(); ec1.setProperty("ep1", "ev1"); ec1.setProperty("ep2", 3L); ExportQueue.configure(conf, new org.apache.fluo.recipes.core.export.ExportQueue.Options("Q1", "ET", "KT", "VT", 100)); ExportQueue.configure(conf, new org.apache.fluo.recipes.core.export.ExportQueue.Options("Q2", "ET2", "KT2", "VT2", 200) .setBucketsPerTablet(20).setBufferSize(1000000).setExporterConfiguration(ec1)); org.apache.fluo.recipes.core.export.ExportQueue.Options opts1 = new org.apache.fluo.recipes.core.export.ExportQueue.Options("Q1", conf.getAppConfiguration()); Assert.assertEquals(opts1.fluentCfg.exporterType, "ET"); Assert.assertEquals(opts1.fluentCfg.keyType, "KT"); Assert.assertEquals(opts1.fluentCfg.valueType, "VT"); Assert.assertEquals(opts1.fluentCfg.buckets, 100); Assert.assertEquals(opts1.fluentCfg.bucketsPerTablet.intValue(), FluentConfigurator.DEFAULT_BUCKETS_PER_TABLET); Assert.assertEquals(opts1.fluentCfg.bufferSize.intValue(), FluentConfigurator.DEFAULT_BUFFER_SIZE); org.apache.fluo.recipes.core.export.ExportQueue.Options opts2 = new org.apache.fluo.recipes.core.export.ExportQueue.Options("Q2", conf.getAppConfiguration()); Assert.assertEquals(opts2.fluentCfg.exporterType, "ET2"); Assert.assertEquals(opts2.fluentCfg.keyType, "KT2"); Assert.assertEquals(opts2.fluentCfg.valueType, "VT2"); Assert.assertEquals(opts2.fluentCfg.buckets, 200); Assert.assertEquals(opts2.fluentCfg.bucketsPerTablet.intValue(), 20); Assert.assertEquals(opts2.fluentCfg.bufferSize.intValue(), 1000000); SimpleConfiguration ec2 = opts2.getExporterConfiguration(); Assert.assertEquals("ev1", ec2.getString("ep1")); Assert.assertEquals(3, ec2.getInt("ep2")); List<org.apache.fluo.api.config.ObserverSpecification> obsSpecs = conf.getObserverSpecifications(); Assert.assertTrue(obsSpecs.size() == 2); for (org.apache.fluo.api.config.ObserverSpecification ospec : obsSpecs) { Assert.assertEquals(ExportObserver.class.getName(), ospec.getClassName()); String qid = ospec.getConfiguration().getString("queueId"); Assert.assertTrue(qid.equals("Q1") || qid.equals("Q2")); } } @Test public void testExportQueueOptions() { FluoConfiguration conf = new FluoConfiguration(); SimpleConfiguration ec1 = new SimpleConfiguration(); ec1.setProperty("ep1", "ev1"); ec1.setProperty("ep2", 3L); ExportQueue.configure("Q1").keyType("KT").valueType("VT").buckets(100).save(conf); ExportQueue.configure("Q2").keyType("KT2").valueType("VT2").buckets(200).bucketsPerTablet(20) .bufferSize(1000000).save(conf); FluentConfigurator opts1 = FluentConfigurator.load("Q1", conf.getAppConfiguration()); Assert.assertNull(opts1.exporterType); Assert.assertEquals(opts1.keyType, "KT"); Assert.assertEquals(opts1.valueType, "VT"); Assert.assertEquals(opts1.buckets, 100); Assert.assertEquals(opts1.bucketsPerTablet.intValue(), FluentConfigurator.DEFAULT_BUCKETS_PER_TABLET); Assert.assertEquals(opts1.bufferSize.intValue(), FluentConfigurator.DEFAULT_BUFFER_SIZE); FluentConfigurator opts2 = FluentConfigurator.load("Q2", conf.getAppConfiguration()); Assert.assertNull(opts2.exporterType); Assert.assertEquals(opts2.keyType, "KT2"); Assert.assertEquals(opts2.valueType, "VT2"); Assert.assertEquals(opts2.buckets, 200); Assert.assertEquals(opts2.bucketsPerTablet.intValue(), 20); Assert.assertEquals(opts2.bufferSize.intValue(), 1000000); } }
5,959
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export/it/GsonSerializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.export.it; import java.nio.charset.StandardCharsets; import com.google.gson.Gson; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; public class GsonSerializer implements SimpleSerializer { private Gson gson = new Gson(); @Override public void init(SimpleConfiguration appConfig) { } @Override public <T> byte[] serialize(T obj) { return gson.toJson(obj).getBytes(StandardCharsets.UTF_8); } @Override public <T> T deserialize(byte[] serObj, Class<T> clazz) { return gson.fromJson(new String(serObj, StandardCharsets.UTF_8), clazz); } }
5,960
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export/it/DocumentLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.export.it; import org.apache.fluo.recipes.core.types.TypedLoader; import org.apache.fluo.recipes.core.types.TypedTransactionBase; public class DocumentLoader extends TypedLoader { String docid; String refs[]; DocumentLoader(String docid, String... refs) { this.docid = docid; this.refs = refs; } @Override public void load(TypedTransactionBase tx, Context context) throws Exception { tx.mutate().row("d:" + docid).fam("content").qual("new").set(String.join(" ", refs)); } }
5,961
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export/it/DocumentObserver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.export.it; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.observer.StringObserver; import org.apache.fluo.recipes.core.export.ExportQueue; public class DocumentObserver implements StringObserver { ExportQueue<String, RefUpdates> refExportQueue; private static final Column CURRENT_COL = new Column("content", "current"); DocumentObserver(ExportQueue<String, RefUpdates> refExportQueue) { this.refExportQueue = refExportQueue; } @Override public void process(TransactionBase tx, String row, Column col) { String newContent = tx.gets(row, col).toString(); Set<String> newRefs = new HashSet<>(Arrays.asList(newContent.split(" "))); Set<String> currentRefs = new HashSet<>(Arrays.asList(tx.gets(row, CURRENT_COL, "").split(" "))); Set<String> addedRefs = new HashSet<>(newRefs); addedRefs.removeAll(currentRefs); Set<String> deletedRefs = new HashSet<>(currentRefs); deletedRefs.removeAll(newRefs); String key = row.toString().substring(2); RefUpdates val = new RefUpdates(addedRefs, deletedRefs); refExportQueue.add(tx, key, val); tx.set(row, CURRENT_COL, newContent); } }
5,962
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export/it/RefInfo.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.export.it; class RefInfo { long seq; boolean deleted; public RefInfo(long seq, boolean deleted) { this.seq = seq; this.deleted = deleted; } }
5,963
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export/it/RefUpdates.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.export.it; import java.util.Set; public class RefUpdates { private Set<String> addedRefs; private Set<String> deletedRefs; public RefUpdates() {} public RefUpdates(Set<String> addedRefs, Set<String> deletedRefs) { this.addedRefs = addedRefs; this.deletedRefs = deletedRefs; } public Set<String> getAddedRefs() { return addedRefs; } public Set<String> getDeletedRefs() { return deletedRefs; } @Override public String toString() { return "added:" + addedRefs + " deleted:" + deletedRefs; } }
5,964
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export/it/ExportBufferIT.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.export.it; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.fluo.api.client.FluoClient; import org.apache.fluo.api.client.FluoFactory; import org.apache.fluo.api.client.Transaction; import org.apache.fluo.recipes.core.export.ExportQueue; import org.junit.Assert; import org.junit.Test; public class ExportBufferIT extends ExportTestBase { @Override protected int getNumBuckets() { return 2; } @Override protected Integer getBufferSize() { return 1024; } @Test public void testSmallExportBuffer() { // try setting the export buffer size small. Make sure everything is exported. try (FluoClient fc = FluoFactory.newClient(miniFluo.getClientConfiguration())) { ExportQueue<String, RefUpdates> refExportQueue = ExportQueue.getInstance(RefExporter.QUEUE_ID, fc.getAppConfiguration()); try (Transaction tx = fc.newTransaction()) { for (int i = 0; i < 1000; i++) { refExportQueue.add(tx, nk(i), new RefUpdates(ns(i + 10, i + 20), ns(new int[0]))); } tx.commit(); } } miniFluo.waitForObservers(); Map<String, Set<String>> erefs = getExportedReferees(); Map<String, Set<String>> expected = new HashMap<>(); for (int i = 0; i < 1000; i++) { expected.computeIfAbsent(nk(i + 10), s -> new HashSet<>()).add(nk(i)); expected.computeIfAbsent(nk(i + 20), s -> new HashSet<>()).add(nk(i)); } assertEquals(expected, erefs); int prevNumExportCalls = getNumExportCalls(); Assert.assertTrue(prevNumExportCalls > 10); // with small buffer there should be lots of exports // calls try (FluoClient fc = FluoFactory.newClient(miniFluo.getClientConfiguration())) { ExportQueue<String, RefUpdates> refExportQueue = ExportQueue.getInstance(RefExporter.QUEUE_ID, fc.getAppConfiguration()); try (Transaction tx = fc.newTransaction()) { for (int i = 0; i < 1000; i++) { refExportQueue.add(tx, nk(i), new RefUpdates(ns(i + 12), ns(i + 10))); } tx.commit(); } } miniFluo.waitForObservers(); erefs = getExportedReferees(); expected = new HashMap<>(); for (int i = 0; i < 1000; i++) { expected.computeIfAbsent(nk(i + 12), s -> new HashSet<>()).add(nk(i)); expected.computeIfAbsent(nk(i + 20), s -> new HashSet<>()).add(nk(i)); } assertEquals(expected, erefs); prevNumExportCalls = getNumExportCalls() - prevNumExportCalls; Assert.assertTrue(prevNumExportCalls > 10); } public void assertEquals(Map<String, Set<String>> expected, Map<String, Set<String>> actual) { if (!expected.equals(actual)) { System.out.println("*** diff ***"); diff(expected, actual); Assert.fail(); } } }
5,965
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export/it/ExportQueueIT.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.export.it; import org.apache.fluo.api.client.FluoClient; import org.apache.fluo.api.client.FluoFactory; import org.apache.fluo.api.client.LoaderExecutor; import org.apache.fluo.api.config.FluoConfiguration; import org.junit.Assert; import org.junit.Test; public class ExportQueueIT extends ExportTestBase { @Test public void testExport() { try (FluoClient fc = FluoFactory.newClient(miniFluo.getClientConfiguration())) { try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0999", "0005", "0002")); loader.execute(new DocumentLoader("0002", "0999", "0042")); loader.execute(new DocumentLoader("0005", "0999", "0042")); loader.execute(new DocumentLoader("0042", "0999")); } miniFluo.waitForObservers(); Assert.assertEquals(ns("0002", "0005", "0042"), getExportedReferees("0999")); Assert.assertEquals(ns("0999"), getExportedReferees("0002")); Assert.assertEquals(ns("0999"), getExportedReferees("0005")); Assert.assertEquals(ns("0002", "0005"), getExportedReferees("0042")); try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0999", "0005", "0042")); } try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0999", "0005")); } miniFluo.waitForObservers(); Assert.assertEquals(ns("0002", "0005", "0042"), getExportedReferees("0999")); Assert.assertEquals(ns(new String[0]), getExportedReferees("0002")); Assert.assertEquals(ns("0999"), getExportedReferees("0005")); Assert.assertEquals(ns("0002", "0005"), getExportedReferees("0042")); try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0042", "0999", "0002", "0005")); loader.execute(new DocumentLoader("0005", "0002")); } try (LoaderExecutor loader = fc.newLoaderExecutor()) { loader.execute(new DocumentLoader("0005", "0003")); } miniFluo.waitForObservers(); Assert.assertEquals(ns("0002", "0042"), getExportedReferees("0999")); Assert.assertEquals(ns("0042"), getExportedReferees("0002")); Assert.assertEquals(ns("0005"), getExportedReferees("0003")); Assert.assertEquals(ns("0999", "0042"), getExportedReferees("0005")); Assert.assertEquals(ns("0002"), getExportedReferees("0042")); } } @Test public void exportStressTest() { FluoConfiguration config = new FluoConfiguration(miniFluo.getClientConfiguration()); config.setLoaderQueueSize(100); config.setLoaderThreads(20); try (FluoClient fc = FluoFactory.newClient(miniFluo.getClientConfiguration())) { loadRandom(fc, 1000, 500); miniFluo.waitForObservers(); diff(getFluoReferees(fc), getExportedReferees()); assertEquals(getFluoReferees(fc), getExportedReferees(), fc); loadRandom(fc, 1000, 500); miniFluo.waitForObservers(); assertEquals(getFluoReferees(fc), getExportedReferees(), fc); loadRandom(fc, 1000, 10000); miniFluo.waitForObservers(); assertEquals(getFluoReferees(fc), getExportedReferees(), fc); loadRandom(fc, 1000, 10000); miniFluo.waitForObservers(); assertEquals(getFluoReferees(fc), getExportedReferees(), fc); } } }
5,966
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/export/it/ExportTestBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.export.it; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.Set; import com.google.common.collect.Iterators; import org.apache.commons.io.FileUtils; import org.apache.fluo.api.client.FluoClient; import org.apache.fluo.api.client.FluoFactory; import org.apache.fluo.api.client.LoaderExecutor; import org.apache.fluo.api.client.Snapshot; import org.apache.fluo.api.client.scanner.CellScanner; import org.apache.fluo.api.client.scanner.ColumnScanner; import org.apache.fluo.api.client.scanner.RowScanner; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.ColumnValue; import org.apache.fluo.api.data.Span; import org.apache.fluo.api.mini.MiniFluo; import org.apache.fluo.api.observer.ObserverProvider; import org.apache.fluo.recipes.core.export.ExportQueue; import org.apache.fluo.recipes.core.export.SequencedExport; import org.apache.fluo.recipes.core.export.function.Exporter; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import static org.apache.fluo.api.observer.Observer.NotificationType.STRONG; public class ExportTestBase { private static Map<String, Map<String, RefInfo>> globalExports = new HashMap<>(); private static int exportCalls = 0; protected static Set<String> getExportedReferees(String node) { synchronized (globalExports) { Set<String> ret = new HashSet<>(); Map<String, RefInfo> referees = globalExports.get(node); if (referees == null) { return ret; } referees.forEach((k, v) -> { if (!v.deleted) ret.add(k); }); return ret; } } protected static Map<String, Set<String>> getExportedReferees() { synchronized (globalExports) { Map<String, Set<String>> ret = new HashMap<>(); for (String k : globalExports.keySet()) { Set<String> referees = getExportedReferees(k); if (referees.size() > 0) { ret.put(k, referees); } } return ret; } } protected static int getNumExportCalls() { synchronized (globalExports) { return exportCalls; } } public static class RefExporter implements Exporter<String, RefUpdates> { public static final String QUEUE_ID = "req"; private void updateExports(String key, long seq, String addedRef, boolean deleted) { Map<String, RefInfo> referees = globalExports.computeIfAbsent(addedRef, k -> new HashMap<>()); referees.compute(key, (k, v) -> (v == null || v.seq < seq) ? new RefInfo(seq, deleted) : v); } @Override public void export(Iterator<SequencedExport<String, RefUpdates>> exportIterator) { ArrayList<SequencedExport<String, RefUpdates>> exportList = new ArrayList<>(); Iterators.addAll(exportList, exportIterator); synchronized (globalExports) { exportCalls++; for (SequencedExport<String, RefUpdates> se : exportList) { for (String addedRef : se.getValue().getAddedRefs()) { updateExports(se.getKey(), se.getSequence(), addedRef, false); } for (String deletedRef : se.getValue().getDeletedRefs()) { updateExports(se.getKey(), se.getSequence(), deletedRef, true); } } } } } protected MiniFluo miniFluo; protected int getNumBuckets() { return 13; } protected Integer getBufferSize() { return null; } public static class ExportTestObserverProvider implements ObserverProvider { @Override public void provide(Registry or, Context ctx) { ExportQueue<String, RefUpdates> refExportQueue = ExportQueue.getInstance(RefExporter.QUEUE_ID, ctx.getAppConfiguration()); or.forColumn(new Column("content", "new"), STRONG) .useObserver(new DocumentObserver(refExportQueue)); refExportQueue.registerObserver(or, new RefExporter()); } } @Before public void setUpFluo() throws Exception { FileUtils.deleteQuietly(new File("target/mini")); FluoConfiguration props = new FluoConfiguration(); props.setApplicationName("eqt"); props.setWorkerThreads(20); props.setMiniDataDir("target/mini"); props.setObserverProvider(ExportTestObserverProvider.class); SimpleSerializer.setSerializer(props, GsonSerializer.class); if (getBufferSize() == null) { ExportQueue.configure(RefExporter.QUEUE_ID).keyType(String.class).valueType(RefUpdates.class) .buckets(getNumBuckets()).save(props); } else { ExportQueue.configure(RefExporter.QUEUE_ID).keyType(String.class).valueType(RefUpdates.class) .buckets(getNumBuckets()).bufferSize(getBufferSize()).save(props); } miniFluo = FluoFactory.newMiniFluo(props); globalExports.clear(); exportCalls = 0; } @After public void tearDownFluo() throws Exception { if (miniFluo != null) { miniFluo.close(); } } protected static Set<String> ns(String... sa) { return new HashSet<>(Arrays.asList(sa)); } protected static String nk(int i) { return String.format("%06d", i); } protected static Set<String> ns(int... ia) { HashSet<String> ret = new HashSet<>(); for (int i : ia) { ret.add(nk(i)); } return ret; } public void assertEquals(Map<String, Set<String>> expected, Map<String, Set<String>> actual, FluoClient fc) { if (!expected.equals(actual)) { System.out.println("*** diff ***"); diff(expected, actual); System.out.println("*** fluo dump ***"); dump(fc); System.out.println("*** map dump ***"); Assert.fail(); } } protected void loadRandom(FluoClient fc, int num, int maxDocId) { try (LoaderExecutor loader = fc.newLoaderExecutor()) { Random rand = new Random(); for (int i = 0; i < num; i++) { String docid = String.format("%05d", rand.nextInt(maxDocId)); String[] refs = new String[rand.nextInt(20) + 1]; for (int j = 0; j < refs.length; j++) { refs[j] = String.format("%05d", rand.nextInt(maxDocId)); } loader.execute(new DocumentLoader(docid, refs)); } } } protected void diff(Map<String, Set<String>> fr, Map<String, Set<String>> er) { HashSet<String> allKeys = new HashSet<>(fr.keySet()); allKeys.addAll(er.keySet()); for (String k : allKeys) { Set<String> s1 = fr.getOrDefault(k, Collections.emptySet()); Set<String> s2 = er.getOrDefault(k, Collections.emptySet()); HashSet<String> sub1 = new HashSet<>(s1); sub1.removeAll(s2); HashSet<String> sub2 = new HashSet<>(s2); sub2.removeAll(s1); if (sub1.size() > 0 || sub2.size() > 0) { System.out.println(k + " " + sub1 + " " + sub2); } } } protected Map<String, Set<String>> getFluoReferees(FluoClient fc) { Map<String, Set<String>> fluoReferees = new HashMap<>(); try (Snapshot snap = fc.newSnapshot()) { Column currCol = new Column("content", "current"); RowScanner rowScanner = snap.scanner().over(Span.prefix("d:")).fetch(currCol).byRow().build(); for (ColumnScanner columnScanner : rowScanner) { String docid = columnScanner.getsRow().substring(2); for (ColumnValue columnValue : columnScanner) { String[] refs = columnValue.getsValue().split(" "); for (String ref : refs) { if (ref.isEmpty()) continue; fluoReferees.computeIfAbsent(ref, k -> new HashSet<>()).add(docid); } } } } return fluoReferees; } public static void dump(FluoClient fc) { try (Snapshot snap = fc.newSnapshot()) { CellScanner scanner = snap.scanner().build(); scanner.forEach(rcv -> System.out.println("row:[" + rcv.getRow() + "] col:[" + rcv.getColumn() + "] val:[" + rcv.getValue() + "]")); } } }
5,967
0
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/test/java/org/apache/fluo/recipes/core/data/RowHasherTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.data; import java.util.Arrays; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.recipes.core.common.TableOptimizations; import org.junit.Assert; import org.junit.Test; public class RowHasherTest { @Test public void testBadPrefixes() { String[] badPrefixes = {"q:she6:test1", "q:she6:test1", "p:Mhe6:test1", "p;she6:test1", "p:she6;test1", "p;she6;test1", "p:+he6:test1", "p:s?e6:test1", "p:sh{6:test1", "p:sh6:"}; RowHasher rh = new RowHasher("p"); for (String badPrefix : badPrefixes) { try { rh.removeHash(Bytes.of(badPrefix)); Assert.fail(); } catch (IllegalArgumentException e) { } } } @Test public void testBasic() { RowHasher rh = new RowHasher("p"); Assert.assertTrue(rh.removeHash(rh.addHash("abc")).toString().equals("abc")); rh = new RowHasher("p2"); Assert.assertTrue(rh.removeHash(rh.addHash("abc")).toString().equals("abc")); Assert.assertTrue(rh.addHash("abc").toString().startsWith("p2:")); // test to ensure hash is stable over time Assert.assertEquals("p2:she6:test1", rh.addHash("test1").toString()); Assert.assertEquals("p2:hgt0:0123456789abcdefghijklmnopqrstuvwxyz", rh.addHash("0123456789abcdefghijklmnopqrstuvwxyz").toString()); Assert.assertEquals("p2:fluo:86ce3b094982c6a", rh.addHash("86ce3b094982c6a").toString()); } @Test public void testBalancerRegex() { FluoConfiguration fc = new FluoConfiguration(); RowHasher.configure(fc, "p", 3); TableOptimizations optimizations = new RowHasher.Optimizer().getTableOptimizations("p", fc.getAppConfiguration()); String regex = optimizations.getTabletGroupingRegex(); Assert.assertEquals("(\\Qp:\\E).*", regex); Assert.assertEquals(Arrays.asList(Bytes.of("p:c000"), Bytes.of("p:o000"), Bytes.of("p:~")), optimizations.getSplits()); } }
5,968
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/TxLog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.transaction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.RowColumn; /** * Contains list of operations (GET, SET, DELETE) performed during a {@link RecordingTransaction} * * @since 1.0.0 */ public class TxLog { private List<LogEntry> logEntries = new ArrayList<>(); public TxLog() {} /** * Adds LogEntry to TxLog */ public void add(LogEntry entry) { logEntries.add(entry); } /** * Adds LogEntry to TxLog if it passes filter */ public void filteredAdd(LogEntry entry, Predicate<LogEntry> filter) { if (filter.test(entry)) { add(entry); } } /** * Returns all LogEntry in TxLog */ public List<LogEntry> getLogEntries() { return Collections.unmodifiableList(logEntries); } /** * Returns true if TxLog is empty */ public boolean isEmpty() { return logEntries.isEmpty(); } /** * Returns a map of RowColumn changes given an operation */ public Map<RowColumn, Bytes> getOperationMap(LogEntry.Operation op) { Map<RowColumn, Bytes> opMap = new HashMap<>(); for (LogEntry entry : logEntries) { if (entry.getOp().equals(op)) { opMap.put(new RowColumn(entry.getRow(), entry.getColumn()), entry.getValue()); } } return opMap; } }
5,969
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/RecordingTransaction.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.transaction; import java.util.function.Predicate; import org.apache.fluo.api.client.Transaction; import org.apache.fluo.api.exceptions.CommitException; /** * An implementation of {@link Transaction} that logs all transactions operations (GET, SET, or * DELETE) in a {@link TxLog} that can be used for exports * * @since 1.0.0 */ public class RecordingTransaction extends RecordingTransactionBase implements Transaction { private final Transaction tx; private RecordingTransaction(Transaction tx) { super(tx); this.tx = tx; } private RecordingTransaction(Transaction tx, Predicate<LogEntry> filter) { super(tx, filter); this.tx = tx; } @Override public void commit() throws CommitException { tx.commit(); } @Override public void close() { tx.close(); } /** * Creates a RecordingTransaction by wrapping an existing Transaction */ public static RecordingTransaction wrap(Transaction tx) { return new RecordingTransaction(tx); } /** * Creates a RecordingTransaction using the provided LogEntry filter and existing Transaction */ public static RecordingTransaction wrap(Transaction tx, Predicate<LogEntry> filter) { return new RecordingTransaction(tx, filter); } }
5,970
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/LogEntry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.transaction; import java.util.Objects; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; /** * Logs an operation (i.e GET, SET, or DELETE) in a Transaction. Multiple LogEntry objects make up a * {@link TxLog}. * * @since 1.0.0 */ public class LogEntry { /** * @since 1.0.0 */ public enum Operation { GET, SET, DELETE } private Operation op; private Bytes row; private Column col; private Bytes value; private LogEntry() {} private LogEntry(Operation op, Bytes row, Column col, Bytes value) { Objects.requireNonNull(op); Objects.requireNonNull(row); Objects.requireNonNull(col); Objects.requireNonNull(value); this.op = op; this.row = row; this.col = col; this.value = value; } public Operation getOp() { return op; } public Bytes getRow() { return row; } public Column getColumn() { return col; } public Bytes getValue() { return value; } @Override public boolean equals(Object o) { if (o instanceof LogEntry) { LogEntry other = (LogEntry) o; return ((op == other.op) && row.equals(other.row) && col.equals(other.col) && value.equals(other.value)); } return false; } @Override public int hashCode() { int result = op.hashCode(); result = 31 * result + row.hashCode(); result = 31 * result + col.hashCode(); result = 31 * result + value.hashCode(); return result; } @Override public String toString() { return "LogEntry{op=" + op + ", row=" + row + ", col=" + col + ", value=" + value + "}"; } public static LogEntry newGet(CharSequence row, Column col, CharSequence value) { return newGet(Bytes.of(row), col, Bytes.of(value)); } public static LogEntry newGet(Bytes row, Column col, Bytes value) { return new LogEntry(Operation.GET, row, col, value); } public static LogEntry newSet(CharSequence row, Column col, CharSequence value) { return newSet(Bytes.of(row), col, Bytes.of(value)); } public static LogEntry newSet(Bytes row, Column col, Bytes value) { return new LogEntry(Operation.SET, row, col, value); } public static LogEntry newDelete(CharSequence row, Column col) { return newDelete(Bytes.of(row), col); } public static LogEntry newDelete(Bytes row, Column col) { return new LogEntry(Operation.DELETE, row, col, Bytes.EMPTY); } }
5,971
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/RecordingTransactionBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.transaction; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import com.google.common.collect.Iterators; import org.apache.fluo.api.client.AbstractTransactionBase; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.client.scanner.CellScanner; import org.apache.fluo.api.client.scanner.ColumnScanner; import org.apache.fluo.api.client.scanner.RowScanner; import org.apache.fluo.api.client.scanner.RowScannerBuilder; import org.apache.fluo.api.client.scanner.ScannerBuilder; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.ColumnValue; import org.apache.fluo.api.data.RowColumn; import org.apache.fluo.api.data.RowColumnValue; import org.apache.fluo.api.data.Span; import org.apache.fluo.api.exceptions.AlreadySetException; /** * An implementation of {@link TransactionBase} that logs all transactions operations (GET, SET, or * DELETE) in a {@link TxLog} that can be used for exports * * @since 1.0.0 */ public class RecordingTransactionBase extends AbstractTransactionBase implements TransactionBase { private final TransactionBase txb; private final TxLog txLog = new TxLog(); private final Predicate<LogEntry> filter; RecordingTransactionBase(TransactionBase txb, Predicate<LogEntry> filter) { this.txb = txb; this.filter = filter; } RecordingTransactionBase(TransactionBase txb) { this(txb, le -> true); } @Override public void setWeakNotification(Bytes row, Column col) { txb.setWeakNotification(row, col); } @Override public void set(Bytes row, Column col, Bytes value) throws AlreadySetException { txLog.filteredAdd(LogEntry.newSet(row, col, value), filter); txb.set(row, col, value); } @Override public void delete(Bytes row, Column col) { txLog.filteredAdd(LogEntry.newDelete(row, col), filter); txb.delete(row, col); } /** * Logs GETs for returned Row/Columns. Requests that return no data will not be logged. */ @Override public Bytes get(Bytes row, Column col) { Bytes val = txb.get(row, col); if (val != null) { txLog.filteredAdd(LogEntry.newGet(row, col, val), filter); } return val; } /** * Logs GETs for returned Row/Columns. Requests that return no data will not be logged. */ @Override public Map<Column, Bytes> get(Bytes row, Set<Column> columns) { Map<Column, Bytes> colVal = txb.get(row, columns); for (Map.Entry<Column, Bytes> entry : colVal.entrySet()) { txLog.filteredAdd(LogEntry.newGet(row, entry.getKey(), entry.getValue()), filter); } return colVal; } /** * Logs GETs for returned Row/Columns. Requests that return no data will not be logged. */ @Override public Map<Bytes, Map<Column, Bytes>> get(Collection<Bytes> rows, Set<Column> columns) { Map<Bytes, Map<Column, Bytes>> rowColVal = txb.get(rows, columns); for (Map.Entry<Bytes, Map<Column, Bytes>> rowEntry : rowColVal.entrySet()) { for (Map.Entry<Column, Bytes> colEntry : rowEntry.getValue().entrySet()) { txLog.filteredAdd( LogEntry.newGet(rowEntry.getKey(), colEntry.getKey(), colEntry.getValue()), filter); } } return rowColVal; } @Override public Map<RowColumn, Bytes> get(Collection<RowColumn> rowColumns) { Map<RowColumn, Bytes> rowColVal = txb.get(rowColumns); for (Map.Entry<RowColumn, Bytes> rce : rowColVal.entrySet()) { txLog.filteredAdd( LogEntry.newGet(rce.getKey().getRow(), rce.getKey().getColumn(), rce.getValue()), filter); } return rowColVal; } private class RtxIterator implements Iterator<RowColumnValue> { private Iterator<RowColumnValue> iter; public RtxIterator(Iterator<RowColumnValue> iterator) { this.iter = iterator; } @Override public boolean hasNext() { return iter.hasNext(); } @Override public RowColumnValue next() { RowColumnValue rcv = iter.next(); txLog.filteredAdd(LogEntry.newGet(rcv.getRow(), rcv.getColumn(), rcv.getValue()), filter); return rcv; } } private class RtxCellSanner implements CellScanner { private CellScanner scanner; public RtxCellSanner(CellScanner scanner) { this.scanner = scanner; } @Override public Iterator<RowColumnValue> iterator() { return new RtxIterator(scanner.iterator()); } } private class RtxCVIterator implements Iterator<ColumnValue> { private Iterator<ColumnValue> iter; private Bytes row; public RtxCVIterator(Bytes row, Iterator<ColumnValue> iterator) { this.row = row; this.iter = iterator; } @Override public boolean hasNext() { return iter.hasNext(); } @Override public ColumnValue next() { ColumnValue cv = iter.next(); txLog.filteredAdd(LogEntry.newGet(row, cv.getColumn(), cv.getValue()), filter); return cv; } } private class RtxColumnScanner implements ColumnScanner { private ColumnScanner cs; public RtxColumnScanner(ColumnScanner cs) { this.cs = cs; } @Override public Iterator<ColumnValue> iterator() { return new RtxCVIterator(cs.getRow(), cs.iterator()); } @Override public Bytes getRow() { return cs.getRow(); } @Override public String getsRow() { return cs.getsRow(); } } private class RtxRowScanner implements RowScanner { private RowScanner scanner; public RtxRowScanner(RowScanner scanner) { this.scanner = scanner; } @Override public Iterator<ColumnScanner> iterator() { return Iterators.transform(scanner.iterator(), RtxColumnScanner::new); } } private class RtxRowScannerBuilder implements RowScannerBuilder { private RowScannerBuilder rsb; public RtxRowScannerBuilder(RowScannerBuilder rsb) { this.rsb = rsb; } @Override public RowScanner build() { return new RtxRowScanner(rsb.build()); } } private class RtxScannerBuilder implements ScannerBuilder { private ScannerBuilder sb; public RtxScannerBuilder(ScannerBuilder sb) { this.sb = sb; } @Override public ScannerBuilder over(Span span) { sb = sb.over(span); return this; } @Override public ScannerBuilder fetch(Column... columns) { sb = sb.fetch(columns); return this; } @Override public ScannerBuilder fetch(Collection<Column> columns) { sb = sb.fetch(columns); return this; } @Override public CellScanner build() { return new RtxCellSanner(sb.build()); } @Override public RowScannerBuilder byRow() { return new RtxRowScannerBuilder(sb.byRow()); } } /** * Logs GETs for Row/Columns returned by iterators. Requests that return no data will not be * logged. */ @Override public ScannerBuilder scanner() { return new RtxScannerBuilder(txb.scanner()); } @Override public long getStartTimestamp() { return txb.getStartTimestamp(); } public TxLog getTxLog() { return txLog; } /** * Creates a RecordingTransactionBase by wrapping an existing TransactionBase */ public static RecordingTransactionBase wrap(TransactionBase txb) { return new RecordingTransactionBase(txb); } /** * Creates a RecordingTransactionBase using the provided LogEntry filter function and existing * TransactionBase */ public static RecordingTransactionBase wrap(TransactionBase txb, Predicate<LogEntry> filter) { return new RecordingTransactionBase(txb, filter); } }
5,972
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/types/TypedSnapshotBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.google.common.collect.Maps; import org.apache.commons.collections.map.DefaultedMap; import org.apache.fluo.api.client.AbstractSnapshotBase; import org.apache.fluo.api.client.SnapshotBase; import org.apache.fluo.api.client.scanner.ScannerBuilder; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.RowColumn; import org.apache.fluo.recipes.core.types.TypeLayer.Data; import org.apache.fluo.recipes.core.types.TypeLayer.FamilyMethods; import org.apache.fluo.recipes.core.types.TypeLayer.QualifierMethods; import org.apache.fluo.recipes.core.types.TypeLayer.RowMethods; // TODO need to refactor column to use Encoder /** * A {@link SnapshotBase} that uses a {@link TypeLayer} * * @since 1.0.0 */ public class TypedSnapshotBase extends AbstractSnapshotBase implements SnapshotBase { private SnapshotBase snapshot; private Encoder encoder; private TypeLayer tl; /** * @since 1.0.0 */ public class VisibilityMethods extends Value { VisibilityMethods(Data data) { super(data); } public Value vis(Bytes cv) { data.vis = cv; return new Value(data); } public Value vis(byte[] cv) { data.vis = Bytes.of(cv); return new Value(data); } public Value vis(ByteBuffer bb) { data.vis = Bytes.of(bb); return new Value(data); } public Value vis(String cv) { data.vis = Bytes.of(cv); return new Value(data); } } /** * @since 1.0.0 */ public class Value { private Bytes bytes; private boolean gotBytes = false; Data data; public Bytes getBytes() { if (!gotBytes) { try { bytes = snapshot.get(data.row, data.getCol()); gotBytes = true; } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } } return bytes; } private Value(Bytes bytes) { this.bytes = bytes; this.gotBytes = true; } private Value(Data data) { this.data = data; this.gotBytes = false; } public Integer toInteger() { if (getBytes() == null) { return null; } return encoder.decodeInteger(getBytes()); } public int toInteger(int defaultValue) { if (getBytes() == null) { return defaultValue; } return encoder.decodeInteger(getBytes()); } public Long toLong() { if (getBytes() == null) { return null; } return encoder.decodeLong(getBytes()); } public long toLong(long defaultValue) { if (getBytes() == null) { return defaultValue; } return encoder.decodeLong(getBytes()); } @Override public String toString() { if (getBytes() == null) { return null; } return encoder.decodeString(getBytes()); } public String toString(String defaultValue) { if (getBytes() == null) { return defaultValue; } return encoder.decodeString(getBytes()); } public Float toFloat() { if (getBytes() == null) { return null; } return encoder.decodeFloat(getBytes()); } public float toFloat(float defaultValue) { if (getBytes() == null) { return defaultValue; } return encoder.decodeFloat(getBytes()); } public Double toDouble() { if (getBytes() == null) { return null; } return encoder.decodeDouble(getBytes()); } public double toDouble(double defaultValue) { if (getBytes() == null) { return defaultValue; } return encoder.decodeDouble(getBytes()); } public Boolean toBoolean() { if (getBytes() == null) { return null; } return encoder.decodeBoolean(getBytes()); } public boolean toBoolean(boolean defaultValue) { if (getBytes() == null) { return defaultValue; } return encoder.decodeBoolean(getBytes()); } public byte[] toBytes() { if (getBytes() == null) { return null; } return getBytes().toArray(); } public byte[] toBytes(byte[] defaultValue) { if (getBytes() == null) { return defaultValue; } return getBytes().toArray(); } public ByteBuffer toByteBuffer() { if (getBytes() == null) { return null; } return ByteBuffer.wrap(getBytes().toArray()); } public ByteBuffer toByteBuffer(ByteBuffer defaultValue) { if (getBytes() == null) { return defaultValue; } return toByteBuffer(); } @Override public int hashCode() { if (getBytes() == null) { return 0; } return getBytes().hashCode(); } @Override public boolean equals(Object o) { if (o instanceof Value) { Value ov = (Value) o; if (getBytes() == null) { return ov.getBytes() == null; } else { return getBytes().equals(ov.getBytes()); } } return false; } } /** * @since 1.0.0 */ public class ValueQualifierBuilder extends QualifierMethods<VisibilityMethods> { ValueQualifierBuilder(Data data) { tl.super(data); } @Override VisibilityMethods create(Data data) { return new VisibilityMethods(data); } } /** * @since 1.0.0 */ public class ValueFamilyMethods extends FamilyMethods<ValueQualifierBuilder, Value> { ValueFamilyMethods(Data data) { tl.super(data); } @Override ValueQualifierBuilder create1(Data data) { return new ValueQualifierBuilder(data); } @Override Value create2(Data data) { return new Value(data); } public Map<Column, Value> columns(Set<Column> columns) { try { return wrap(snapshot.get(data.row, columns)); } catch (Exception e) { throw new RuntimeException(e); } } public Map<Column, Value> columns(Column... columns) { try { return wrap(snapshot.get(data.row, new HashSet<>(Arrays.asList(columns)))); } catch (Exception e) { throw new RuntimeException(e); } } } /** * @since 1.0.0 */ public class MapConverter { private Collection<Bytes> rows; private Set<Column> columns; public MapConverter(Collection<Bytes> rows, Set<Column> columns) { this.rows = rows; this.columns = columns; } private Map<Bytes, Map<Column, Bytes>> getInput() { try { return snapshot.get(rows, columns); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings({"rawtypes", "unchecked"}) private Map wrap2(Map m) { return Collections .unmodifiableMap(DefaultedMap.decorate(m, new DefaultedMap(new Value((Bytes) null)))); } @SuppressWarnings("unchecked") public Map<String, Map<Column, Value>> toStringMap() { Map<Bytes, Map<Column, Bytes>> in = getInput(); Map<String, Map<Column, Value>> out = new HashMap<>(); for (Entry<Bytes, Map<Column, Bytes>> rowEntry : in.entrySet()) { out.put(encoder.decodeString(rowEntry.getKey()), wrap(rowEntry.getValue())); } return wrap2(out); } @SuppressWarnings("unchecked") public Map<Long, Map<Column, Value>> toLongMap() { Map<Bytes, Map<Column, Bytes>> in = getInput(); Map<Long, Map<Column, Value>> out = new HashMap<>(); for (Entry<Bytes, Map<Column, Bytes>> rowEntry : in.entrySet()) { out.put(encoder.decodeLong(rowEntry.getKey()), wrap(rowEntry.getValue())); } return wrap2(out); } @SuppressWarnings("unchecked") public Map<Integer, Map<Column, Value>> toIntegerMap() { Map<Bytes, Map<Column, Bytes>> in = getInput(); Map<Integer, Map<Column, Value>> out = new HashMap<>(); for (Entry<Bytes, Map<Column, Bytes>> rowEntry : in.entrySet()) { out.put(encoder.decodeInteger(rowEntry.getKey()), wrap(rowEntry.getValue())); } return wrap2(out); } @SuppressWarnings("unchecked") public Map<Bytes, Map<Column, Value>> toBytesMap() { Map<Bytes, Map<Column, Bytes>> in = getInput(); Map<Bytes, Map<Column, Value>> out = new HashMap<>(); for (Entry<Bytes, Map<Column, Bytes>> rowEntry : in.entrySet()) { out.put(rowEntry.getKey(), wrap(rowEntry.getValue())); } return wrap2(out); } } /** * @since 1.0.0 */ public class ColumnsMethods { private Collection<Bytes> rows; public ColumnsMethods(Collection<Bytes> rows) { this.rows = rows; } public MapConverter columns(Set<Column> columns) { return new MapConverter(rows, columns); } public MapConverter columns(Column... columns) { return columns(new HashSet<>(Arrays.asList(columns))); } } /** * @since 1.0.0 */ public class ValueRowMethods extends RowMethods<ValueFamilyMethods> { ValueRowMethods() { tl.super(); } @Override ValueFamilyMethods create(Data data) { return new ValueFamilyMethods(data); } public ColumnsMethods rows(Collection<Bytes> rows) { return new ColumnsMethods(rows); } public ColumnsMethods rows(Bytes... rows) { return new ColumnsMethods(Arrays.asList(rows)); } public ColumnsMethods rowsString(String... rows) { return rowsString(Arrays.asList(rows)); } public ColumnsMethods rowsString(Collection<String> rows) { ArrayList<Bytes> conv = new ArrayList<>(); for (String row : rows) { conv.add(encoder.encode(row)); } return rows(conv); } public ColumnsMethods rowsLong(Long... rows) { return rowsLong(Arrays.asList(rows)); } public ColumnsMethods rowsLong(Collection<Long> rows) { ArrayList<Bytes> conv = new ArrayList<>(); for (Long row : rows) { conv.add(encoder.encode(row)); } return rows(conv); } public ColumnsMethods rowsInteger(Integer... rows) { return rowsInteger(Arrays.asList(rows)); } public ColumnsMethods rowsInteger(Collection<Integer> rows) { ArrayList<Bytes> conv = new ArrayList<>(); for (Integer row : rows) { conv.add(encoder.encode(row)); } return rows(conv); } public ColumnsMethods rowsBytes(byte[]... rows) { return rowsBytes(Arrays.asList(rows)); } public ColumnsMethods rowsBytes(Collection<byte[]> rows) { ArrayList<Bytes> conv = new ArrayList<>(); for (byte[] row : rows) { conv.add(Bytes.of(row)); } return rows(conv); } public ColumnsMethods rowsByteBuffers(ByteBuffer... rows) { return rowsByteBuffers(Arrays.asList(rows)); } public ColumnsMethods rowsByteBuffers(Collection<ByteBuffer> rows) { ArrayList<Bytes> conv = new ArrayList<>(); for (ByteBuffer row : rows) { conv.add(Bytes.of(row)); } return rows(conv); } } TypedSnapshotBase(SnapshotBase snapshot, Encoder encoder, TypeLayer tl) { this.snapshot = snapshot; this.encoder = encoder; this.tl = tl; } @Override public Bytes get(Bytes row, Column column) { return snapshot.get(row, column); } @Override public Map<Column, Bytes> get(Bytes row, Set<Column> columns) { return snapshot.get(row, columns); } @Override public Map<RowColumn, Bytes> get(Collection<RowColumn> rowColumns) { return snapshot.get(rowColumns); } @Override public Map<Bytes, Map<Column, Bytes>> get(Collection<Bytes> rows, Set<Column> columns) { return snapshot.get(rows, columns); } public ValueRowMethods get() { return new ValueRowMethods(); } @Override public ScannerBuilder scanner() { return snapshot.scanner(); } @SuppressWarnings({"unchecked"}) private Map<Column, Value> wrap(Map<Column, Bytes> map) { Map<Column, Value> ret = Maps.transformValues(map, Value::new); return Collections.unmodifiableMap(DefaultedMap.decorate(ret, new Value((Bytes) null))); } @Override public long getStartTimestamp() { return snapshot.getStartTimestamp(); } @Override public String gets(CharSequence row, Column column) { return snapshot.gets(row, column); } @Override public Map<Column, String> gets(CharSequence row, Set<Column> columns) { return snapshot.gets(row, columns); } @Override public Map<String, Map<Column, String>> gets(Collection<? extends CharSequence> rows, Set<Column> columns) { return snapshot.gets(rows, columns); } @Override public Map<RowColumn, String> gets(Collection<RowColumn> rowColumns) { return snapshot.gets(rowColumns); } }
5,973
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/types/TypedLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import org.apache.fluo.api.client.Loader; import org.apache.fluo.api.client.TransactionBase; /** * A {@link Loader} that uses a {@link TypeLayer} * * @since 1.0.0 */ public abstract class TypedLoader implements Loader { private final TypeLayer tl; public TypedLoader() { tl = new TypeLayer(new StringEncoder()); } public TypedLoader(TypeLayer tl) { this.tl = tl; } @Override public void load(TransactionBase tx, Context context) throws Exception { load(tl.wrap(tx), context); } public abstract void load(TypedTransactionBase tx, Context context) throws Exception; }
5,974
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/types/TypedSnapshot.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import org.apache.fluo.api.client.Snapshot; /** * A {@link Snapshot} that uses a {@link TypeLayer} * * @since 1.0.0 */ public class TypedSnapshot extends TypedSnapshotBase implements Snapshot { private final Snapshot closeSnapshot; TypedSnapshot(Snapshot snapshot, Encoder encoder, TypeLayer tl) { super(snapshot, encoder, tl); closeSnapshot = snapshot; } @Override public void close() { closeSnapshot.close(); } }
5,975
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/types/TypedObserver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.observer.Observer; /** * An {@link Observer} that uses a {@link TypeLayer} * * @since 1.0.0 */ public abstract class TypedObserver implements Observer { private final TypeLayer tl; public TypedObserver() { tl = new TypeLayer(new StringEncoder()); } public TypedObserver(TypeLayer tl) { this.tl = tl; } @Override public void process(TransactionBase tx, Bytes row, Column col) { process(tl.wrap(tx), row, col); } public abstract void process(TypedTransactionBase tx, Bytes row, Column col); }
5,976
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/types/TypedTransaction.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import com.google.common.annotations.VisibleForTesting; import org.apache.fluo.api.client.Transaction; import org.apache.fluo.api.exceptions.CommitException; /** * A {@link Transaction} that uses a {@link TypeLayer} * * @since 1.0.0 */ public class TypedTransaction extends TypedTransactionBase implements Transaction { private final Transaction closeTx; @VisibleForTesting protected TypedTransaction(Transaction tx, Encoder encoder, TypeLayer tl) { super(tx, encoder, tl); closeTx = tx; } @Override public void commit() throws CommitException { closeTx.commit(); } @Override public void close() { closeTx.close(); } }
5,977
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/types/TypeLayer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import java.nio.ByteBuffer; import org.apache.fluo.api.client.Snapshot; import org.apache.fluo.api.client.Transaction; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; /** * A simple convenience layer for Fluo. This layer attempts to make the following common operations * easier. * * <UL> * <LI>Working with different types. * <LI>Supplying default values * <LI>Dealing with null return types. * <LI>Working with row/column and column maps * </UL> * * <p> * This layer was intentionally loosely coupled with the basic API. This allows other convenience * layers for Fluo to build directly on the basic API w/o having to consider the particulars of this * layer. Also its expected that integration with other languages may only use the basic API. * </p> * * <h3>Using</h3> * * <p> * A TypeLayer is created with a certain encoder that is used for converting from bytes to * primitives and visa versa. In order to ensure that all of your code uses the same encoder, its * probably best to centralize the choice of an encoder within your project. There are many ways do * to this, below is an example of one way to centralize and use. * </p> * * <pre> * <code> * * public class MyTypeLayer extends TypeLayer { * public MyTypeLayer() { * super(new MyEncoder()); * } * } * * public class MyObserver extends TypedObserver { * MyObserver(){ * super(new MyTypeLayer()); * } * * public abstract void process(TypedTransaction tx, Bytes row, Column col){ * //do something w/ typed transaction * } * } * * public class MyUtil { * //A little util to print out some stuff * public void printStuff(Snapshot snap, byte[] row){ * TypedSnapshot tsnap = new MytTypeLayer().wrap(snap); * * System.out.println(tsnap.get().row(row).fam("b90000").qual(137).toString("NP")); * } * } * </code> * </pre> * * <h3>Working with different types</h3> * * <p> * The following example code shows using the basic fluo API with different types. * </p> * * <pre> * <code> * * void process(Transaction tx, byte[] row, byte[] cf, int cq, long val){ * tx.set(Bytes.of(row), new Column(Bytes.of(cf), Bytes.of(Integer.toString(cq))), * Bytes.of(Long.toString(val)); * } * </code> * </pre> * * <p> * Alternatively, the same thing can be written using a {@link TypedTransactionBase} in the * following way. Because row(), fam(), qual(), and set() each take many different types, this * enables many different permutations that would not be achievable with overloading. * </p> * * <pre> * <code> * * void process(TypedTransaction tx, byte[] r, byte[] cf, int cq, long v){ * tx.mutate().row(r).fam(cf).qual(cq).set(v); * } * </code> * </pre> * * <h3>Default values</h3> * * <p> * The following example code shows using the basic fluo API to read a value and default to zero if * it does not exist. * </p> * * <pre> * <code> * * void add(Transaction tx, byte[] row, Column col, long amount){ * * long balance = 0; * Bytes bval = tx.get(Bytes.of(row), col); * if(bval != null) * balance = Long.parseLong(bval.toString()); * * balance += amount; * * tx.set(Bytes.of(row), col, Bytes.of(Long.toString(amount))); * * } * </code> * </pre> * * <p> * Alternatively, the same thing can be written using a {@link TypedTransactionBase} in the * following way. This code avoids the null check by supplying a default value of zero. * </p> * * <pre> * <code> * * void add(TypedTransaction tx, byte[] r, Column c, long amount){ * long balance = tx.get().row(r).col(c).toLong(0); * balance += amount; * tx.mutate().row(r).col(c).set(balance); * } * </code> * </pre> * * <p> * For this particular case, shorter code can be written by using the increment method. * </p> * * <pre> * <code> * * void add(TypedTransaction tx, byte[] r, Column c, long amount){ * tx.mutate().row(r).col(c).increment(amount); * } * </code> * </pre> * * <h3>Null return types</h3> * * <p> * When using the basic API, you must ensure the return type is not null before converting a string * or long. * </p> * * <pre> * <code> * * void process(Transaction tx, byte[] row, Column col, long amount) { * Bytes val = tx.get(Bytes.of(row), col); * if(val == null) * return; * long balance = Long.parseLong(val.toString()); * } * </code> * </pre> * * <p> * With {@link TypedTransactionBase} if no default value is supplied, then the null is passed * through. * </p> * * <pre> * <code> * * void process(TypedTransaction tx, byte[] r, Column c, long amount){ * Long balance = tx.get().row(r).col(c).toLong(); * if(balance == null) * return; * } * </code> * </pre> * * <h3>Defaulted maps</h3> * * <p> * The operations that return maps, return defaulted maps which make it easy to specify defaults and * avoid null. * </p> * * <pre> * {@code * // pretend this method has curly braces. javadoc has issues with less than. * * void process(TypedTransaction tx, byte[] r, Column c1, Column c2, Column c3, long amount) * * Map<Column, Value> columns = tx.get().row(r).columns(c1,c2,c3); * * // If c1 does not exist in map, a Value that wraps null will be returned. * // When c1 does not exist val1 will be set to null and no NPE will be thrown. * String val1 = columns.get(c1).toString(); * * // If c2 does not exist in map, then val2 will be set to empty string. * String val2 = columns.get(c2).toString(""); * * // If c3 does not exist in map, then val9 will be set to 9. * Long val3 = columns.get(c3).toLong(9); * } * </pre> * * <p> * This also applies to getting sets of rows. * </p> * * <pre> * {@code * // pretend this method has curly braces. javadoc has issues with less than. * * void process(TypedTransaction tx, List<String> rows, Column c1, Column c2, Column c3, * long amount) * * Map<String,Map<Column,Value>> rowCols = * tx.get().rowsString(rows).columns(c1,c2,c3).toStringMap(); * * // this will set val1 to null if row does not exist in map and/or column does not * // exist in child map * String val1 = rowCols.get("row1").get(c1).toString(); * } * </pre> * * @since 1.0.0 */ public class TypeLayer { private Encoder encoder; static class Data { Bytes row; Bytes family; Bytes qual; Bytes vis; Column getCol() { if (qual == null) { return new Column(family); } else if (vis == null) { return new Column(family, qual); } else { return new Column(family, qual, vis); } } } /** * @since 1.0.0 */ public abstract class RowMethods<R> { abstract R create(Data data); public R row(String row) { return row(encoder.encode(row)); } public R row(int row) { return row(encoder.encode(row)); } public R row(long row) { return row(encoder.encode(row)); } public R row(byte[] row) { return row(Bytes.of(row)); } public R row(ByteBuffer row) { return row(Bytes.of(row)); } public R row(Bytes row) { Data data = new Data(); data.row = row; R result = create(data); return result; } } /** * @since 1.0.0 */ public abstract class SimpleFamilyMethods<R1> { Data data; SimpleFamilyMethods(Data data) { this.data = data; } abstract R1 create1(Data data); public R1 fam(String family) { return fam(encoder.encode(family)); } public R1 fam(int family) { return fam(encoder.encode(family)); } public R1 fam(long family) { return fam(encoder.encode(family)); } public R1 fam(byte[] family) { return fam(Bytes.of(family)); } public R1 fam(ByteBuffer family) { return fam(Bytes.of(family)); } public R1 fam(Bytes family) { data.family = family; return create1(data); } } /** * @since 1.0.0 */ public abstract class FamilyMethods<R1, R2> extends SimpleFamilyMethods<R1> { FamilyMethods(Data data) { super(data); } abstract R2 create2(Data data); public R2 col(Column col) { data.family = col.getFamily(); data.qual = col.getQualifier(); data.vis = col.getVisibility(); return create2(data); } } /** * @since 1.0.0 */ public abstract class QualifierMethods<R> { private Data data; QualifierMethods(Data data) { this.data = data; } abstract R create(Data data); public R qual(String qualifier) { return qual(encoder.encode(qualifier)); } public R qual(int qualifier) { return qual(encoder.encode(qualifier)); } public R qual(long qualifier) { return qual(encoder.encode(qualifier)); } public R qual(byte[] qualifier) { return qual(Bytes.of(qualifier)); } public R qual(ByteBuffer qualifier) { return qual(Bytes.of(qualifier)); } public R qual(Bytes qualifier) { data.qual = qualifier; return create(data); } } /** * @since 1.0.0 */ public static class VisibilityMethods { private Data data; VisibilityMethods(Data data) { this.data = data; } public Column vis() { return new Column(data.family, data.qual); } public Column vis(String cv) { return vis(Bytes.of(cv)); } public Column vis(Bytes cv) { return new Column(data.family, data.qual, cv); } public Column vis(ByteBuffer cv) { return vis(Bytes.of(cv)); } public Column vis(byte[] cv) { return vis(Bytes.of(cv)); } } /** * @since 1.0.0 */ public class CQB extends QualifierMethods<VisibilityMethods> { CQB(Data data) { super(data); } @Override VisibilityMethods create(Data data) { return new VisibilityMethods(data); } } /** * @since 1.0.0 */ public class CFB extends SimpleFamilyMethods<CQB> { CFB() { super(new Data()); } @Override CQB create1(Data data) { return new CQB(data); } } public TypeLayer(Encoder encoder) { this.encoder = encoder; } /** * Initiates the chain of calls needed to build a column. * * @return a column builder */ public CFB bc() { return new CFB(); } public TypedSnapshot wrap(Snapshot snap) { return new TypedSnapshot(snap, encoder, this); } public TypedTransactionBase wrap(TransactionBase tx) { return new TypedTransactionBase(tx, encoder, this); } public TypedTransaction wrap(Transaction tx) { return new TypedTransaction(tx, encoder, this); } }
5,978
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/types/TypedTransactionBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import java.nio.ByteBuffer; import com.google.common.annotations.VisibleForTesting; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.exceptions.AlreadySetException; import org.apache.fluo.recipes.core.types.TypeLayer.Data; import org.apache.fluo.recipes.core.types.TypeLayer.FamilyMethods; import org.apache.fluo.recipes.core.types.TypeLayer.QualifierMethods; import org.apache.fluo.recipes.core.types.TypeLayer.RowMethods; /** * A {@link TransactionBase} that uses a {@link TypeLayer} * * @since 1.0.0 */ public class TypedTransactionBase extends TypedSnapshotBase implements TransactionBase { private final TransactionBase tx; private final Encoder encoder; private final TypeLayer tl; /** * @since 1.0.0 */ public class Mutator { private boolean set = false; Data data; Mutator(Data data) { this.data = data; } void checkNotSet() { if (set) { throw new IllegalStateException("Already set value"); } } public void set(Bytes bytes) throws AlreadySetException { checkNotSet(); tx.set(data.row, data.getCol(), bytes); set = true; } public void set(String s) throws AlreadySetException { set(encoder.encode(s)); } public void set(int i) throws AlreadySetException { set(encoder.encode(i)); } public void set(long l) throws AlreadySetException { set(encoder.encode(l)); } public void set(float f) throws AlreadySetException { set(encoder.encode(f)); } public void set(double d) throws AlreadySetException { set(encoder.encode(d)); } public void set(boolean b) throws AlreadySetException { set(encoder.encode(b)); } public void set(byte[] ba) throws AlreadySetException { set(Bytes.of(ba)); } public void set(ByteBuffer bb) throws AlreadySetException { set(Bytes.of(bb)); } /** * Set an empty value */ public void set() throws AlreadySetException { set(Bytes.EMPTY); } /** * Reads the current value of the row/column, adds i, sets the sum. If the row/column does not * have a current value, then it defaults to zero. * * @param i Integer increment amount * @return The current value (before incrementing). If there is no current value, returns 0. * @throws AlreadySetException if value was previously set in transaction */ public int increment(int i) throws AlreadySetException { checkNotSet(); Bytes val = tx.get(data.row, data.getCol()); int v = 0; if (val != null) { v = encoder.decodeInteger(val); } tx.set(data.row, data.getCol(), encoder.encode(v + i)); return v; } /** * Reads the current value of the row/column, adds l, sets the sum. If the row/column does not * have a current value, then it defaults to zero. * * @param l Long increment amount * @return The current value (before incrementing). If there is no current value, returns 0. * @throws AlreadySetException if value was previously set in transaction */ public long increment(long l) throws AlreadySetException { checkNotSet(); Bytes val = tx.get(data.row, data.getCol()); long v = 0; if (val != null) { v = encoder.decodeLong(val); } tx.set(data.row, data.getCol(), encoder.encode(v + l)); return v; } public void delete() throws AlreadySetException { checkNotSet(); tx.delete(data.row, data.getCol()); set = true; } public void weaklyNotify() { checkNotSet(); tx.setWeakNotification(data.row, data.getCol()); set = true; } } /** * @since 1.0.0 */ public class VisibilityMutator extends Mutator { VisibilityMutator(Data data) { super(data); } public Mutator vis(String cv) { checkNotSet(); data.vis = Bytes.of(cv); return new Mutator(data); } public Mutator vis(Bytes cv) { checkNotSet(); data.vis = cv; return new Mutator(data); } public Mutator vis(byte[] cv) { checkNotSet(); data.vis = Bytes.of(cv); return new Mutator(data); } public Mutator vis(ByteBuffer cv) { checkNotSet(); data.vis = Bytes.of(cv); return new Mutator(data); } } /** * @since 1.0.0 */ public class MutatorQualifierMethods extends QualifierMethods<VisibilityMutator> { MutatorQualifierMethods(Data data) { tl.super(data); } @Override VisibilityMutator create(Data data) { return new VisibilityMutator(data); } } /** * @since 1.0.0 */ public class MutatorFamilyMethods extends FamilyMethods<MutatorQualifierMethods, Mutator> { MutatorFamilyMethods(Data data) { tl.super(data); } @Override MutatorQualifierMethods create1(Data data) { return new MutatorQualifierMethods(data); } @Override Mutator create2(Data data) { return new Mutator(data); } } /** * @since 1.0.0 */ public class MutatorRowMethods extends RowMethods<MutatorFamilyMethods> { MutatorRowMethods() { tl.super(); } @Override MutatorFamilyMethods create(Data data) { return new MutatorFamilyMethods(data); } } @VisibleForTesting protected TypedTransactionBase(TransactionBase tx, Encoder encoder, TypeLayer tl) { super(tx, encoder, tl); this.tx = tx; this.encoder = encoder; this.tl = tl; } public MutatorRowMethods mutate() { return new MutatorRowMethods(); } @Override public void set(Bytes row, Column col, Bytes value) throws AlreadySetException { tx.set(row, col, value); } @Override public void set(CharSequence row, Column col, CharSequence value) throws AlreadySetException { tx.set(row, col, value); } @Override public void setWeakNotification(Bytes row, Column col) { tx.setWeakNotification(row, col); } @Override public void setWeakNotification(CharSequence row, Column col) { tx.setWeakNotification(row, col); } @Override public void delete(Bytes row, Column col) throws AlreadySetException { tx.delete(row, col); } @Override public void delete(CharSequence row, Column col) { tx.delete(row, col); } }
5,979
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/types/Encoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import org.apache.fluo.api.data.Bytes; /** * Transforms Java primitives to and from bytes using desired encoding * * @since 1.0.0 */ public interface Encoder { /** * Encodes an integer to {@link Bytes} */ Bytes encode(int i); /** * Encodes a long to {@link Bytes} */ Bytes encode(long l); /** * Encodes a String to {@link Bytes} */ Bytes encode(String s); /** * Encodes a float to {@link Bytes} */ Bytes encode(float f); /** * Encodes a double to {@link Bytes} */ Bytes encode(double d); /** * Encodes a boolean to {@link Bytes} */ Bytes encode(boolean b); /** * Decodes an integer from {@link Bytes} */ int decodeInteger(Bytes b); /** * Decodes a long from {@link Bytes} */ long decodeLong(Bytes b); /** * Decodes a String from {@link Bytes} */ String decodeString(Bytes b); /** * Decodes a float from {@link Bytes} */ float decodeFloat(Bytes b); /** * Decodes a double from {@link Bytes} */ double decodeDouble(Bytes b); /** * Decodes a boolean from {@link Bytes} */ boolean decodeBoolean(Bytes b); }
5,980
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/types/StringEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.types; import org.apache.fluo.api.data.Bytes; /** * Transforms Java primitives to and from bytes using a String encoding * * @since 1.0.0 */ public class StringEncoder implements Encoder { @Override public Bytes encode(int i) { return encode(Integer.toString(i)); } @Override public Bytes encode(long l) { return encode(Long.toString(l)); } @Override public Bytes encode(String s) { return Bytes.of(s); } @Override public Bytes encode(float f) { return encode(Float.toString(f)); } @Override public Bytes encode(double d) { return encode(Double.toString(d)); } @Override public Bytes encode(boolean b) { return encode(Boolean.toString(b)); } @Override public int decodeInteger(Bytes b) { return Integer.parseInt(decodeString(b)); } @Override public long decodeLong(Bytes b) { return Long.parseLong(decodeString(b)); } @Override public String decodeString(Bytes b) { return b.toString(); } @Override public float decodeFloat(Bytes b) { return Float.parseFloat(decodeString(b)); } @Override public double decodeDouble(Bytes b) { return Double.parseDouble(decodeString(b)); } @Override public boolean decodeBoolean(Bytes b) { return Boolean.parseBoolean(decodeString(b)); } }
5,981
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/Combiner.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.util.Iterator; import java.util.Optional; import java.util.stream.Stream; /** * This class was created as an alternative to {@link Combiner}. It supports easy and efficient use * of java streams when implementing combiners using lambdas. * * @since 1.1.0 */ @FunctionalInterface public interface Combiner<K, V> { /** * * @since 1.1.0 */ public static interface Input<KI, VI> extends Iterable<VI> { KI getKey(); Stream<VI> stream(); Iterator<VI> iterator(); } /** * This function is called to combine the current value of a key with updates that were queued for * the key. See the collision free map project level documentation for more information. * * @return Then new value for the key. Returning Optional.empty() will cause the key to be * deleted. */ Optional<V> combine(Input<K, V> input); }
5,982
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/InitializerImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import com.google.common.hash.Hashing; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Bytes.BytesBuilder; import org.apache.fluo.api.data.RowColumnValue; import org.apache.fluo.recipes.core.combine.CombineQueue.Initializer; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; // intentionally package private class InitializerImpl<K, V> implements Initializer<K, V> { private static final long serialVersionUID = 1L; private Bytes dataPrefix; private SimpleSerializer serializer; private int numBuckets = -1; InitializerImpl(String cqId, int numBuckets, SimpleSerializer serializer) { this.dataPrefix = Bytes.of(cqId + ":d:"); this.numBuckets = numBuckets; this.serializer = serializer; } public RowColumnValue convert(K key, V val) { byte[] k = serializer.serialize(key); int hash = Hashing.murmur3_32().hashBytes(k).asInt(); String bucketId = CombineQueueImpl.genBucketId(Math.abs(hash % numBuckets), numBuckets); BytesBuilder bb = Bytes.builder(dataPrefix.length() + bucketId.length() + 1 + k.length); Bytes row = bb.append(dataPrefix).append(bucketId).append(':').append(k).toBytes(); byte[] v = serializer.serialize(val); return new RowColumnValue(row, CombineQueueImpl.DATA_COLUMN, Bytes.of(v)); } }
5,983
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/ChangeObserver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.util.Optional; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.recipes.core.export.ExportQueue; /** * {@link CombineQueue} uses this interface to notify of changes to a keys value. It provides the * new and old value for a key. For efficiency, the {@link CombineQueue} processes batches of key * updates at once. It is strongly advised to only use the passed in transaction for writes that are * unlikely to collide. If one write collides, then it will cause the whole batch to fail. Examples * of writes that will not collide are updating an {@link ExportQueue} or another * {@link CombineQueue}. * * <p> * It was advised to only do writes because reads for each key will slow down processing a batch. If * reading data is necessary then consider doing batch reads. * * @since 1.1.0 */ @FunctionalInterface public interface ChangeObserver<K, V> { /** * @since 1.1.0 */ public static interface Change<K2, V2> { public K2 getKey(); public Optional<V2> getNewValue(); public Optional<V2> getOldValue(); } void process(TransactionBase tx, Iterable<Change<K, V>> changes); }
5,984
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/CombineQueue.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.io.Serializable; import java.util.Map; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.api.data.RowColumnValue; import org.apache.fluo.api.observer.ObserverProvider.Registry; import org.apache.fluo.recipes.core.common.TableOptimizations; import org.apache.fluo.recipes.core.common.TableOptimizations.TableOptimizationsFactory; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; /** * See the project level documentation for information about this recipe. * * @since 1.1.0 */ public interface CombineQueue<K, V> { /** * Queues updates for this combine queue. These updates will be made by an Observer executing in * another transaction. This method will not collide with other transaction queuing updates for * the same keys. * * @param tx This transaction will be used to make the updates. * @param updates The keys in the map should correspond to keys in the collision free map being * updated. The values in the map will be queued for updating. */ public void addAll(TransactionBase tx, Map<K, V> updates); /** * Used to register a Fluo Observer that processes updates to this combine queue. If this is not * called, then updates will never be processed. * */ public void registerObserver(Registry obsRegistry, Combiner<K, V> combiner, ChangeObserver<K, V> updateObserver); /** * Get a combiner queue instance. * * @param combineQueueId This should be the same id passed to {@link #configure(String)} before * initializing Fluo. * @param appConfig Application configuration obtained from * {@code FluoClient.getAppConfiguration()}, * {@code FluoConfiguration.getAppConfiguration()}, or * {@code ObserverProvider.Context.getAppConfiguration()} */ public static <K2, V2> CombineQueue<K2, V2> getInstance(String combineQueueId, SimpleConfiguration appConfig) { try { return new CombineQueueImpl<>(combineQueueId, appConfig); } catch (Exception e) { throw new RuntimeException(e); } } /** * Part of a fluent API for configuring a combine queue. * * @since 1.1.0 */ public static interface FluentArg1 { public FluentArg2 keyType(String keyType); public FluentArg2 keyType(Class<?> keyType); } /** * Part of a fluent API for configuring a combine queue. * * @since 1.1.0 */ public static interface FluentArg2 { public FluentArg3 valueType(String valType); public FluentArg3 valueType(Class<?> valType); } /** * Part of a fluent API for configuring a combine queue. * * @since 1.1.0 */ public static interface FluentArg3 { FluentOptions buckets(int numBuckets); } /** * Part of a fluent API for configuring a combine queue. * * @since 1.1.0 */ public static interface FluentOptions { /** * Sets a limit on the amount of serialized updates to read into memory. Additional memory will * be used to actually deserialize and process the updates. This limit does not account for * object overhead in java, which can be significant. * * <p> * The way memory read is calculated is by summing the length of serialized key and value byte * arrays. Once this sum exceeds the configured memory limit, no more update key values are * processed in the current transaction. When not everything is processed, the observer * processing updates will notify itself causing another transaction to continue processing * later */ public FluentOptions bufferSize(long bufferSize); /** * Sets the number of buckets per tablet to generate. This affects how many split points will be * generated when optimizing the Accumulo table. */ public FluentOptions bucketsPerTablet(int bucketsPerTablet); /** * Adds properties to the Fluo application configuration for this CombineQueue. */ public void save(FluoConfiguration fluoConfig); } /** * Call this method before initializing Fluo to configure a combine queue. * * @param combineQueueId An id that uniquely identifies a combine queue. This id is used in the * keys in the Fluo table and in the keys in the Fluo application configuration. * @return A Fluent configurator. */ public static FluentArg1 configure(String combineQueueId) { return new CqConfigurator(combineQueueId); } /** * @since 1.1.0 */ public static interface Initializer<K2, V2> extends Serializable { public RowColumnValue convert(K2 key, V2 val); } /** * A {@link CombineQueue} stores data in its own data format in the Fluo table. When initializing * a Fluo table with something like Map Reduce or Spark, data will need to be written in this * format. That's the purpose of this method, it provides a simple class that can do this * conversion. */ public static <K2, V2> Initializer<K2, V2> getInitializer(String cqId, int numBuckets, SimpleSerializer serializer) { return new InitializerImpl<>(cqId, numBuckets, serializer); } /** * @since 1.1.0 */ public static class Optimizer implements TableOptimizationsFactory { /** * Return suggested Fluo table optimizations for the specified combine queue. * * @param appConfig Must pass in the application configuration obtained from * {@code FluoClient.getAppConfiguration()} or * {@code FluoConfiguration.getAppConfiguration()} */ @Override public TableOptimizations getTableOptimizations(String cqId, SimpleConfiguration appConfig) { return CqOptimizer.getTableOptimizations(cqId, appConfig); } } }
5,985
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/CqOptimizer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Bytes.BytesBuilder; import org.apache.fluo.recipes.core.common.TableOptimizations; // This class intentionally package private. class CqOptimizer { public static TableOptimizations getTableOptimizations(String cqId, SimpleConfiguration appConfig) { int numBuckets = CqConfigurator.getNumBucket(cqId, appConfig); int bpt = CqConfigurator.getBucketsPerTablet(cqId, appConfig); BytesBuilder rowBuilder = Bytes.builder(); rowBuilder.append(cqId); List<Bytes> dataSplits = new ArrayList<>(); for (int i = bpt; i < numBuckets; i += bpt) { String bucketId = CombineQueueImpl.genBucketId(i, numBuckets); rowBuilder.setLength(cqId.length()); dataSplits.add(rowBuilder.append(":d:").append(bucketId).toBytes()); } Collections.sort(dataSplits); List<Bytes> updateSplits = new ArrayList<>(); for (int i = bpt; i < numBuckets; i += bpt) { String bucketId = CombineQueueImpl.genBucketId(i, numBuckets); rowBuilder.setLength(cqId.length()); updateSplits.add(rowBuilder.append(":u:").append(bucketId).toBytes()); } Collections.sort(updateSplits); Bytes dataRangeEnd = Bytes.of(cqId + CqConfigurator.DATA_RANGE_END); Bytes updateRangeEnd = Bytes.of(cqId + CqConfigurator.UPDATE_RANGE_END); List<Bytes> splits = new ArrayList<>(); splits.add(dataRangeEnd); splits.add(updateRangeEnd); splits.addAll(dataSplits); splits.addAll(updateSplits); TableOptimizations tableOptim = new TableOptimizations(); tableOptim.setSplits(splits); tableOptim.setTabletGroupingRegex(Pattern.quote(cqId + ":") + "[du]:"); return tableOptim; } }
5,986
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/CombineQueueImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Sets; import com.google.common.hash.Hashing; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Bytes.BytesBuilder; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.RowColumn; import org.apache.fluo.api.data.RowColumnValue; import org.apache.fluo.api.data.Span; import org.apache.fluo.api.observer.Observer.NotificationType; import org.apache.fluo.api.observer.ObserverProvider.Registry; import org.apache.fluo.recipes.core.combine.ChangeObserver.Change; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; // intentionally package private class CombineQueueImpl<K, V> implements CombineQueue<K, V> { static final Column DATA_COLUMN = new Column("data", "current"); static final Column UPDATE_COL = new Column("u", "v"); static final Column NEXT_COL = new Column("u", "next"); private Bytes updatePrefix; private Bytes dataPrefix; private Column notifyColumn; private final String cqId; private final Class<K> keyType; private final Class<V> valType; private final int numBuckets; private final long bufferSize; private SimpleSerializer serializer; @SuppressWarnings("unchecked") CombineQueueImpl(String cqId, SimpleConfiguration appConfig) throws Exception { this.cqId = cqId; this.updatePrefix = Bytes.of(cqId + ":u:"); this.dataPrefix = Bytes.of(cqId + ":d:"); this.notifyColumn = new Column("fluoRecipes", "cfm:" + cqId); this.keyType = (Class<K>) getClass().getClassLoader() .loadClass(CqConfigurator.getKeyType(cqId, appConfig)); this.valType = (Class<V>) getClass().getClassLoader() .loadClass(CqConfigurator.getValueType(cqId, appConfig)); this.numBuckets = CqConfigurator.getNumBucket(cqId, appConfig); this.bufferSize = CqConfigurator.getBufferSize(cqId, appConfig); this.serializer = SimpleSerializer.getInstance(appConfig); } private static byte[] encSeq(long l) { byte[] ret = new byte[8]; ret[0] = (byte) (l >>> 56); ret[1] = (byte) (l >>> 48); ret[2] = (byte) (l >>> 40); ret[3] = (byte) (l >>> 32); ret[4] = (byte) (l >>> 24); ret[5] = (byte) (l >>> 16); ret[6] = (byte) (l >>> 8); ret[7] = (byte) (l >>> 0); return ret; } static String genBucketId(int bucket, int maxBucket) { Preconditions.checkArgument(bucket >= 0); Preconditions.checkArgument(maxBucket > 0); int bits = 32 - Integer.numberOfLeadingZeros(maxBucket); int bucketLen = bits / 4 + (bits % 4 > 0 ? 1 : 0); return Strings.padStart(Integer.toHexString(bucket), bucketLen, '0'); } @Override public void addAll(TransactionBase tx, Map<K, V> updates) { Preconditions.checkState(numBuckets > 0, "Not initialized"); Set<String> buckets = new HashSet<>(); BytesBuilder rowBuilder = Bytes.builder(); rowBuilder.append(updatePrefix); int prefixLength = rowBuilder.getLength(); byte[] startTs = encSeq(tx.getStartTimestamp()); for (Entry<K, V> entry : updates.entrySet()) { byte[] k = serializer.serialize(entry.getKey()); int hash = Hashing.murmur3_32().hashBytes(k).asInt(); String bucketId = genBucketId(Math.abs(hash % numBuckets), numBuckets); // reset to the common row prefix rowBuilder.setLength(prefixLength); Bytes row = rowBuilder.append(bucketId).append(':').append(k).append(startTs).toBytes(); Bytes val = Bytes.of(serializer.serialize(entry.getValue())); // TODO set if not exists would be comforting here.... but // collisions on bucketId+key+uuid should never occur tx.set(row, UPDATE_COL, val); buckets.add(bucketId); } for (String bucketId : buckets) { rowBuilder.setLength(prefixLength); rowBuilder.append(bucketId).append(':'); Bytes row = rowBuilder.toBytes(); tx.setWeakNotification(row, notifyColumn); } } private Map<Bytes, Map<Column, Bytes>> getCurrentValues(TransactionBase tx, BytesBuilder prefix, Set<Bytes> keySet) { Set<Bytes> rows = new HashSet<>(); int prefixLen = prefix.getLength(); for (Bytes key : keySet) { prefix.setLength(prefixLen); rows.add(prefix.append(key).toBytes()); } try { return tx.get(rows, Collections.singleton(DATA_COLUMN)); } catch (IllegalArgumentException e) { System.out.println(rows.size()); throw e; } } private V deserVal(Bytes val) { return serializer.deserialize(val.toArray(), valType); } private Bytes getKeyFromUpdateRow(Bytes prefix, Bytes row) { return row.subSequence(prefix.length(), row.length() - 8); } void process(TransactionBase tx, Bytes ntfyRow, Column col, Combiner<K, V> combiner, ChangeObserver<K, V> changeObserver) throws Exception { Preconditions.checkState(ntfyRow.startsWith(updatePrefix)); Bytes nextKey = tx.get(ntfyRow, NEXT_COL); Span span; if (nextKey != null) { Bytes startRow = Bytes.builder(ntfyRow.length() + nextKey.length()).append(ntfyRow) .append(nextKey).toBytes(); Span tmpSpan = Span.prefix(ntfyRow); Span nextSpan = new Span(new RowColumn(startRow, UPDATE_COL), false, tmpSpan.getEnd(), tmpSpan.isEndInclusive()); span = nextSpan; } else { span = Span.prefix(ntfyRow); } Iterator<RowColumnValue> iter = tx.scanner().over(span).fetch(UPDATE_COL).build().iterator(); Map<Bytes, List<Bytes>> updates = new HashMap<>(); long approxMemUsed = 0; Bytes partiallyReadKey = null; boolean setNextKey = false; if (iter.hasNext()) { Bytes lastKey = null; while (iter.hasNext() && approxMemUsed < bufferSize) { RowColumnValue rcv = iter.next(); Bytes curRow = rcv.getRow(); tx.delete(curRow, UPDATE_COL); Bytes serializedKey = getKeyFromUpdateRow(ntfyRow, curRow); lastKey = serializedKey; List<Bytes> updateList = updates.get(serializedKey); if (updateList == null) { updateList = new ArrayList<>(); updates.put(serializedKey, updateList); } Bytes val = rcv.getValue(); updateList.add(val); approxMemUsed += curRow.length(); approxMemUsed += val.length(); } if (iter.hasNext()) { RowColumnValue rcv = iter.next(); Bytes curRow = rcv.getRow(); // check if more updates for last key if (getKeyFromUpdateRow(ntfyRow, curRow).equals(lastKey)) { // there are still more updates for this key partiallyReadKey = lastKey; // start next time at the current key tx.set(ntfyRow, NEXT_COL, partiallyReadKey); } else { // start next time at the next possible key Bytes nextPossible = Bytes.builder(lastKey.length() + 1).append(lastKey).append(0).toBytes(); tx.set(ntfyRow, NEXT_COL, nextPossible); } setNextKey = true; } else if (nextKey != null) { // clear nextKey tx.delete(ntfyRow, NEXT_COL); } } else if (nextKey != null) { tx.delete(ntfyRow, NEXT_COL); } if (nextKey != null || setNextKey) { // If not all data was read need to run again in the future. If scanning was started in the // middle of the bucket, its possible there is new data before nextKey that still needs to be // processed. If scanning stopped before reading the entire bucket there may be data after the // stop point. tx.setWeakNotification(ntfyRow, col); } BytesBuilder rowBuilder = Bytes.builder(); rowBuilder.append(dataPrefix); rowBuilder.append(ntfyRow.subSequence(updatePrefix.length(), ntfyRow.length())); int rowPrefixLen = rowBuilder.getLength(); Set<Bytes> keysToFetch = updates.keySet(); if (partiallyReadKey != null) { final Bytes prk = partiallyReadKey; keysToFetch = Sets.filter(keysToFetch, b -> !b.equals(prk)); } Map<Bytes, Map<Column, Bytes>> currentVals = getCurrentValues(tx, rowBuilder, keysToFetch); ArrayList<Change<K, V>> updatesToReport = new ArrayList<>(updates.size()); for (Entry<Bytes, List<Bytes>> entry : updates.entrySet()) { rowBuilder.setLength(rowPrefixLen); Bytes currentValueRow = rowBuilder.append(entry.getKey()).toBytes(); Bytes currVal = currentVals.getOrDefault(currentValueRow, Collections.emptyMap()).get(DATA_COLUMN); K kd = serializer.deserialize(entry.getKey().toArray(), keyType); if (partiallyReadKey != null && partiallyReadKey.equals(entry.getKey())) { // not all updates were read for this key, so requeue the combined updates as an update Optional<V> nv = combiner.combine(new InputImpl<>(kd, this::deserVal, entry.getValue())); if (nv.isPresent()) { addAll(tx, Collections.singletonMap(kd, nv.get())); } } else { Optional<V> nv = combiner.combine(new InputImpl<>(kd, this::deserVal, currVal, entry.getValue())); Bytes newVal = nv.isPresent() ? Bytes.of(serializer.serialize(nv.get())) : null; if (newVal != null ^ currVal != null || (currVal != null && !currVal.equals(newVal))) { if (newVal == null) { tx.delete(currentValueRow, DATA_COLUMN); } else { tx.set(currentValueRow, DATA_COLUMN, newVal); } Optional<V> cvd = Optional.ofNullable(currVal).map(this::deserVal); updatesToReport.add(new ChangeImpl<>(kd, cvd, nv)); } } } // TODO could clear these as converted to objects to avoid double memory usage updates.clear(); currentVals.clear(); if (updatesToReport.size() > 0) { changeObserver.process(tx, updatesToReport); } } @Override public void registerObserver(Registry obsRegistry, Combiner<K, V> combiner, ChangeObserver<K, V> changeObserver) { obsRegistry.forColumn(notifyColumn, NotificationType.WEAK).withId("combineq-" + cqId) .useObserver((tx, row, col) -> process(tx, row, col, combiner, changeObserver)); } }
5,987
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/ChangeImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.util.Optional; // intentionally package private class ChangeImpl<K, V> implements ChangeObserver.Change<K, V> { private final K key; private final Optional<V> oldValue; private final Optional<V> newValue; ChangeImpl(K key, Optional<V> oldValue, Optional<V> newValue) { this.key = key; this.oldValue = oldValue; this.newValue = newValue; } @Override public K getKey() { return key; } @Override public Optional<V> getNewValue() { return newValue; } @Override public Optional<V> getOldValue() { return oldValue; } }
5,988
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/CqConfigurator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.util.Objects; import com.google.common.base.Preconditions; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.recipes.core.combine.CombineQueue.FluentArg1; import org.apache.fluo.recipes.core.combine.CombineQueue.FluentArg2; import org.apache.fluo.recipes.core.combine.CombineQueue.FluentArg3; import org.apache.fluo.recipes.core.combine.CombineQueue.FluentOptions; import org.apache.fluo.recipes.core.common.RowRange; import org.apache.fluo.recipes.core.common.TableOptimizations; import org.apache.fluo.recipes.core.common.TransientRegistry; // this class intentionally package private class CqConfigurator implements FluentArg1, FluentArg2, FluentArg3, FluentOptions { static final String UPDATE_RANGE_END = ":u:~"; static final String DATA_RANGE_END = ":d:~"; int numBuckets; Integer bucketsPerTablet = null; Long bufferSize; String keyType; String valueType; String cqId; static final int DEFAULT_BUCKETS_PER_TABLET = 10; static final long DEFAULT_BUFFER_SIZE = 1 << 22; static final String PREFIX = "recipes.cfm."; CqConfigurator(String id) { Objects.requireNonNull(id); Preconditions.checkArgument(!id.contains(":"), "Combine queue id cannot contain ':'"); this.cqId = id; } @Override public FluentOptions buckets(int numBuckets) { Preconditions.checkArgument(numBuckets > 0); this.numBuckets = numBuckets; return this; } @Override public FluentArg3 valueType(String valType) { this.valueType = Objects.requireNonNull(valType); return this; } @Override public FluentArg3 valueType(Class<?> valType) { this.valueType = valType.getName(); return this; } @Override public FluentArg2 keyType(String keyType) { this.keyType = Objects.requireNonNull(keyType); return this; } @Override public FluentArg2 keyType(Class<?> keyType) { this.keyType = keyType.getName(); return this; } @Override public FluentOptions bufferSize(long bufferSize) { Preconditions.checkArgument(bufferSize > 0, "Buffer size must be positive"); this.bufferSize = bufferSize; return this; } @Override public FluentOptions bucketsPerTablet(int bucketsPerTablet) { Preconditions.checkArgument(bucketsPerTablet > 0, "bucketsPerTablet is <= 0 : " + bucketsPerTablet); this.bucketsPerTablet = bucketsPerTablet; return this; } @Override public void save(FluoConfiguration fluoConfig) { SimpleConfiguration appConfig = fluoConfig.getAppConfiguration(); appConfig.setProperty(PREFIX + cqId + ".buckets", numBuckets + ""); appConfig.setProperty(PREFIX + cqId + ".key", keyType); appConfig.setProperty(PREFIX + cqId + ".val", valueType); if (bufferSize != null) { appConfig.setProperty(PREFIX + cqId + ".bufferSize", bufferSize); } if (bucketsPerTablet != null) { appConfig.setProperty(PREFIX + cqId + ".bucketsPerTablet", bucketsPerTablet); } Bytes dataRangeEnd = Bytes.of(cqId + DATA_RANGE_END); Bytes updateRangeEnd = Bytes.of(cqId + UPDATE_RANGE_END); new TransientRegistry(fluoConfig.getAppConfiguration()).addTransientRange("cfm." + cqId, new RowRange(dataRangeEnd, updateRangeEnd)); TableOptimizations.registerOptimization(appConfig, cqId, CombineQueue.Optimizer.class); } static long getBufferSize(String cqId, SimpleConfiguration appConfig) { return appConfig.getLong(PREFIX + cqId + ".bufferSize", DEFAULT_BUFFER_SIZE); } static String getValueType(String cqId, SimpleConfiguration appConfig) { return appConfig.getString(PREFIX + cqId + ".val"); } static String getKeyType(String cqId, SimpleConfiguration appConfig) { return appConfig.getString(PREFIX + cqId + ".key"); } static int getBucketsPerTablet(String cqId, SimpleConfiguration appConfig) { return appConfig.getInt(PREFIX + cqId + ".bucketsPerTablet", DEFAULT_BUCKETS_PER_TABLET); } static int getNumBucket(String cqId, SimpleConfiguration appConfig) { return appConfig.getInt(PREFIX + cqId + ".buckets"); } }
5,989
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/InputImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.util.Collection; import java.util.Iterator; import java.util.function.Function; import java.util.stream.Stream; import com.google.common.collect.Iterators; import org.apache.fluo.api.data.Bytes; // intentionally package private class InputImpl<K, V> implements Combiner.Input<K, V> { private K key; private Collection<Bytes> valuesCollection; private Bytes currentValue; private Function<Bytes, V> valDeser; InputImpl(K k, Function<Bytes, V> valDeser, Collection<Bytes> serializedValues) { this.key = k; this.valDeser = valDeser; this.valuesCollection = serializedValues; } InputImpl(K k, Function<Bytes, V> valDeser, Bytes currentValue, Collection<Bytes> serializedValues) { this(k, valDeser, serializedValues); this.currentValue = currentValue; } @Override public K getKey() { return key; } @Override public Stream<V> stream() { Stream<Bytes> bytesStream = valuesCollection.stream(); if (currentValue != null) { bytesStream = Stream.concat(Stream.of(currentValue), bytesStream); } return bytesStream.map(valDeser); } @Override public Iterator<V> iterator() { Iterator<Bytes> bytesIter = valuesCollection.iterator(); if (currentValue != null) { bytesIter = Iterators.concat(bytesIter, Iterators.singletonIterator(currentValue)); } return Iterators.transform(bytesIter, valDeser::apply); } }
5,990
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/combine/SummingCombiner.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.combine; import java.util.Optional; /** * Sums long values and returns Optional.empty() when the sum is zero. * * @since 1.1.0 */ public class SummingCombiner<K> implements Combiner<K, Long> { @Override public Optional<Long> combine(Input<K, Long> input) { long sum = 0; for (Long l : input) { sum += l; } return sum == 0 ? Optional.empty() : Optional.of(sum); } }
5,991
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/serialization/SimpleSerializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.serialization; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; /** * @since 1.0.0 */ public interface SimpleSerializer { /** * Called immediately after construction and passed Fluo application configuration. */ void init(SimpleConfiguration appConfig); // TODO refactor to support reuse of objects and byte arrays??? <T> byte[] serialize(T obj); <T> T deserialize(byte[] serObj, Class<T> clazz); static void setSerializer(FluoConfiguration fluoConfig, Class<? extends SimpleSerializer> serializerType) { setSerializer(fluoConfig, serializerType.getName()); } static void setSerializer(FluoConfiguration fluoConfig, String serializerType) { fluoConfig.getAppConfiguration().setProperty("recipes.serializer", serializerType); } static SimpleSerializer getInstance(SimpleConfiguration appConfig) { String serType = appConfig.getString("recipes.serializer", "org.apache.fluo.recipes.kryo.KryoSimplerSerializer"); try { SimpleSerializer simplerSer = SimpleSerializer.class.getClassLoader().loadClass(serType) .asSubclass(SimpleSerializer.class).newInstance(); simplerSer.init(appConfig); return simplerSer; } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException(e); } } }
5,992
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/common/TableOptimizations.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.common; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; import org.apache.fluo.api.client.FluoClient; import org.apache.fluo.api.client.FluoFactory; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.api.data.Bytes; /** * Post initialization recommended table optimizations. * * @since 1.0.0 */ public class TableOptimizations { private List<Bytes> splits = new ArrayList<>(); private String tabletGroupingRegex = ""; public void setSplits(List<Bytes> splits) { this.splits.clear(); this.splits.addAll(splits); } /** * @return A recommended set of splits points to add to a Fluo table after initialization. */ public List<Bytes> getSplits() { return Collections.unmodifiableList(splits); } public void setTabletGroupingRegex(String tgr) { Objects.requireNonNull(tgr); this.tabletGroupingRegex = tgr; } public String getTabletGroupingRegex() { return "(" + tabletGroupingRegex + ").*"; } public void merge(TableOptimizations other) { splits.addAll(other.splits); if (tabletGroupingRegex.length() > 0 && other.tabletGroupingRegex.length() > 0) { tabletGroupingRegex += "|" + other.tabletGroupingRegex; } else { tabletGroupingRegex += other.tabletGroupingRegex; } } public static interface TableOptimizationsFactory { TableOptimizations getTableOptimizations(String key, SimpleConfiguration appConfig); } private static final String PREFIX = "recipes.optimizations."; /** * This method provides a standard way to register a table optimization for the Fluo table before * initialization. After Fluo is initialized, the optimizations can be retrieved by calling * {@link #getConfiguredOptimizations(FluoConfiguration)}. * * @param appConfig config, likely obtained from calling * {@link FluoConfiguration#getAppConfiguration()} * @param key A unique identifier for the optimization * @param clazz The optimization factory type. */ public static void registerOptimization(SimpleConfiguration appConfig, String key, Class<? extends TableOptimizationsFactory> clazz) { appConfig.setProperty(PREFIX + key, clazz.getName()); } /** * A utility method to get all registered table optimizations. Many recipes will automatically * register table optimizations when configured. */ public static TableOptimizations getConfiguredOptimizations(FluoConfiguration fluoConfig) { try (FluoClient client = FluoFactory.newClient(fluoConfig)) { SimpleConfiguration appConfig = client.getAppConfiguration(); TableOptimizations tableOptim = new TableOptimizations(); SimpleConfiguration subset = appConfig.subset(PREFIX.substring(0, PREFIX.length() - 1)); Iterator<String> keys = subset.getKeys(); while (keys.hasNext()) { String key = keys.next(); String clazz = subset.getString(key); try { TableOptimizationsFactory factory = Class.forName(clazz).asSubclass(TableOptimizationsFactory.class).newInstance(); tableOptim.merge(factory.getTableOptimizations(key, appConfig)); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException(e); } } return tableOptim; } } }
5,993
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/common/TransientRegistry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.common; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.bind.DatatypeConverter; import org.apache.fluo.api.client.FluoClient; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.api.data.Bytes; /** * This class offers a standard way to register transient ranges. The project level documentation * provides a comprehensive overview. * * @since 1.0.0 */ public class TransientRegistry { private SimpleConfiguration appConfig; private static final String PREFIX = "recipes.transientRange."; /** * @param appConfig Fluo application config. Can be obtained from * {@link FluoConfiguration#getAppConfiguration()} before initializing fluo when adding * Transient ranges. After Fluo is initialized, app config can be obtained from * {@link FluoClient#getAppConfiguration()} or * {@link org.apache.fluo.api.observer.Observer.Context#getAppConfiguration()} */ public TransientRegistry(SimpleConfiguration appConfig) { this.appConfig = appConfig; } /** * This method is expected to be called before Fluo is initialized to register transient ranges. * */ public void addTransientRange(String id, RowRange range) { String start = DatatypeConverter.printHexBinary(range.getStart().toArray()); String end = DatatypeConverter.printHexBinary(range.getEnd().toArray()); appConfig.setProperty(PREFIX + id, start + ":" + end); } /** * This method is expected to be called after Fluo is initialized to get the ranges that were * registered before initialization. */ public List<RowRange> getTransientRanges() { List<RowRange> ranges = new ArrayList<>(); Iterator<String> keys = appConfig.getKeys(PREFIX.substring(0, PREFIX.length() - 1)); while (keys.hasNext()) { String key = keys.next(); String val = appConfig.getString(key); String[] sa = val.split(":"); RowRange rowRange = new RowRange(Bytes.of(DatatypeConverter.parseHexBinary(sa[0])), Bytes.of(DatatypeConverter.parseHexBinary(sa[1]))); ranges.add(rowRange); } return ranges; } }
5,994
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/common/RowRange.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.common; import java.util.Objects; import org.apache.fluo.api.data.Bytes; /** * @since 1.0.0 */ public class RowRange { private final Bytes start; private final Bytes end; public RowRange(Bytes start, Bytes end) { Objects.requireNonNull(start); Objects.requireNonNull(end); this.start = start; this.end = end; } public Bytes getStart() { return start; } public Bytes getEnd() { return end; } @Override public int hashCode() { return start.hashCode() + 31 * end.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof RowRange) { RowRange or = (RowRange) o; return start.equals(or.start) && end.equals(or.end); } return false; } private static void encNonAscii(StringBuilder sb, Bytes bytes) { if (bytes == null) { sb.append("null"); } else { for (int i = 0; i < bytes.length(); i++) { byte b = bytes.byteAt(i); if (b >= 32 && b <= 126 && b != '\\') { sb.append((char) b); } else { sb.append(String.format("\\x%02x", b & 0xff)); } } } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); encNonAscii(sb, start); sb.append(", "); encNonAscii(sb, end); sb.append("]"); return sb.toString(); } }
5,995
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/map/Combiner.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map; import java.util.Iterator; import java.util.Optional; import org.apache.fluo.recipes.core.combine.CombineQueue; /** * @since 1.0.0 * @deprecated since 1.1.0 use {@link org.apache.fluo.recipes.core.combine.Combiner} and * {@link CombineQueue} */ @Deprecated public interface Combiner<K, V> { /** * This function is called to combine the current value of a key with updates that were queued for * the key. See the collision free map project level documentation for more information. * * @return Then new value for the key. Returning Optional.absent() will cause the key to be * deleted. */ Optional<V> combine(K key, Iterator<V> updates); }
5,996
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/map/Update.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map; import java.util.Iterator; import java.util.Optional; import com.google.common.collect.Iterators; import org.apache.fluo.recipes.core.combine.ChangeObserver.Change; /** * @since 1.0.0 * @deprecated since 1.1.0 */ @Deprecated public class Update<K, V> { private final K key; private final Optional<V> oldValue; private final Optional<V> newValue; Update(K key, Optional<V> oldValue, Optional<V> newValue) { this.key = key; this.oldValue = oldValue; this.newValue = newValue; } public K getKey() { return key; } public Optional<V> getNewValue() { return newValue; } public Optional<V> getOldValue() { return oldValue; } static <K2, V2> Iterator<Update<K2, V2>> transform(Iterable<Change<K2, V2>> changes) { return Iterators.transform(changes.iterator(), change -> new Update<K2, V2>(change.getKey(), change.getOldValue(), change.getNewValue())); } }
5,997
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/map/CollisionFreeMap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.Map; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Iterators; import com.google.common.hash.Hashing; import org.apache.fluo.api.client.SnapshotBase; import org.apache.fluo.api.client.TransactionBase; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.api.config.SimpleConfiguration; import org.apache.fluo.api.data.Bytes; import org.apache.fluo.api.data.Bytes.BytesBuilder; import org.apache.fluo.api.data.Column; import org.apache.fluo.api.data.RowColumnValue; import org.apache.fluo.api.data.Span; import org.apache.fluo.api.observer.Observer; import org.apache.fluo.api.observer.Observer.NotificationType; import org.apache.fluo.api.observer.ObserverProvider; import org.apache.fluo.api.observer.StringObserver; import org.apache.fluo.recipes.core.combine.CombineQueue; import org.apache.fluo.recipes.core.common.TableOptimizations; import org.apache.fluo.recipes.core.common.TableOptimizations.TableOptimizationsFactory; import org.apache.fluo.recipes.core.serialization.SimpleSerializer; /** * See the project level documentation for information about this recipe. * * @since 1.0.0 * @deprecated since 1.1.0 use {@link CombineQueue} */ @Deprecated public class CollisionFreeMap<K, V> { private Bytes updatePrefix; private Bytes dataPrefix; private Class<V> valType; private SimpleSerializer serializer; private Combiner<K, V> combiner; UpdateObserver<K, V> updateObserver; static final Column UPDATE_COL = new Column("u", "v"); static final Column NEXT_COL = new Column("u", "next"); private int numBuckets = -1; private CombineQueue<K, V> combineQ; private Observer combineQueueObserver; private static class CfmRegistry implements ObserverProvider.Registry { Observer observer; private class Registry implements ObserverProvider.Registry.ObserverArgument, ObserverProvider.Registry.IdentityOption { @Override public ObserverArgument withId(String alias) { return this; } @Override public void useObserver(Observer obs) { observer = obs; } @Override public void useStrObserver(StringObserver obs) { observer = obs; } } @Override public IdentityOption forColumn(Column observedColumn, NotificationType ntfyType) { return new Registry(); } } @SuppressWarnings("unchecked") CollisionFreeMap(SimpleConfiguration appConfig, Options opts, SimpleSerializer serializer) throws Exception { this.updatePrefix = Bytes.of(opts.mapId + ":u:"); this.dataPrefix = Bytes.of(opts.mapId + ":d:"); this.numBuckets = opts.numBuckets; this.valType = (Class<V>) getClass().getClassLoader().loadClass(opts.valueType); this.combiner = (Combiner<K, V>) getClass().getClassLoader().loadClass(opts.combinerType).newInstance(); this.serializer = serializer; if (opts.updateObserverType != null) { this.updateObserver = getClass().getClassLoader().loadClass(opts.updateObserverType) .asSubclass(UpdateObserver.class).newInstance(); } else { this.updateObserver = new NullUpdateObserver<>(); } combineQ = CombineQueue.getInstance(opts.mapId, appConfig); // When this class was deprecated, most of its code was copied to CombineQueue. The following // code is a round about way of using that copied code, with having to make anything in // CombineQueue public. CfmRegistry obsRegistry = new CfmRegistry(); combineQ.registerObserver(obsRegistry, i -> this.combiner.combine(i.getKey(), i.iterator()), (tx, changes) -> this.updateObserver.updatingValues(tx, Update.transform(changes))); combineQueueObserver = obsRegistry.observer; } private V deserVal(Bytes val) { return serializer.deserialize(val.toArray(), valType); } void process(TransactionBase tx, Bytes ntfyRow, Column col) throws Exception { combineQueueObserver.process(tx, ntfyRow, col); } private static final Column DATA_COLUMN = new Column("data", "current"); private Iterator<V> concat(Iterator<V> updates, Bytes currentVal) { if (currentVal == null) { return updates; } return Iterators.concat(updates, Iterators.singletonIterator(deserVal(currentVal))); } /** * This method will retrieve the current value for key and any outstanding updates and combine * them using the configured {@link Combiner}. The result from the combiner is returned. */ public V get(SnapshotBase tx, K key) { byte[] k = serializer.serialize(key); int hash = Hashing.murmur3_32().hashBytes(k).asInt(); String bucketId = genBucketId(Math.abs(hash % numBuckets), numBuckets); BytesBuilder rowBuilder = Bytes.builder(); rowBuilder.append(updatePrefix).append(bucketId).append(':').append(k); Iterator<RowColumnValue> iter = tx.scanner().over(Span.prefix(rowBuilder.toBytes())).build().iterator(); Iterator<V> ui; if (iter.hasNext()) { ui = Iterators.transform(iter, rcv -> deserVal(rcv.getValue())); } else { ui = Collections.<V>emptyList().iterator(); } rowBuilder.setLength(0); rowBuilder.append(dataPrefix).append(bucketId).append(':').append(k); Bytes dataRow = rowBuilder.toBytes(); Bytes cv = tx.get(dataRow, DATA_COLUMN); if (!ui.hasNext()) { if (cv == null) { return null; } else { return deserVal(cv); } } return combiner.combine(key, concat(ui, cv)).orElse(null); } /** * Queues updates for a collision free map. These updates will be made by an Observer executing * another transaction. This method will not collide with other transaction queuing updates for * the same keys. * * @param tx This transaction will be used to make the updates. * @param updates The keys in the map should correspond to keys in the collision free map being * updated. The values in the map will be queued for updating. */ public void update(TransactionBase tx, Map<K, V> updates) { combineQ.addAll(tx, updates); } static String genBucketId(int bucket, int maxBucket) { Preconditions.checkArgument(bucket >= 0); Preconditions.checkArgument(maxBucket > 0); int bits = 32 - Integer.numberOfLeadingZeros(maxBucket); int bucketLen = bits / 4 + (bits % 4 > 0 ? 1 : 0); return Strings.padStart(Integer.toHexString(bucket), bucketLen, '0'); } public static <K2, V2> CollisionFreeMap<K2, V2> getInstance(String mapId, SimpleConfiguration appConf) { Options opts = new Options(mapId, appConf); try { return new CollisionFreeMap<>(appConf, opts, SimpleSerializer.getInstance(appConf)); } catch (Exception e) { // TODO throw new RuntimeException(e); } } /** * A {@link CollisionFreeMap} stores data in its own data format in the Fluo table. When * initializing a Fluo table with something like Map Reduce or Spark, data will need to be written * in this format. That's the purpose of this method, it provide a simple class that can do this * conversion. */ public static <K2, V2> Initializer<K2, V2> getInitializer(String mapId, int numBuckets, SimpleSerializer serializer) { return new Initializer<>(mapId, numBuckets, serializer); } /** * @see CollisionFreeMap#getInitializer(String, int, SimpleSerializer) * * @since 1.0.0 * @deprecated since 1.1.0 */ @Deprecated public static class Initializer<K2, V2> implements Serializable { private static final long serialVersionUID = 1L; private org.apache.fluo.recipes.core.combine.CombineQueue.Initializer<K2, V2> initializer; private Initializer(String mapId, int numBuckets, SimpleSerializer serializer) { this.initializer = CombineQueue.getInitializer(mapId, numBuckets, serializer); } public RowColumnValue convert(K2 key, V2 val) { return initializer.convert(key, val); } } /** * @since 1.0.0 * @deprecated since 1.1.0 */ @Deprecated public static class Options { static final long DEFAULT_BUFFER_SIZE = 1 << 22; static final int DEFAULT_BUCKETS_PER_TABLET = 10; int numBuckets; Integer bucketsPerTablet = null; Long bufferSize; String keyType; String valueType; String combinerType; String updateObserverType; String mapId; private static final String PREFIX = "recipes.cfm."; Options(String mapId, SimpleConfiguration appConfig) { this.mapId = mapId; this.numBuckets = appConfig.getInt(PREFIX + mapId + ".buckets"); this.combinerType = appConfig.getString(PREFIX + mapId + ".combiner"); this.keyType = appConfig.getString(PREFIX + mapId + ".key"); this.valueType = appConfig.getString(PREFIX + mapId + ".val"); this.updateObserverType = appConfig.getString(PREFIX + mapId + ".updateObserver", null); this.bufferSize = appConfig.getLong(PREFIX + mapId + ".bufferSize", DEFAULT_BUFFER_SIZE); this.bucketsPerTablet = appConfig.getInt(PREFIX + mapId + ".bucketsPerTablet", DEFAULT_BUCKETS_PER_TABLET); } public Options(String mapId, String combinerType, String keyType, String valType, int buckets) { Preconditions.checkArgument(buckets > 0); Preconditions.checkArgument(!mapId.contains(":"), "Map id cannot contain ':'"); this.mapId = mapId; this.numBuckets = buckets; this.combinerType = combinerType; this.updateObserverType = null; this.keyType = keyType; this.valueType = valType; } public Options(String mapId, String combinerType, String updateObserverType, String keyType, String valueType, int buckets) { Preconditions.checkArgument(buckets > 0); Preconditions.checkArgument(!mapId.contains(":"), "Map id cannot contain ':'"); this.mapId = mapId; this.numBuckets = buckets; this.combinerType = combinerType; this.updateObserverType = updateObserverType; this.keyType = keyType; this.valueType = valueType; } /** * Sets a limit on the amount of serialized updates to read into memory. Additional memory will * be used to actually deserialize and process the updates. This limit does not account for * object overhead in java, which can be significant. * * <p> * The way memory read is calculated is by summing the length of serialized key and value byte * arrays. Once this sum exceeds the configured memory limit, no more update key values are * processed in the current transaction. When not everything is processed, the observer * processing updates will notify itself causing another transaction to continue processing * later */ public Options setBufferSize(long bufferSize) { Preconditions.checkArgument(bufferSize > 0, "Buffer size must be positive"); this.bufferSize = bufferSize; return this; } long getBufferSize() { if (bufferSize == null) { return DEFAULT_BUFFER_SIZE; } return bufferSize; } /** * Sets the number of buckets per tablet to generate. This affects how many split points will be * generated when optimizing the Accumulo table. */ public Options setBucketsPerTablet(int bucketsPerTablet) { Preconditions.checkArgument(bucketsPerTablet > 0, "bucketsPerTablet is <= 0 : " + bucketsPerTablet); this.bucketsPerTablet = bucketsPerTablet; return this; } public <K, V> Options(String mapId, Class<? extends Combiner<K, V>> combiner, Class<K> keyType, Class<V> valueType, int buckets) { this(mapId, combiner.getName(), keyType.getName(), valueType.getName(), buckets); } public <K, V> Options(String mapId, Class<? extends Combiner<K, V>> combiner, Class<? extends UpdateObserver<K, V>> updateObserver, Class<K> keyType, Class<V> valueType, int buckets) { this(mapId, combiner.getName(), updateObserver.getName(), keyType.getName(), valueType.getName(), buckets); } void save(SimpleConfiguration appConfig) { appConfig.setProperty(PREFIX + mapId + ".combiner", combinerType + ""); if (updateObserverType != null) { appConfig.setProperty(PREFIX + mapId + ".updateObserver", updateObserverType + ""); } } } /** * This method configures a collision free map for use. It must be called before initializing * Fluo. */ public static void configure(FluoConfiguration fluoConfig, Options opts) { org.apache.fluo.recipes.core.combine.CombineQueue.FluentOptions cqopts = CombineQueue.configure(opts.mapId).keyType(opts.keyType).valueType(opts.valueType) .buckets(opts.numBuckets); if (opts.bucketsPerTablet != null) { cqopts.bucketsPerTablet(opts.bucketsPerTablet); } if (opts.bufferSize != null) { cqopts.bufferSize(opts.bufferSize); } cqopts.save(fluoConfig); opts.save(fluoConfig.getAppConfiguration()); fluoConfig.addObserver(new org.apache.fluo.api.config.ObserverSpecification( CollisionFreeMapObserver.class.getName(), Map.of("mapId", opts.mapId))); } /** * @deprecated since 1.1.0 use {@link org.apache.fluo.recipes.core.combine.CombineQueue.Optimizer} */ @Deprecated public static class Optimizer implements TableOptimizationsFactory { /** * Return suggested Fluo table optimizations for the specified collision free map. * * @param appConfig Must pass in the application configuration obtained from * {@code FluoClient.getAppConfiguration()} or * {@code FluoConfiguration.getAppConfiguration()} */ @Override public TableOptimizations getTableOptimizations(String mapId, SimpleConfiguration appConfig) { return new org.apache.fluo.recipes.core.combine.CombineQueue.Optimizer() .getTableOptimizations(mapId, appConfig); } } }
5,998
0
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core
Create_ds/fluo-recipes/modules/core/src/main/java/org/apache/fluo/recipes/core/map/NullUpdateObserver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.fluo.recipes.core.map; import java.util.Iterator; import org.apache.fluo.api.client.TransactionBase; @Deprecated class NullUpdateObserver<K, V> extends UpdateObserver<K, V> { @Override public void updatingValues(TransactionBase tx, Iterator<Update<K, V>> updates) {} }
5,999