index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/layer/BaseLayer.java | package com.airbnb.lottie.model.layer;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.Build;
import androidx.annotation.CallSuper;
import androidx.annotation.FloatRange;
import androidx.annotation.Nullable;
import com.airbnb.lottie.L;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.animation.LPaint;
import com.airbnb.lottie.animation.content.Content;
import com.airbnb.lottie.animation.content.DrawingContent;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.FloatKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.MaskKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.TransformKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.KeyPathElement;
import com.airbnb.lottie.model.content.BlurEffect;
import com.airbnb.lottie.model.content.Mask;
import com.airbnb.lottie.model.content.ShapeData;
import com.airbnb.lottie.parser.DropShadowEffect;
import com.airbnb.lottie.utils.Logger;
import com.airbnb.lottie.utils.Utils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class BaseLayer
implements DrawingContent, BaseKeyframeAnimation.AnimationListener, KeyPathElement {
/**
* These flags were in Canvas but they were deprecated and removed.
* TODO: test removing these on older versions of Android.
*/
private static final int CLIP_SAVE_FLAG = 0x02;
private static final int CLIP_TO_LAYER_SAVE_FLAG = 0x10;
private static final int MATRIX_SAVE_FLAG = 0x01;
private static final int SAVE_FLAGS = CLIP_SAVE_FLAG | CLIP_TO_LAYER_SAVE_FLAG | MATRIX_SAVE_FLAG;
@Nullable
static BaseLayer forModel(
CompositionLayer compositionLayer, Layer layerModel, LottieDrawable drawable, LottieComposition composition) {
switch (layerModel.getLayerType()) {
case SHAPE:
return new ShapeLayer(drawable, layerModel, compositionLayer, composition);
case PRE_COMP:
return new CompositionLayer(drawable, layerModel,
composition.getPrecomps(layerModel.getRefId()), composition);
case SOLID:
return new SolidLayer(drawable, layerModel);
case IMAGE:
return new ImageLayer(drawable, layerModel);
case NULL:
return new NullLayer(drawable, layerModel);
case TEXT:
return new TextLayer(drawable, layerModel);
case UNKNOWN:
default:
// Do nothing
Logger.warning("Unknown layer type " + layerModel.getLayerType());
return null;
}
}
private final Path path = new Path();
private final Matrix matrix = new Matrix();
private final Matrix canvasMatrix = new Matrix();
private final Paint contentPaint = new LPaint(Paint.ANTI_ALIAS_FLAG);
private final Paint dstInPaint = new LPaint(Paint.ANTI_ALIAS_FLAG, PorterDuff.Mode.DST_IN);
private final Paint dstOutPaint = new LPaint(Paint.ANTI_ALIAS_FLAG, PorterDuff.Mode.DST_OUT);
private final Paint mattePaint = new LPaint(Paint.ANTI_ALIAS_FLAG);
private final Paint clearPaint = new LPaint(PorterDuff.Mode.CLEAR);
private final RectF rect = new RectF();
private final RectF canvasBounds = new RectF();
private final RectF maskBoundsRect = new RectF();
private final RectF matteBoundsRect = new RectF();
private final RectF tempMaskBoundsRect = new RectF();
private final String drawTraceName;
final Matrix boundsMatrix = new Matrix();
final LottieDrawable lottieDrawable;
final Layer layerModel;
@Nullable
private MaskKeyframeAnimation mask;
@Nullable
private FloatKeyframeAnimation inOutAnimation;
@Nullable
private BaseLayer matteLayer;
/**
* This should only be used by {@link #buildParentLayerListIfNeeded()}
* to construct the list of parent layers.
*/
@Nullable
private BaseLayer parentLayer;
private List<BaseLayer> parentLayers;
private final List<BaseKeyframeAnimation<?, ?>> animations = new ArrayList<>();
final TransformKeyframeAnimation transform;
private boolean visible = true;
private boolean outlineMasksAndMattes;
@Nullable private Paint outlineMasksAndMattesPaint;
float blurMaskFilterRadius = 0f;
@Nullable BlurMaskFilter blurMaskFilter;
BaseLayer(LottieDrawable lottieDrawable, Layer layerModel) {
this.lottieDrawable = lottieDrawable;
this.layerModel = layerModel;
drawTraceName = layerModel.getName() + "#draw";
if (layerModel.getMatteType() == Layer.MatteType.INVERT) {
mattePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
} else {
mattePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
}
this.transform = layerModel.getTransform().createAnimation();
transform.addListener(this);
if (layerModel.getMasks() != null && !layerModel.getMasks().isEmpty()) {
this.mask = new MaskKeyframeAnimation(layerModel.getMasks());
for (BaseKeyframeAnimation<?, Path> animation : mask.getMaskAnimations()) {
// Don't call addAnimation() because progress gets set manually in setProgress to
// properly handle time scale.
animation.addUpdateListener(this);
}
for (BaseKeyframeAnimation<Integer, Integer> animation : mask.getOpacityAnimations()) {
addAnimation(animation);
animation.addUpdateListener(this);
}
}
setupInOutAnimations();
}
/**
* Enable this to debug slow animations by outlining masks and mattes. The performance overhead of the masks and mattes will
* be proportional to the surface area of all of the masks/mattes combined.
* <p>
* DO NOT leave this enabled in production.
*/
void setOutlineMasksAndMattes(boolean outline) {
if (outline && outlineMasksAndMattesPaint == null) {
outlineMasksAndMattesPaint = new LPaint();
}
outlineMasksAndMattes = outline;
}
@Override
public void onValueChanged() {
invalidateSelf();
}
Layer getLayerModel() {
return layerModel;
}
void setMatteLayer(@Nullable BaseLayer matteLayer) {
this.matteLayer = matteLayer;
}
boolean hasMatteOnThisLayer() {
return matteLayer != null;
}
void setParentLayer(@Nullable BaseLayer parentLayer) {
this.parentLayer = parentLayer;
}
private void setupInOutAnimations() {
if (!layerModel.getInOutKeyframes().isEmpty()) {
inOutAnimation = new FloatKeyframeAnimation(layerModel.getInOutKeyframes());
inOutAnimation.setIsDiscrete();
inOutAnimation.addUpdateListener(() -> setVisible(inOutAnimation.getFloatValue() == 1f));
setVisible(inOutAnimation.getValue() == 1f);
addAnimation(inOutAnimation);
} else {
setVisible(true);
}
}
private void invalidateSelf() {
lottieDrawable.invalidateSelf();
}
public void addAnimation(@Nullable BaseKeyframeAnimation<?, ?> newAnimation) {
if (newAnimation == null) {
return;
}
animations.add(newAnimation);
}
public void removeAnimation(BaseKeyframeAnimation<?, ?> animation) {
animations.remove(animation);
}
@CallSuper
@Override
public void getBounds(
RectF outBounds, Matrix parentMatrix, boolean applyParents) {
rect.set(0, 0, 0, 0);
buildParentLayerListIfNeeded();
boundsMatrix.set(parentMatrix);
if (applyParents) {
if (parentLayers != null) {
for (int i = parentLayers.size() - 1; i >= 0; i--) {
boundsMatrix.preConcat(parentLayers.get(i).transform.getMatrix());
}
} else if (parentLayer != null) {
boundsMatrix.preConcat(parentLayer.transform.getMatrix());
}
}
boundsMatrix.preConcat(transform.getMatrix());
}
@Override
public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
L.beginSection(drawTraceName);
if (!visible || layerModel.isHidden()) {
L.endSection(drawTraceName);
return;
}
buildParentLayerListIfNeeded();
L.beginSection("Layer#parentMatrix");
matrix.reset();
matrix.set(parentMatrix);
for (int i = parentLayers.size() - 1; i >= 0; i--) {
matrix.preConcat(parentLayers.get(i).transform.getMatrix());
}
L.endSection("Layer#parentMatrix");
// It is unclear why but getting the opacity here would sometimes NPE.
// The extra code here is designed to avoid this.
// https://github.com/airbnb/lottie-android/issues/2083
int opacity = 100;
BaseKeyframeAnimation<?, Integer> opacityAnimation = transform.getOpacity();
if (opacityAnimation != null) {
Integer opacityValue = opacityAnimation.getValue();
if (opacityValue != null) {
opacity = opacityValue;
}
}
int alpha = (int) ((parentAlpha / 255f * (float) opacity / 100f) * 255);
if (!hasMatteOnThisLayer() && !hasMasksOnThisLayer()) {
matrix.preConcat(transform.getMatrix());
L.beginSection("Layer#drawLayer");
drawLayer(canvas, matrix, alpha);
L.endSection("Layer#drawLayer");
recordRenderTime(L.endSection(drawTraceName));
return;
}
L.beginSection("Layer#computeBounds");
getBounds(rect, matrix, false);
intersectBoundsWithMatte(rect, parentMatrix);
matrix.preConcat(transform.getMatrix());
intersectBoundsWithMask(rect, matrix);
// Intersect the mask and matte rect with the canvas bounds.
// If the canvas has a transform, then we need to transform its bounds by its matrix
// so that we know the coordinate space that the canvas is showing.
canvasBounds.set(0f, 0f, canvas.getWidth(), canvas.getHeight());
//noinspection deprecation
canvas.getMatrix(canvasMatrix);
if (!canvasMatrix.isIdentity()) {
canvasMatrix.invert(canvasMatrix);
canvasMatrix.mapRect(canvasBounds);
}
if (!rect.intersect(canvasBounds)) {
rect.set(0, 0, 0, 0);
}
L.endSection("Layer#computeBounds");
// Ensure that what we are drawing is >=1px of width and height.
// On older devices, drawing to an offscreen buffer of <1px would draw back as a black bar.
// https://github.com/airbnb/lottie-android/issues/1625
if (rect.width() >= 1f && rect.height() >= 1f) {
L.beginSection("Layer#saveLayer");
contentPaint.setAlpha(255);
Utils.saveLayerCompat(canvas, rect, contentPaint);
L.endSection("Layer#saveLayer");
// Clear the off screen buffer. This is necessary for some phones.
clearCanvas(canvas);
L.beginSection("Layer#drawLayer");
drawLayer(canvas, matrix, alpha);
L.endSection("Layer#drawLayer");
if (hasMasksOnThisLayer()) {
applyMasks(canvas, matrix);
}
if (hasMatteOnThisLayer()) {
L.beginSection("Layer#drawMatte");
L.beginSection("Layer#saveLayer");
Utils.saveLayerCompat(canvas, rect, mattePaint, SAVE_FLAGS);
L.endSection("Layer#saveLayer");
clearCanvas(canvas);
//noinspection ConstantConditions
matteLayer.draw(canvas, parentMatrix, alpha);
L.beginSection("Layer#restoreLayer");
canvas.restore();
L.endSection("Layer#restoreLayer");
L.endSection("Layer#drawMatte");
}
L.beginSection("Layer#restoreLayer");
canvas.restore();
L.endSection("Layer#restoreLayer");
}
if (outlineMasksAndMattes && outlineMasksAndMattesPaint != null) {
outlineMasksAndMattesPaint.setStyle(Paint.Style.STROKE);
outlineMasksAndMattesPaint.setColor(0xFFFC2803);
outlineMasksAndMattesPaint.setStrokeWidth(4);
canvas.drawRect(rect, outlineMasksAndMattesPaint);
outlineMasksAndMattesPaint.setStyle(Paint.Style.FILL);
outlineMasksAndMattesPaint.setColor(0x50EBEBEB);
canvas.drawRect(rect, outlineMasksAndMattesPaint);
}
recordRenderTime(L.endSection(drawTraceName));
}
private void recordRenderTime(float ms) {
lottieDrawable.getComposition()
.getPerformanceTracker().recordRenderTime(layerModel.getName(), ms);
}
private void clearCanvas(Canvas canvas) {
L.beginSection("Layer#clearLayer");
// If we don't pad the clear draw, some phones leave a 1px border of the graphics buffer.
canvas.drawRect(rect.left - 1, rect.top - 1, rect.right + 1, rect.bottom + 1, clearPaint);
L.endSection("Layer#clearLayer");
}
private void intersectBoundsWithMask(RectF rect, Matrix matrix) {
maskBoundsRect.set(0, 0, 0, 0);
if (!hasMasksOnThisLayer()) {
return;
}
//noinspection ConstantConditions
int size = mask.getMasks().size();
for (int i = 0; i < size; i++) {
Mask mask = this.mask.getMasks().get(i);
BaseKeyframeAnimation<?, Path> maskAnimation = this.mask.getMaskAnimations().get(i);
Path maskPath = maskAnimation.getValue();
if (maskPath == null) {
// This should never happen but seems to happen occasionally.
// There is no known repro for this but is is probably best to just skip this mask if that is the case.
// https://github.com/airbnb/lottie-android/issues/1879
continue;
}
path.set(maskPath);
path.transform(matrix);
switch (mask.getMaskMode()) {
case MASK_MODE_NONE:
// Mask mode none will just render the original content so it is the whole bounds.
return;
case MASK_MODE_SUBTRACT:
// If there is a subtract mask, the mask could potentially be the size of the entire
// canvas so we can't use the mask bounds.
return;
case MASK_MODE_INTERSECT:
case MASK_MODE_ADD:
if (mask.isInverted()) {
return;
}
default:
path.computeBounds(tempMaskBoundsRect, false);
// As we iterate through the masks, we want to calculate the union region of the masks.
// We initialize the rect with the first mask. If we don't call set() on the first call,
// the rect will always extend to (0,0).
if (i == 0) {
maskBoundsRect.set(tempMaskBoundsRect);
} else {
maskBoundsRect.set(
Math.min(maskBoundsRect.left, tempMaskBoundsRect.left),
Math.min(maskBoundsRect.top, tempMaskBoundsRect.top),
Math.max(maskBoundsRect.right, tempMaskBoundsRect.right),
Math.max(maskBoundsRect.bottom, tempMaskBoundsRect.bottom)
);
}
}
}
boolean intersects = rect.intersect(maskBoundsRect);
if (!intersects) {
rect.set(0f, 0f, 0f, 0f);
}
}
private void intersectBoundsWithMatte(RectF rect, Matrix matrix) {
if (!hasMatteOnThisLayer()) {
return;
}
if (layerModel.getMatteType() == Layer.MatteType.INVERT) {
// We can't trim the bounds if the mask is inverted since it extends all the way to the
// composition bounds.
return;
}
matteBoundsRect.set(0f, 0f, 0f, 0f);
matteLayer.getBounds(matteBoundsRect, matrix, true);
boolean intersects = rect.intersect(matteBoundsRect);
if (!intersects) {
rect.set(0f, 0f, 0f, 0f);
}
}
abstract void drawLayer(Canvas canvas, Matrix parentMatrix, int parentAlpha);
private void applyMasks(Canvas canvas, Matrix matrix) {
L.beginSection("Layer#saveLayer");
Utils.saveLayerCompat(canvas, rect, dstInPaint, SAVE_FLAGS);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
// Pre-Pie, offscreen buffers were opaque which meant that outer border of a mask
// might get drawn depending on the result of float rounding.
clearCanvas(canvas);
}
L.endSection("Layer#saveLayer");
for (int i = 0; i < mask.getMasks().size(); i++) {
Mask mask = this.mask.getMasks().get(i);
BaseKeyframeAnimation<ShapeData, Path> maskAnimation = this.mask.getMaskAnimations().get(i);
BaseKeyframeAnimation<Integer, Integer> opacityAnimation = this.mask.getOpacityAnimations().get(i);
switch (mask.getMaskMode()) {
case MASK_MODE_NONE:
// None mask should have no effect. If all masks are NONE, fill the
// mask canvas with a rectangle so it fully covers the original layer content.
// However, if there are other masks, they should be the only ones that have an effect so
// this should noop.
if (areAllMasksNone()) {
contentPaint.setAlpha(255);
canvas.drawRect(rect, contentPaint);
}
break;
case MASK_MODE_ADD:
if (mask.isInverted()) {
applyInvertedAddMask(canvas, matrix, maskAnimation, opacityAnimation);
} else {
applyAddMask(canvas, matrix, maskAnimation, opacityAnimation);
}
break;
case MASK_MODE_SUBTRACT:
if (i == 0) {
contentPaint.setColor(Color.BLACK);
contentPaint.setAlpha(255);
canvas.drawRect(rect, contentPaint);
}
if (mask.isInverted()) {
applyInvertedSubtractMask(canvas, matrix, maskAnimation, opacityAnimation);
} else {
applySubtractMask(canvas, matrix, maskAnimation);
}
break;
case MASK_MODE_INTERSECT:
if (mask.isInverted()) {
applyInvertedIntersectMask(canvas, matrix, maskAnimation, opacityAnimation);
} else {
applyIntersectMask(canvas, matrix, maskAnimation, opacityAnimation);
}
break;
}
}
L.beginSection("Layer#restoreLayer");
canvas.restore();
L.endSection("Layer#restoreLayer");
}
private boolean areAllMasksNone() {
if (mask.getMaskAnimations().isEmpty()) {
return false;
}
for (int i = 0; i < mask.getMasks().size(); i++) {
if (mask.getMasks().get(i).getMaskMode() != Mask.MaskMode.MASK_MODE_NONE) {
return false;
}
}
return true;
}
private void applyAddMask(Canvas canvas, Matrix matrix,
BaseKeyframeAnimation<ShapeData, Path> maskAnimation, BaseKeyframeAnimation<Integer, Integer> opacityAnimation) {
Path maskPath = maskAnimation.getValue();
path.set(maskPath);
path.transform(matrix);
contentPaint.setAlpha((int) (opacityAnimation.getValue() * 2.55f));
canvas.drawPath(path, contentPaint);
}
private void applyInvertedAddMask(Canvas canvas, Matrix matrix,
BaseKeyframeAnimation<ShapeData, Path> maskAnimation, BaseKeyframeAnimation<Integer, Integer> opacityAnimation) {
Utils.saveLayerCompat(canvas, rect, contentPaint);
canvas.drawRect(rect, contentPaint);
Path maskPath = maskAnimation.getValue();
path.set(maskPath);
path.transform(matrix);
contentPaint.setAlpha((int) (opacityAnimation.getValue() * 2.55f));
canvas.drawPath(path, dstOutPaint);
canvas.restore();
}
private void applySubtractMask(Canvas canvas, Matrix matrix, BaseKeyframeAnimation<ShapeData, Path> maskAnimation) {
Path maskPath = maskAnimation.getValue();
path.set(maskPath);
path.transform(matrix);
canvas.drawPath(path, dstOutPaint);
}
private void applyInvertedSubtractMask(Canvas canvas, Matrix matrix,
BaseKeyframeAnimation<ShapeData, Path> maskAnimation, BaseKeyframeAnimation<Integer, Integer> opacityAnimation) {
Utils.saveLayerCompat(canvas, rect, dstOutPaint);
canvas.drawRect(rect, contentPaint);
dstOutPaint.setAlpha((int) (opacityAnimation.getValue() * 2.55f));
Path maskPath = maskAnimation.getValue();
path.set(maskPath);
path.transform(matrix);
canvas.drawPath(path, dstOutPaint);
canvas.restore();
}
private void applyIntersectMask(Canvas canvas, Matrix matrix,
BaseKeyframeAnimation<ShapeData, Path> maskAnimation, BaseKeyframeAnimation<Integer, Integer> opacityAnimation) {
Utils.saveLayerCompat(canvas, rect, dstInPaint);
Path maskPath = maskAnimation.getValue();
path.set(maskPath);
path.transform(matrix);
contentPaint.setAlpha((int) (opacityAnimation.getValue() * 2.55f));
canvas.drawPath(path, contentPaint);
canvas.restore();
}
private void applyInvertedIntersectMask(Canvas canvas, Matrix matrix,
BaseKeyframeAnimation<ShapeData, Path> maskAnimation, BaseKeyframeAnimation<Integer, Integer> opacityAnimation) {
Utils.saveLayerCompat(canvas, rect, dstInPaint);
canvas.drawRect(rect, contentPaint);
dstOutPaint.setAlpha((int) (opacityAnimation.getValue() * 2.55f));
Path maskPath = maskAnimation.getValue();
path.set(maskPath);
path.transform(matrix);
canvas.drawPath(path, dstOutPaint);
canvas.restore();
}
boolean hasMasksOnThisLayer() {
return mask != null && !mask.getMaskAnimations().isEmpty();
}
private void setVisible(boolean visible) {
if (visible != this.visible) {
this.visible = visible;
invalidateSelf();
}
}
void setProgress(@FloatRange(from = 0f, to = 1f) float progress) {
L.beginSection("BaseLayer#setProgress");
// Time stretch should not be applied to the layer transform.
L.beginSection("BaseLayer#setProgress.transform");
transform.setProgress(progress);
L.endSection("BaseLayer#setProgress.transform");
if (mask != null) {
L.beginSection("BaseLayer#setProgress.mask");
for (int i = 0; i < mask.getMaskAnimations().size(); i++) {
mask.getMaskAnimations().get(i).setProgress(progress);
}
L.endSection("BaseLayer#setProgress.mask");
}
if (inOutAnimation != null) {
L.beginSection("BaseLayer#setProgress.inout");
inOutAnimation.setProgress(progress);
L.endSection("BaseLayer#setProgress.inout");
}
if (matteLayer != null) {
L.beginSection("BaseLayer#setProgress.matte");
matteLayer.setProgress(progress);
L.endSection("BaseLayer#setProgress.matte");
}
L.beginSection("BaseLayer#setProgress.animations." + animations.size());
for (int i = 0; i < animations.size(); i++) {
animations.get(i).setProgress(progress);
}
L.endSection("BaseLayer#setProgress.animations." + animations.size());
L.endSection("BaseLayer#setProgress");
}
private void buildParentLayerListIfNeeded() {
if (parentLayers != null) {
return;
}
if (parentLayer == null) {
parentLayers = Collections.emptyList();
return;
}
parentLayers = new ArrayList<>();
BaseLayer layer = parentLayer;
while (layer != null) {
parentLayers.add(layer);
layer = layer.parentLayer;
}
}
@Override
public String getName() {
return layerModel.getName();
}
@Nullable
public BlurEffect getBlurEffect() {
return layerModel.getBlurEffect();
}
public BlurMaskFilter getBlurMaskFilter(float radius) {
if (blurMaskFilterRadius == radius) {
return blurMaskFilter;
}
blurMaskFilter = new BlurMaskFilter(radius / 2f, BlurMaskFilter.Blur.NORMAL);
blurMaskFilterRadius = radius;
return blurMaskFilter;
}
@Nullable
public DropShadowEffect getDropShadowEffect() {
return layerModel.getDropShadowEffect();
}
@Override
public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
// Do nothing
}
@Override
public void resolveKeyPath(
KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) {
if (matteLayer != null) {
KeyPath matteCurrentPartialKeyPath = currentPartialKeyPath.addKey(matteLayer.getName());
if (keyPath.fullyResolvesTo(matteLayer.getName(), depth)) {
accumulator.add(matteCurrentPartialKeyPath.resolve(matteLayer));
}
if (keyPath.propagateToChildren(getName(), depth)) {
int newDepth = depth + keyPath.incrementDepthBy(matteLayer.getName(), depth);
matteLayer.resolveChildKeyPath(keyPath, newDepth, accumulator, matteCurrentPartialKeyPath);
}
}
if (!keyPath.matches(getName(), depth)) {
return;
}
if (!"__container".equals(getName())) {
currentPartialKeyPath = currentPartialKeyPath.addKey(getName());
if (keyPath.fullyResolvesTo(getName(), depth)) {
accumulator.add(currentPartialKeyPath.resolve(this));
}
}
if (keyPath.propagateToChildren(getName(), depth)) {
int newDepth = depth + keyPath.incrementDepthBy(getName(), depth);
resolveChildKeyPath(keyPath, newDepth, accumulator, currentPartialKeyPath);
}
}
void resolveChildKeyPath(
KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) {
}
@CallSuper
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
transform.applyValueCallback(property, callback);
}
}
| 2,600 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/layer/CompositionLayer.java | package com.airbnb.lottie.model.layer;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.Log;
import androidx.annotation.FloatRange;
import androidx.annotation.Nullable;
import androidx.collection.LongSparseArray;
import com.airbnb.lottie.L;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.animatable.AnimatableFloatValue;
import com.airbnb.lottie.utils.Utils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.ArrayList;
import java.util.List;
public class CompositionLayer extends BaseLayer {
@Nullable private BaseKeyframeAnimation<Float, Float> timeRemapping;
private final List<BaseLayer> layers = new ArrayList<>();
private final RectF rect = new RectF();
private final RectF newClipRect = new RectF();
private final Paint layerPaint = new Paint();
@Nullable private Boolean hasMatte;
@Nullable private Boolean hasMasks;
private float progress;
private boolean clipToCompositionBounds = true;
public CompositionLayer(LottieDrawable lottieDrawable, Layer layerModel, List<Layer> layerModels,
LottieComposition composition) {
super(lottieDrawable, layerModel);
AnimatableFloatValue timeRemapping = layerModel.getTimeRemapping();
if (timeRemapping != null) {
this.timeRemapping = timeRemapping.createAnimation();
addAnimation(this.timeRemapping);
//noinspection ConstantConditions
this.timeRemapping.addUpdateListener(this);
} else {
this.timeRemapping = null;
}
LongSparseArray<BaseLayer> layerMap =
new LongSparseArray<>(composition.getLayers().size());
BaseLayer mattedLayer = null;
for (int i = layerModels.size() - 1; i >= 0; i--) {
Layer lm = layerModels.get(i);
BaseLayer layer = BaseLayer.forModel(this, lm, lottieDrawable, composition);
if (layer == null) {
continue;
}
layerMap.put(layer.getLayerModel().getId(), layer);
if (mattedLayer != null) {
mattedLayer.setMatteLayer(layer);
mattedLayer = null;
} else {
layers.add(0, layer);
switch (lm.getMatteType()) {
case ADD:
case INVERT:
mattedLayer = layer;
break;
}
}
}
for (int i = 0; i < layerMap.size(); i++) {
long key = layerMap.keyAt(i);
BaseLayer layerView = layerMap.get(key);
// This shouldn't happen but it appears as if sometimes on pre-lollipop devices when
// compiled with d8, layerView is null sometimes.
// https://github.com/airbnb/lottie-android/issues/524
if (layerView == null) {
continue;
}
BaseLayer parentLayer = layerMap.get(layerView.getLayerModel().getParentId());
if (parentLayer != null) {
layerView.setParentLayer(parentLayer);
}
}
}
public void setClipToCompositionBounds(boolean clipToCompositionBounds) {
this.clipToCompositionBounds = clipToCompositionBounds;
}
@Override public void setOutlineMasksAndMattes(boolean outline) {
super.setOutlineMasksAndMattes(outline);
for (BaseLayer layer : layers) {
layer.setOutlineMasksAndMattes(outline);
}
}
@Override void drawLayer(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
L.beginSection("CompositionLayer#draw");
newClipRect.set(0, 0, layerModel.getPreCompWidth(), layerModel.getPreCompHeight());
parentMatrix.mapRect(newClipRect);
// Apply off-screen rendering only when needed in order to improve rendering performance.
boolean isDrawingWithOffScreen = lottieDrawable.isApplyingOpacityToLayersEnabled() && layers.size() > 1 && parentAlpha != 255;
if (isDrawingWithOffScreen) {
layerPaint.setAlpha(parentAlpha);
Utils.saveLayerCompat(canvas, newClipRect, layerPaint);
} else {
canvas.save();
}
int childAlpha = isDrawingWithOffScreen ? 255 : parentAlpha;
for (int i = layers.size() - 1; i >= 0; i--) {
boolean nonEmptyClip = true;
// Only clip precomps. This mimics the way After Effects renders animations.
boolean ignoreClipOnThisLayer = !clipToCompositionBounds && "__container".equals(layerModel.getName());
if (!ignoreClipOnThisLayer && !newClipRect.isEmpty()) {
nonEmptyClip = canvas.clipRect(newClipRect);
}
if (nonEmptyClip) {
BaseLayer layer = layers.get(i);
layer.draw(canvas, parentMatrix, childAlpha);
}
}
canvas.restore();
L.endSection("CompositionLayer#draw");
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
super.getBounds(outBounds, parentMatrix, applyParents);
for (int i = layers.size() - 1; i >= 0; i--) {
rect.set(0, 0, 0, 0);
layers.get(i).getBounds(rect, boundsMatrix, true);
outBounds.union(rect);
}
}
@Override public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) {
L.beginSection("CompositionLayer#setProgress");
this.progress = progress;
super.setProgress(progress);
if (timeRemapping != null) {
// The duration has 0.01 frame offset to show end of animation properly.
// https://github.com/airbnb/lottie-android/pull/766
// Ignore this offset for calculating time-remapping because time-remapping value is based on original duration.
float durationFrames = lottieDrawable.getComposition().getDurationFrames() + 0.01f;
float compositionDelayFrames = layerModel.getComposition().getStartFrame();
float remappedFrames = timeRemapping.getValue() * layerModel.getComposition().getFrameRate() - compositionDelayFrames;
progress = remappedFrames / durationFrames;
}
if (timeRemapping == null) {
progress -= layerModel.getStartProgress();
}
//Time stretch needs to be divided if is not "__container"
if (layerModel.getTimeStretch() != 0 && !"__container".equals(layerModel.getName())) {
progress /= layerModel.getTimeStretch();
}
for (int i = layers.size() - 1; i >= 0; i--) {
layers.get(i).setProgress(progress);
}
L.endSection("CompositionLayer#setProgress");
}
public float getProgress() {
return progress;
}
public boolean hasMasks() {
if (hasMasks == null) {
for (int i = layers.size() - 1; i >= 0; i--) {
BaseLayer layer = layers.get(i);
if (layer instanceof ShapeLayer) {
if (layer.hasMasksOnThisLayer()) {
hasMasks = true;
return true;
}
} else if (layer instanceof CompositionLayer && ((CompositionLayer) layer).hasMasks()) {
hasMasks = true;
return true;
}
}
hasMasks = false;
}
return hasMasks;
}
public boolean hasMatte() {
if (hasMatte == null) {
if (hasMatteOnThisLayer()) {
hasMatte = true;
return true;
}
for (int i = layers.size() - 1; i >= 0; i--) {
if (layers.get(i).hasMatteOnThisLayer()) {
hasMatte = true;
return true;
}
}
hasMatte = false;
}
return hasMatte;
}
@Override
protected void resolveChildKeyPath(KeyPath keyPath, int depth, List<KeyPath> accumulator,
KeyPath currentPartialKeyPath) {
for (int i = 0; i < layers.size(); i++) {
layers.get(i).resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath);
}
}
@SuppressWarnings("unchecked")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
super.addValueCallback(property, callback);
if (property == LottieProperty.TIME_REMAP) {
if (callback == null) {
if (timeRemapping != null) {
timeRemapping.setValueCallback(null);
}
} else {
timeRemapping = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback);
timeRemapping.addUpdateListener(this);
addAnimation(timeRemapping);
}
}
}
}
| 2,601 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/layer/ImageLayer.java | package com.airbnb.lottie.model.layer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieImageAsset;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.LPaint;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation;
import com.airbnb.lottie.utils.Utils;
import com.airbnb.lottie.value.LottieValueCallback;
public class ImageLayer extends BaseLayer {
private final Paint paint = new LPaint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
private final Rect src = new Rect();
private final Rect dst = new Rect();
@Nullable private final LottieImageAsset lottieImageAsset;
@Nullable private BaseKeyframeAnimation<ColorFilter, ColorFilter> colorFilterAnimation;
@Nullable private BaseKeyframeAnimation<Bitmap, Bitmap> imageAnimation;
ImageLayer(LottieDrawable lottieDrawable, Layer layerModel) {
super(lottieDrawable, layerModel);
lottieImageAsset = lottieDrawable.getLottieImageAssetForId(layerModel.getRefId());
}
@Override public void drawLayer(@NonNull Canvas canvas, Matrix parentMatrix, int parentAlpha) {
Bitmap bitmap = getBitmap();
if (bitmap == null || bitmap.isRecycled() || lottieImageAsset == null) {
return;
}
float density = Utils.dpScale();
paint.setAlpha(parentAlpha);
if (colorFilterAnimation != null) {
paint.setColorFilter(colorFilterAnimation.getValue());
}
canvas.save();
canvas.concat(parentMatrix);
src.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
if (lottieDrawable.getMaintainOriginalImageBounds()) {
dst.set(0, 0, (int) (lottieImageAsset.getWidth() * density), (int) (lottieImageAsset.getHeight() * density));
} else {
dst.set(0, 0, (int) (bitmap.getWidth() * density), (int) (bitmap.getHeight() * density));
}
canvas.drawBitmap(bitmap, src, dst, paint);
canvas.restore();
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
super.getBounds(outBounds, parentMatrix, applyParents);
if (lottieImageAsset != null) {
float scale = Utils.dpScale();
outBounds.set(0, 0, lottieImageAsset.getWidth() * scale, lottieImageAsset.getHeight() * scale);
boundsMatrix.mapRect(outBounds);
}
}
@Nullable
private Bitmap getBitmap() {
if (imageAnimation != null) {
Bitmap callbackBitmap = imageAnimation.getValue();
if (callbackBitmap != null) {
return callbackBitmap;
}
}
String refId = layerModel.getRefId();
Bitmap bitmapFromDrawable = lottieDrawable.getBitmapForId(refId);
if (bitmapFromDrawable != null) {
return bitmapFromDrawable;
}
LottieImageAsset asset = this.lottieImageAsset;
if (asset != null) {
return asset.getBitmap();
}
return null;
}
@SuppressWarnings("SingleStatementInBlock")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
super.addValueCallback(property, callback);
if (property == LottieProperty.COLOR_FILTER) {
if (callback == null) {
colorFilterAnimation = null;
} else {
//noinspection unchecked
colorFilterAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<ColorFilter>) callback);
}
} else if (property == LottieProperty.IMAGE) {
if (callback == null) {
imageAnimation = null;
} else {
//noinspection unchecked
imageAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Bitmap>) callback);
}
}
}
}
| 2,602 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/layer/TextLayer.java | package com.airbnb.lottie.model.layer;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Typeface;
import androidx.annotation.Nullable;
import androidx.collection.LongSparseArray;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.TextDelegate;
import com.airbnb.lottie.animation.content.ContentGroup;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.TextKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation;
import com.airbnb.lottie.model.DocumentData;
import com.airbnb.lottie.model.Font;
import com.airbnb.lottie.model.FontCharacter;
import com.airbnb.lottie.model.animatable.AnimatableTextProperties;
import com.airbnb.lottie.model.content.ShapeGroup;
import com.airbnb.lottie.utils.Utils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TextLayer extends BaseLayer {
// Capacity is 2 because emojis are 2 characters. Some are longer in which case, the capacity will
// be expanded but that should be pretty rare.
private final StringBuilder stringBuilder = new StringBuilder(2);
private final RectF rectF = new RectF();
private final Matrix matrix = new Matrix();
private final Paint fillPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {{
setStyle(Style.FILL);
}};
private final Paint strokePaint = new Paint(Paint.ANTI_ALIAS_FLAG) {{
setStyle(Style.STROKE);
}};
private final Map<FontCharacter, List<ContentGroup>> contentsForCharacter = new HashMap<>();
private final LongSparseArray<String> codePointCache = new LongSparseArray<>();
/**
* If this is paragraph text, one line may wrap depending on the size of the document data box.
*/
private final List<TextSubLine> textSubLines = new ArrayList<>();
private final TextKeyframeAnimation textAnimation;
private final LottieDrawable lottieDrawable;
private final LottieComposition composition;
@Nullable
private BaseKeyframeAnimation<Integer, Integer> colorAnimation;
@Nullable
private BaseKeyframeAnimation<Integer, Integer> colorCallbackAnimation;
@Nullable
private BaseKeyframeAnimation<Integer, Integer> strokeColorAnimation;
@Nullable
private BaseKeyframeAnimation<Integer, Integer> strokeColorCallbackAnimation;
@Nullable
private BaseKeyframeAnimation<Float, Float> strokeWidthAnimation;
@Nullable
private BaseKeyframeAnimation<Float, Float> strokeWidthCallbackAnimation;
@Nullable
private BaseKeyframeAnimation<Float, Float> trackingAnimation;
@Nullable
private BaseKeyframeAnimation<Float, Float> trackingCallbackAnimation;
@Nullable
private BaseKeyframeAnimation<Float, Float> textSizeCallbackAnimation;
@Nullable
private BaseKeyframeAnimation<Typeface, Typeface> typefaceCallbackAnimation;
TextLayer(LottieDrawable lottieDrawable, Layer layerModel) {
super(lottieDrawable, layerModel);
this.lottieDrawable = lottieDrawable;
composition = layerModel.getComposition();
//noinspection ConstantConditions
textAnimation = layerModel.getText().createAnimation();
textAnimation.addUpdateListener(this);
addAnimation(textAnimation);
AnimatableTextProperties textProperties = layerModel.getTextProperties();
if (textProperties != null && textProperties.color != null) {
colorAnimation = textProperties.color.createAnimation();
colorAnimation.addUpdateListener(this);
addAnimation(colorAnimation);
}
if (textProperties != null && textProperties.stroke != null) {
strokeColorAnimation = textProperties.stroke.createAnimation();
strokeColorAnimation.addUpdateListener(this);
addAnimation(strokeColorAnimation);
}
if (textProperties != null && textProperties.strokeWidth != null) {
strokeWidthAnimation = textProperties.strokeWidth.createAnimation();
strokeWidthAnimation.addUpdateListener(this);
addAnimation(strokeWidthAnimation);
}
if (textProperties != null && textProperties.tracking != null) {
trackingAnimation = textProperties.tracking.createAnimation();
trackingAnimation.addUpdateListener(this);
addAnimation(trackingAnimation);
}
}
@Override
public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
super.getBounds(outBounds, parentMatrix, applyParents);
// TODO: use the correct text bounds.
outBounds.set(0, 0, composition.getBounds().width(), composition.getBounds().height());
}
@Override
void drawLayer(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
DocumentData documentData = textAnimation.getValue();
Font font = composition.getFonts().get(documentData.fontName);
if (font == null) {
return;
}
canvas.save();
canvas.concat(parentMatrix);
configurePaint(documentData, parentAlpha);
if (lottieDrawable.useTextGlyphs()) {
drawTextWithGlyphs(documentData, parentMatrix, font, canvas);
} else {
drawTextWithFont(documentData, font, canvas);
}
canvas.restore();
}
private void configurePaint(DocumentData documentData, int parentAlpha) {
if (colorCallbackAnimation != null) {
fillPaint.setColor(colorCallbackAnimation.getValue());
} else if (colorAnimation != null) {
fillPaint.setColor(colorAnimation.getValue());
} else {
fillPaint.setColor(documentData.color);
}
if (strokeColorCallbackAnimation != null) {
strokePaint.setColor(strokeColorCallbackAnimation.getValue());
} else if (strokeColorAnimation != null) {
strokePaint.setColor(strokeColorAnimation.getValue());
} else {
strokePaint.setColor(documentData.strokeColor);
}
int opacity = transform.getOpacity() == null ? 100 : transform.getOpacity().getValue();
int alpha = opacity * 255 / 100 * parentAlpha / 255;
fillPaint.setAlpha(alpha);
strokePaint.setAlpha(alpha);
if (strokeWidthCallbackAnimation != null) {
strokePaint.setStrokeWidth(strokeWidthCallbackAnimation.getValue());
} else if (strokeWidthAnimation != null) {
strokePaint.setStrokeWidth(strokeWidthAnimation.getValue());
} else {
strokePaint.setStrokeWidth(documentData.strokeWidth * Utils.dpScale());
}
}
private void drawTextWithGlyphs(
DocumentData documentData, Matrix parentMatrix, Font font, Canvas canvas) {
float textSize;
if (textSizeCallbackAnimation != null) {
textSize = textSizeCallbackAnimation.getValue();
} else {
textSize = documentData.size;
}
float fontScale = textSize / 100f;
float parentScale = Utils.getScale(parentMatrix);
String text = documentData.text;
// Split full text in multiple lines
List<String> textLines = getTextLines(text);
int textLineCount = textLines.size();
// Add tracking
float tracking = documentData.tracking / 10f;
if (trackingCallbackAnimation != null) {
tracking += trackingCallbackAnimation.getValue();
} else if (trackingAnimation != null) {
tracking += trackingAnimation.getValue();
}
int lineIndex = -1;
for (int i = 0; i < textLineCount; i++) {
String textLine = textLines.get(i);
float boxWidth = documentData.boxSize == null ? 0f : documentData.boxSize.x;
List<TextSubLine> lines = splitGlyphTextIntoLines(textLine, boxWidth, font, fontScale, tracking, true);
for (int j = 0; j < lines.size(); j++) {
TextSubLine line = lines.get(j);
lineIndex++;
canvas.save();
offsetCanvas(canvas, documentData, lineIndex, line.width);
drawGlyphTextLine(line.text, documentData, font, canvas, parentScale, fontScale, tracking);
canvas.restore();
}
}
}
private void drawGlyphTextLine(String text, DocumentData documentData,
Font font, Canvas canvas, float parentScale, float fontScale, float tracking) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
int characterHash = FontCharacter.hashFor(c, font.getFamily(), font.getStyle());
FontCharacter character = composition.getCharacters().get(characterHash);
if (character == null) {
// Something is wrong. Potentially, they didn't export the text as a glyph.
continue;
}
drawCharacterAsGlyph(character, fontScale, documentData, canvas);
float tx = (float) character.getWidth() * fontScale * Utils.dpScale() + tracking;
canvas.translate(tx, 0);
}
}
private void drawTextWithFont(DocumentData documentData, Font font, Canvas canvas) {
Typeface typeface = getTypeface(font);
if (typeface == null) {
return;
}
String text = documentData.text;
TextDelegate textDelegate = lottieDrawable.getTextDelegate();
if (textDelegate != null) {
text = textDelegate.getTextInternal(getName(), text);
}
fillPaint.setTypeface(typeface);
float textSize;
if (textSizeCallbackAnimation != null) {
textSize = textSizeCallbackAnimation.getValue();
} else {
textSize = documentData.size;
}
fillPaint.setTextSize(textSize * Utils.dpScale());
strokePaint.setTypeface(fillPaint.getTypeface());
strokePaint.setTextSize(fillPaint.getTextSize());
// Calculate tracking
float tracking = documentData.tracking / 10f;
if (trackingCallbackAnimation != null) {
tracking += trackingCallbackAnimation.getValue();
} else if (trackingAnimation != null) {
tracking += trackingAnimation.getValue();
}
tracking = tracking * Utils.dpScale() * textSize / 100.0f;
// Split full text in multiple lines
List<String> textLines = getTextLines(text);
int textLineCount = textLines.size();
int lineIndex = -1;
for (int i = 0; i < textLineCount; i++) {
String textLine = textLines.get(i);
float boxWidth = documentData.boxSize == null ? 0f : documentData.boxSize.x;
List<TextSubLine> lines = splitGlyphTextIntoLines(textLine, boxWidth, font, 0f, tracking, false);
for (int j = 0; j < lines.size(); j++) {
TextSubLine line = lines.get(j);
lineIndex++;
canvas.save();
offsetCanvas(canvas, documentData, lineIndex, line.width);
drawFontTextLine(line.text, documentData, canvas, tracking);
canvas.restore();
}
}
}
private void offsetCanvas(Canvas canvas, DocumentData documentData, int lineIndex, float lineWidth) {
PointF position = documentData.boxPosition;
PointF size = documentData.boxSize;
float dpScale = Utils.dpScale();
float lineStartY = position == null ? 0f : documentData.lineHeight * dpScale + position.y;
float lineOffset = (lineIndex * documentData.lineHeight * dpScale) + lineStartY;
float lineStart = position == null ? 0f : position.x;
float boxWidth = size == null ? 0f : size.x;
switch (documentData.justification) {
case LEFT_ALIGN:
canvas.translate(lineStart, lineOffset);
break;
case RIGHT_ALIGN:
canvas.translate(lineStart + boxWidth - lineWidth, lineOffset);
break;
case CENTER:
canvas.translate(lineStart + boxWidth / 2f - lineWidth / 2f, lineOffset);
break;
}
}
@Nullable
private Typeface getTypeface(Font font) {
if (typefaceCallbackAnimation != null) {
Typeface callbackTypeface = typefaceCallbackAnimation.getValue();
if (callbackTypeface != null) {
return callbackTypeface;
}
}
Typeface drawableTypeface = lottieDrawable.getTypeface(font);
if (drawableTypeface != null) {
return drawableTypeface;
}
return font.getTypeface();
}
private List<String> getTextLines(String text) {
// Split full text by carriage return character
String formattedText = text.replaceAll("\r\n", "\r")
.replaceAll("\u0003", "\r")
.replaceAll("\n", "\r");
String[] textLinesArray = formattedText.split("\r");
return Arrays.asList(textLinesArray);
}
private void drawFontTextLine(String text, DocumentData documentData, Canvas canvas, float tracking) {
for (int i = 0; i < text.length(); ) {
String charString = codePointToString(text, i);
i += charString.length();
drawCharacterFromFont(charString, documentData, canvas);
float charWidth = fillPaint.measureText(charString);
float tx = charWidth + tracking;
canvas.translate(tx, 0);
}
}
private List<TextSubLine> splitGlyphTextIntoLines(String textLine, float boxWidth, Font font, float fontScale, float tracking,
boolean usingGlyphs) {
int lineCount = 0;
float currentLineWidth = 0;
int currentLineStartIndex = 0;
int currentWordStartIndex = 0;
float currentWordWidth = 0f;
boolean nextCharacterStartsWord = false;
// The measured size of a space.
float spaceWidth = 0f;
for (int i = 0; i < textLine.length(); i++) {
char c = textLine.charAt(i);
float currentCharWidth;
if (usingGlyphs) {
int characterHash = FontCharacter.hashFor(c, font.getFamily(), font.getStyle());
FontCharacter character = composition.getCharacters().get(characterHash);
if (character == null) {
continue;
}
currentCharWidth = (float) character.getWidth() * fontScale * Utils.dpScale() + tracking;
} else {
currentCharWidth = fillPaint.measureText(textLine.substring(i, i + 1)) + tracking;
}
if (c == ' ') {
spaceWidth = currentCharWidth;
nextCharacterStartsWord = true;
} else if (nextCharacterStartsWord) {
nextCharacterStartsWord = false;
currentWordStartIndex = i;
currentWordWidth = currentCharWidth;
} else {
currentWordWidth += currentCharWidth;
}
currentLineWidth += currentCharWidth;
if (boxWidth > 0f && currentLineWidth >= boxWidth) {
if (c == ' ') {
// Spaces at the end of a line don't do anything. Ignore it.
// The next non-space character will hit the conditions below.
continue;
}
TextSubLine subLine = ensureEnoughSubLines(++lineCount);
if (currentWordStartIndex == currentLineStartIndex) {
// Only word on line is wider than box, start wrapping mid-word.
String substr = textLine.substring(currentLineStartIndex, i);
String trimmed = substr.trim();
float trimmedSpace = (trimmed.length() - substr.length()) * spaceWidth;
subLine.set(trimmed, currentLineWidth - currentCharWidth - trimmedSpace);
currentLineStartIndex = i;
currentLineWidth = currentCharWidth;
currentWordStartIndex = currentLineStartIndex;
currentWordWidth = currentCharWidth;
} else {
String substr = textLine.substring(currentLineStartIndex, currentWordStartIndex - 1);
String trimmed = substr.trim();
float trimmedSpace = (substr.length() - trimmed.length()) * spaceWidth;
subLine.set(trimmed, currentLineWidth - currentWordWidth - trimmedSpace - spaceWidth);
currentLineStartIndex = currentWordStartIndex;
currentLineWidth = currentWordWidth;
}
}
}
if (currentLineWidth > 0f) {
TextSubLine line = ensureEnoughSubLines(++lineCount);
line.set(textLine.substring(currentLineStartIndex), currentLineWidth);
}
return textSubLines.subList(0, lineCount);
}
/**
* Elements are reused and not deleted to save allocations.
*/
private TextSubLine ensureEnoughSubLines(int numLines) {
for (int i = textSubLines.size(); i < numLines; i++) {
textSubLines.add(new TextSubLine());
}
return textSubLines.get(numLines - 1);
}
private void drawCharacterAsGlyph(
FontCharacter character,
float fontScale,
DocumentData documentData,
Canvas canvas) {
List<ContentGroup> contentGroups = getContentsForCharacter(character);
for (int j = 0; j < contentGroups.size(); j++) {
Path path = contentGroups.get(j).getPath();
path.computeBounds(rectF, false);
matrix.reset();
matrix.preTranslate(0, -documentData.baselineShift * Utils.dpScale());
matrix.preScale(fontScale, fontScale);
path.transform(matrix);
if (documentData.strokeOverFill) {
drawGlyph(path, fillPaint, canvas);
drawGlyph(path, strokePaint, canvas);
} else {
drawGlyph(path, strokePaint, canvas);
drawGlyph(path, fillPaint, canvas);
}
}
}
private void drawGlyph(Path path, Paint paint, Canvas canvas) {
if (paint.getColor() == Color.TRANSPARENT) {
return;
}
if (paint.getStyle() == Paint.Style.STROKE && paint.getStrokeWidth() == 0) {
return;
}
canvas.drawPath(path, paint);
}
private void drawCharacterFromFont(String character, DocumentData documentData, Canvas canvas) {
if (documentData.strokeOverFill) {
drawCharacter(character, fillPaint, canvas);
drawCharacter(character, strokePaint, canvas);
} else {
drawCharacter(character, strokePaint, canvas);
drawCharacter(character, fillPaint, canvas);
}
}
private void drawCharacter(String character, Paint paint, Canvas canvas) {
if (paint.getColor() == Color.TRANSPARENT) {
return;
}
if (paint.getStyle() == Paint.Style.STROKE && paint.getStrokeWidth() == 0) {
return;
}
canvas.drawText(character, 0, character.length(), 0, 0, paint);
}
private List<ContentGroup> getContentsForCharacter(FontCharacter character) {
if (contentsForCharacter.containsKey(character)) {
return contentsForCharacter.get(character);
}
List<ShapeGroup> shapes = character.getShapes();
int size = shapes.size();
List<ContentGroup> contents = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
ShapeGroup sg = shapes.get(i);
contents.add(new ContentGroup(lottieDrawable, this, sg, composition));
}
contentsForCharacter.put(character, contents);
return contents;
}
private String codePointToString(String text, int startIndex) {
int firstCodePoint = text.codePointAt(startIndex);
int firstCodePointLength = Character.charCount(firstCodePoint);
int key = firstCodePoint;
int index = startIndex + firstCodePointLength;
while (index < text.length()) {
int nextCodePoint = text.codePointAt(index);
if (!isModifier(nextCodePoint)) {
break;
}
int nextCodePointLength = Character.charCount(nextCodePoint);
index += nextCodePointLength;
key = key * 31 + nextCodePoint;
}
if (codePointCache.containsKey(key)) {
return codePointCache.get(key);
}
stringBuilder.setLength(0);
for (int i = startIndex; i < index; ) {
int codePoint = text.codePointAt(i);
stringBuilder.appendCodePoint(codePoint);
i += Character.charCount(codePoint);
}
String str = stringBuilder.toString();
codePointCache.put(key, str);
return str;
}
private boolean isModifier(int codePoint) {
return Character.getType(codePoint) == Character.FORMAT ||
Character.getType(codePoint) == Character.MODIFIER_SYMBOL ||
Character.getType(codePoint) == Character.NON_SPACING_MARK ||
Character.getType(codePoint) == Character.OTHER_SYMBOL ||
Character.getType(codePoint) == Character.DIRECTIONALITY_NONSPACING_MARK ||
Character.getType(codePoint) == Character.SURROGATE;
}
@SuppressWarnings("unchecked")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
super.addValueCallback(property, callback);
if (property == LottieProperty.COLOR) {
if (colorCallbackAnimation != null) {
removeAnimation(colorCallbackAnimation);
}
if (callback == null) {
colorCallbackAnimation = null;
} else {
colorCallbackAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Integer>) callback);
colorCallbackAnimation.addUpdateListener(this);
addAnimation(colorCallbackAnimation);
}
} else if (property == LottieProperty.STROKE_COLOR) {
if (strokeColorCallbackAnimation != null) {
removeAnimation(strokeColorCallbackAnimation);
}
if (callback == null) {
strokeColorCallbackAnimation = null;
} else {
strokeColorCallbackAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Integer>) callback);
strokeColorCallbackAnimation.addUpdateListener(this);
addAnimation(strokeColorCallbackAnimation);
}
} else if (property == LottieProperty.STROKE_WIDTH) {
if (strokeWidthCallbackAnimation != null) {
removeAnimation(strokeWidthCallbackAnimation);
}
if (callback == null) {
strokeWidthCallbackAnimation = null;
} else {
strokeWidthCallbackAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback);
strokeWidthCallbackAnimation.addUpdateListener(this);
addAnimation(strokeWidthCallbackAnimation);
}
} else if (property == LottieProperty.TEXT_TRACKING) {
if (trackingCallbackAnimation != null) {
removeAnimation(trackingCallbackAnimation);
}
if (callback == null) {
trackingCallbackAnimation = null;
} else {
trackingCallbackAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback);
trackingCallbackAnimation.addUpdateListener(this);
addAnimation(trackingCallbackAnimation);
}
} else if (property == LottieProperty.TEXT_SIZE) {
if (textSizeCallbackAnimation != null) {
removeAnimation(textSizeCallbackAnimation);
}
if (callback == null) {
textSizeCallbackAnimation = null;
} else {
textSizeCallbackAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback);
textSizeCallbackAnimation.addUpdateListener(this);
addAnimation(textSizeCallbackAnimation);
}
} else if (property == LottieProperty.TYPEFACE) {
if (typefaceCallbackAnimation != null) {
removeAnimation(typefaceCallbackAnimation);
}
if (callback == null) {
typefaceCallbackAnimation = null;
} else {
typefaceCallbackAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Typeface>) callback);
typefaceCallbackAnimation.addUpdateListener(this);
addAnimation(typefaceCallbackAnimation);
}
} else if (property == LottieProperty.TEXT) {
textAnimation.setStringValueCallback((LottieValueCallback<String>) callback);
}
}
private static class TextSubLine {
private String text = "";
private float width = 0f;
void set(String text, float width) {
this.text = text;
this.width = width;
}
}
}
| 2,603 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/layer/SolidLayer.java | package com.airbnb.lottie.model.layer;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.LPaint;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation;
import com.airbnb.lottie.value.LottieValueCallback;
public class SolidLayer extends BaseLayer {
private final RectF rect = new RectF();
private final Paint paint = new LPaint();
private final float[] points = new float[8];
private final Path path = new Path();
private final Layer layerModel;
@Nullable private BaseKeyframeAnimation<ColorFilter, ColorFilter> colorFilterAnimation;
@Nullable private BaseKeyframeAnimation<Integer, Integer> colorAnimation;
SolidLayer(LottieDrawable lottieDrawable, Layer layerModel) {
super(lottieDrawable, layerModel);
this.layerModel = layerModel;
paint.setAlpha(0);
paint.setStyle(Paint.Style.FILL);
paint.setColor(layerModel.getSolidColor());
}
@Override public void drawLayer(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
int backgroundAlpha = Color.alpha(layerModel.getSolidColor());
if (backgroundAlpha == 0) {
return;
}
int opacity = transform.getOpacity() == null ? 100 : transform.getOpacity().getValue();
int alpha = (int) (parentAlpha / 255f * (backgroundAlpha / 255f * opacity / 100f) * 255);
paint.setAlpha(alpha);
if (colorAnimation != null) {
paint.setColor(colorAnimation.getValue());
}
if (colorFilterAnimation != null) {
paint.setColorFilter(colorFilterAnimation.getValue());
}
if (alpha > 0) {
points[0] = 0;
points[1] = 0;
points[2] = layerModel.getSolidWidth();
points[3] = 0;
points[4] = layerModel.getSolidWidth();
points[5] = layerModel.getSolidHeight();
points[6] = 0;
points[7] = layerModel.getSolidHeight();
// We can't map rect here because if there is rotation on the transform then we aren't
// actually drawing a rect.
parentMatrix.mapPoints(points);
path.reset();
path.moveTo(points[0], points[1]);
path.lineTo(points[2], points[3]);
path.lineTo(points[4], points[5]);
path.lineTo(points[6], points[7]);
path.lineTo(points[0], points[1]);
path.close();
canvas.drawPath(path, paint);
}
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
super.getBounds(outBounds, parentMatrix, applyParents);
rect.set(0, 0, layerModel.getSolidWidth(), layerModel.getSolidHeight());
boundsMatrix.mapRect(rect);
outBounds.set(rect);
}
@SuppressWarnings("unchecked")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
super.addValueCallback(property, callback);
if (property == LottieProperty.COLOR_FILTER) {
if (callback == null) {
colorFilterAnimation = null;
} else {
colorFilterAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<ColorFilter>) callback);
}
} else if (property == LottieProperty.COLOR) {
if (callback == null) {
colorAnimation = null;
paint.setColor(layerModel.getSolidColor());
} else {
colorAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Integer>) callback);
}
}
}
}
| 2,604 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/layer/NullLayer.java | package com.airbnb.lottie.model.layer;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import com.airbnb.lottie.LottieDrawable;
public class NullLayer extends BaseLayer {
NullLayer(LottieDrawable lottieDrawable, Layer layerModel) {
super(lottieDrawable, layerModel);
}
@Override void drawLayer(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
// Do nothing.
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
super.getBounds(outBounds, parentMatrix, applyParents);
outBounds.set(0, 0, 0, 0);
}
}
| 2,605 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/layer/ShapeLayer.java | package com.airbnb.lottie.model.layer;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.animation.content.Content;
import com.airbnb.lottie.animation.content.ContentGroup;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.content.BlurEffect;
import com.airbnb.lottie.model.content.ShapeGroup;
import com.airbnb.lottie.parser.DropShadowEffect;
import java.util.Collections;
import java.util.List;
public class ShapeLayer extends BaseLayer {
private final ContentGroup contentGroup;
private final CompositionLayer compositionLayer;
ShapeLayer(LottieDrawable lottieDrawable, Layer layerModel, CompositionLayer compositionLayer, LottieComposition composition) {
super(lottieDrawable, layerModel);
this.compositionLayer = compositionLayer;
// Naming this __container allows it to be ignored in KeyPath matching.
ShapeGroup shapeGroup = new ShapeGroup("__container", layerModel.getShapes(), false);
contentGroup = new ContentGroup(lottieDrawable, this, shapeGroup, composition);
contentGroup.setContents(Collections.<Content>emptyList(), Collections.<Content>emptyList());
}
@Override void drawLayer(@NonNull Canvas canvas, Matrix parentMatrix, int parentAlpha) {
contentGroup.draw(canvas, parentMatrix, parentAlpha);
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
super.getBounds(outBounds, parentMatrix, applyParents);
contentGroup.getBounds(outBounds, boundsMatrix, applyParents);
}
@Nullable @Override public BlurEffect getBlurEffect() {
BlurEffect layerBlur = super.getBlurEffect();
if (layerBlur != null) {
return layerBlur;
}
return compositionLayer.getBlurEffect();
}
@Nullable @Override public DropShadowEffect getDropShadowEffect() {
DropShadowEffect layerDropShadow = super.getDropShadowEffect();
if (layerDropShadow != null) {
return layerDropShadow;
}
return compositionLayer.getDropShadowEffect();
}
@Override
protected void resolveChildKeyPath(KeyPath keyPath, int depth, List<KeyPath> accumulator,
KeyPath currentPartialKeyPath) {
contentGroup.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath);
}
}
| 2,606 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/layer/package-info.java | @RestrictTo(LIBRARY)
package com.airbnb.lottie.model.layer;
import static androidx.annotation.RestrictTo.Scope.LIBRARY;
import androidx.annotation.RestrictTo; | 2,607 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/layer/Layer.java | package com.airbnb.lottie.model.layer;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.model.animatable.AnimatableFloatValue;
import com.airbnb.lottie.model.animatable.AnimatableTextFrame;
import com.airbnb.lottie.model.animatable.AnimatableTextProperties;
import com.airbnb.lottie.model.animatable.AnimatableTransform;
import com.airbnb.lottie.model.content.BlurEffect;
import com.airbnb.lottie.model.content.ContentModel;
import com.airbnb.lottie.model.content.Mask;
import com.airbnb.lottie.parser.DropShadowEffect;
import com.airbnb.lottie.value.Keyframe;
import java.util.List;
import java.util.Locale;
public class Layer {
public enum LayerType {
PRE_COMP,
SOLID,
IMAGE,
NULL,
SHAPE,
TEXT,
UNKNOWN
}
public enum MatteType {
NONE,
ADD,
INVERT,
LUMA,
LUMA_INVERTED,
UNKNOWN
}
private final List<ContentModel> shapes;
private final LottieComposition composition;
private final String layerName;
private final long layerId;
private final LayerType layerType;
private final long parentId;
@Nullable private final String refId;
private final List<Mask> masks;
private final AnimatableTransform transform;
private final int solidWidth;
private final int solidHeight;
private final int solidColor;
private final float timeStretch;
private final float startFrame;
private final float preCompWidth;
private final float preCompHeight;
@Nullable private final AnimatableTextFrame text;
@Nullable private final AnimatableTextProperties textProperties;
@Nullable private final AnimatableFloatValue timeRemapping;
private final List<Keyframe<Float>> inOutKeyframes;
private final MatteType matteType;
private final boolean hidden;
@Nullable private final BlurEffect blurEffect;
@Nullable private final DropShadowEffect dropShadowEffect;
public Layer(List<ContentModel> shapes, LottieComposition composition, String layerName, long layerId,
LayerType layerType, long parentId, @Nullable String refId, List<Mask> masks,
AnimatableTransform transform, int solidWidth, int solidHeight, int solidColor,
float timeStretch, float startFrame, float preCompWidth, float preCompHeight,
@Nullable AnimatableTextFrame text, @Nullable AnimatableTextProperties textProperties,
List<Keyframe<Float>> inOutKeyframes, MatteType matteType,
@Nullable AnimatableFloatValue timeRemapping, boolean hidden, @Nullable BlurEffect blurEffect,
@Nullable DropShadowEffect dropShadowEffect) {
this.shapes = shapes;
this.composition = composition;
this.layerName = layerName;
this.layerId = layerId;
this.layerType = layerType;
this.parentId = parentId;
this.refId = refId;
this.masks = masks;
this.transform = transform;
this.solidWidth = solidWidth;
this.solidHeight = solidHeight;
this.solidColor = solidColor;
this.timeStretch = timeStretch;
this.startFrame = startFrame;
this.preCompWidth = preCompWidth;
this.preCompHeight = preCompHeight;
this.text = text;
this.textProperties = textProperties;
this.inOutKeyframes = inOutKeyframes;
this.matteType = matteType;
this.timeRemapping = timeRemapping;
this.hidden = hidden;
this.blurEffect = blurEffect;
this.dropShadowEffect = dropShadowEffect;
}
LottieComposition getComposition() {
return composition;
}
float getTimeStretch() {
return timeStretch;
}
float getStartProgress() {
return startFrame / composition.getDurationFrames();
}
List<Keyframe<Float>> getInOutKeyframes() {
return inOutKeyframes;
}
public long getId() {
return layerId;
}
public String getName() {
return layerName;
}
public @Nullable String getRefId() {
return refId;
}
float getPreCompWidth() {
return preCompWidth;
}
float getPreCompHeight() {
return preCompHeight;
}
List<Mask> getMasks() {
return masks;
}
public LayerType getLayerType() {
return layerType;
}
MatteType getMatteType() {
return matteType;
}
long getParentId() {
return parentId;
}
List<ContentModel> getShapes() {
return shapes;
}
AnimatableTransform getTransform() {
return transform;
}
int getSolidColor() {
return solidColor;
}
int getSolidHeight() {
return solidHeight;
}
int getSolidWidth() {
return solidWidth;
}
@Nullable AnimatableTextFrame getText() {
return text;
}
@Nullable AnimatableTextProperties getTextProperties() {
return textProperties;
}
@Nullable AnimatableFloatValue getTimeRemapping() {
return timeRemapping;
}
@Override public String toString() {
return toString("");
}
public boolean isHidden() {
return hidden;
}
@Nullable public BlurEffect getBlurEffect() {
return blurEffect;
}
@Nullable public DropShadowEffect getDropShadowEffect() {
return dropShadowEffect;
}
public String toString(String prefix) {
StringBuilder sb = new StringBuilder();
sb.append(prefix).append(getName()).append("\n");
Layer parent = composition.layerModelForId(getParentId());
if (parent != null) {
sb.append("\t\tParents: ").append(parent.getName());
parent = composition.layerModelForId(parent.getParentId());
while (parent != null) {
sb.append("->").append(parent.getName());
parent = composition.layerModelForId(parent.getParentId());
}
sb.append(prefix).append("\n");
}
if (!getMasks().isEmpty()) {
sb.append(prefix).append("\tMasks: ").append(getMasks().size()).append("\n");
}
if (getSolidWidth() != 0 && getSolidHeight() != 0) {
sb.append(prefix).append("\tBackground: ").append(String
.format(Locale.US, "%dx%d %X\n", getSolidWidth(), getSolidHeight(), getSolidColor()));
}
if (!shapes.isEmpty()) {
sb.append(prefix).append("\tShapes:\n");
for (Object shape : shapes) {
sb.append(prefix).append("\t\t").append(shape).append("\n");
}
}
return sb.toString();
}
}
| 2,608 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/freemarker/ActivitiesCodeGenerator.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.freemarker;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.common.ProcessorConstants;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Activities;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class ActivitiesCodeGenerator {
private final String packageName;
private final String interfaceName;
private final Activities activities;
private final SourceFileCreator fileCreator;
private Configuration cfg;
private Map<String, Object> root;
public ActivitiesCodeGenerator(String packageName, String interfaceName, Activities activities,
SourceFileCreator fileCreator) {
this.packageName = packageName;
this.interfaceName = interfaceName;
this.activities = activities;
this.fileCreator = fileCreator;
}
private Configuration getConfiguration() {
if (cfg == null) {
cfg = new Configuration();
cfg.setClassForTemplateLoading(getClass(), "/");
cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
}
return cfg;
}
private Map<String, Object> getRoot() {
if (root == null) {
root = new HashMap<String, Object>();
root.put("packageName", packageName);
root.put("clientInterfaceName", getClientInterfaceName());
root.put("clientImplName", getClientImplName());
root.put("qualifiedTypeName", activities.getQualifiedName());
root.put("activities", activities);
}
return root;
}
private String getClientInterfaceName() {
return interfaceName + ProcessorConstants.CLIENT_INTERFACE_SUFFIX;
}
private String getClientImplName() {
return interfaceName + ProcessorConstants.CLIENT_IMPL_SUFFIX;
}
public void generateCode() {
generateActivitiesClientInterface();
generateActivitiesClientImpl();
}
private void generateActivitiesClientInterface() {
String clientInterfaceName = getClientInterfaceName();
generate(clientInterfaceName, "resources/templates/activitiesclient.ftl");
}
private void generateActivitiesClientImpl() {
String clientImplName = getClientImplName();
generate(clientImplName, "resources/templates/activitiesclientimpl.ftl");
}
private void generate(String className, String templateName) {
PrintWriter writer = fileCreator.createSourceFile(packageName, className);
try {
Template template = getConfiguration().getTemplate(templateName);
template.process(getRoot(), writer);
}
catch (IOException e) {
writer.println("Error loading template: " + templateName);
}
catch (TemplateException e) {
writer.println("Error processing template: " + templateName);
writer.println(e.getMessage());
}
writer.flush();
writer.close();
}
}
| 2,609 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/freemarker/WorkflowCodeGenerator.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.freemarker;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.common.ProcessorConstants;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Workflow;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class WorkflowCodeGenerator {
private final String packageName;
private final String interfaceName;
private final Workflow workflow;
private final SourceFileCreator fileCreator;
private Configuration cfg;
private Map<String, Object> root;
public WorkflowCodeGenerator(String packageName, String interfaceName, Workflow workflow,
SourceFileCreator fileCreator) {
this.packageName = packageName;
this.interfaceName = interfaceName;
this.workflow = workflow;
this.fileCreator = fileCreator;
}
private Configuration getConfiguration() {
if (cfg == null) {
cfg = new Configuration();
cfg.setClassForTemplateLoading(getClass(), "/");
cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
}
return cfg;
}
private Map<String, Object> getRoot() {
if (root == null) {
root = new HashMap<String, Object>();
root.put("packageName", packageName);
root.put("clientInterfaceName", getClientInterfaceName());
root.put("clientImplName", getClientImplName());
root.put("clientFactoryName", getClientFactoryName());
root.put("clientFactoryImplName", getClientFactoryImplName());
root.put("clientExternalInterfaceName", getClientExternalInterfaceName());
root.put("clientExternalImplName", getClientExternalImplName());
root.put("clientExternalFactoryName", getClientExternalFactoryName());
root.put("clientExternalFactoryImplName", getClientExternalFactoryImplName());
root.put("selfClientInterfaceName", getSelfClientInterfaceName());
root.put("selfClientImplName", getSelfClientImplName());
root.put("qualifiedTypeName", workflow.getQualifiedName());
root.put("workflow", workflow);
}
return root;
}
private String getClientInterfaceName() {
return interfaceName + ProcessorConstants.CLIENT_INTERFACE_SUFFIX;
}
private String getClientImplName() {
return interfaceName + ProcessorConstants.CLIENT_IMPL_SUFFIX;
}
private String getClientFactoryName() {
return interfaceName + ProcessorConstants.CLIENT_FACTORY_SUFFIX;
}
private String getClientFactoryImplName() {
return interfaceName + ProcessorConstants.CLIENT_FACTORY_IMPL_SUFFIX;
}
private String getClientExternalInterfaceName() {
return interfaceName + ProcessorConstants.CLIENT_EXTERNAL_INTERFACE_SUFFIX;
}
private String getClientExternalImplName() {
return interfaceName + ProcessorConstants.CLIENT_EXTERNAL_IMPL_SUFFIX;
}
private String getClientExternalFactoryName() {
return interfaceName + ProcessorConstants.CLIENT_EXTERNAL_FACTORY_SUFFIX;
}
private String getClientExternalFactoryImplName() {
return interfaceName + ProcessorConstants.CLIENT_EXTERNAL_FACTORY_IMPL_SUFFIX;
}
private String getSelfClientInterfaceName() {
return interfaceName + ProcessorConstants.SELF_CLIENT_INTERFACE_SUFFIX;
}
private String getSelfClientImplName() {
return interfaceName + ProcessorConstants.SELF_CLIENT_IMPL_SUFFIX;
}
public void generateCode() {
generateWorkflowClientInterface();
generateWorkflowClientImpl();
generateWorkflowClientFactory();
generateWorkflowClientFactoryImpl();
generateWorkflowClientExternalInterface();
generateWorkflowClientExternalImpl();
generateWorkflowClientExternalFactory();
generateWorkflowClientExternalFactoryImpl();
generateWorkflowSelfClientInterface();
generateWorkflowSelfClientImpl();
}
private void generateWorkflowClientInterface() {
String clientInterfaceName = getClientInterfaceName();
generate(clientInterfaceName, "resources/templates/workflowclient.ftl");
}
private void generateWorkflowClientImpl() {
String clientImplName = getClientImplName();
generate(clientImplName, "resources/templates/workflowclientimpl.ftl");
}
private void generateWorkflowClientFactory() {
String clientFactoryName = getClientFactoryName();
generate(clientFactoryName, "resources/templates/workflowclientfactory.ftl");
}
private void generateWorkflowClientFactoryImpl() {
String clientFactoryName = getClientFactoryImplName();
generate(clientFactoryName, "resources/templates/workflowclientfactoryimpl.ftl");
}
private void generateWorkflowClientExternalInterface() {
String clientInterfaceName = getClientExternalInterfaceName();
generate(clientInterfaceName, "resources/templates/workflowclientexternal.ftl");
}
private void generateWorkflowClientExternalImpl() {
String clientImplName = getClientExternalImplName();
generate(clientImplName, "resources/templates/workflowclientexternalimpl.ftl");
}
private void generateWorkflowClientExternalFactory() {
String clientFactoryName = getClientExternalFactoryName();
generate(clientFactoryName, "resources/templates/workflowclientexternalfactory.ftl");
}
private void generateWorkflowClientExternalFactoryImpl() {
String clientFactoryName = getClientExternalFactoryImplName();
generate(clientFactoryName, "resources/templates/workflowclientexternalfactoryimpl.ftl");
}
private void generateWorkflowSelfClientInterface() {
String clientInterfaceName = getSelfClientInterfaceName();
generate(clientInterfaceName, "resources/templates/workflowselfclient.ftl");
}
private void generateWorkflowSelfClientImpl() {
String clientImplName = getSelfClientImplName();
generate(clientImplName, "resources/templates/workflowselfclientimpl.ftl");
}
private void generate(String className, String templateName) {
PrintWriter writer = fileCreator.createSourceFile(packageName, className);
try {
Template template = getConfiguration().getTemplate(templateName);
template.process(getRoot(), writer);
}
catch (IOException e) {
writer.println("Error loading template: " + templateName);
}
catch (TemplateException e) {
writer.println("Error processing template: " + templateName);
writer.println(e.getMessage());
}
writer.flush();
writer.close();
}
}
| 2,610 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/freemarker/SourceFileCreator.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.freemarker;
import java.io.PrintWriter;
public interface SourceFileCreator {
PrintWriter createSourceFile(String packageName, String className);
}
| 2,611 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/common/SharedProcessorUtils.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.common;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Activities;
public final class SharedProcessorUtils {
public static Activities getParentActivities(Activities activities) {
for(Activities parent: activities.getSuperTypes()) {
String parentVersion = parent.getVersion();
if (parentVersion != null && !parentVersion.isEmpty()) {
return parent;
}
}
return null;
}
}
| 2,612 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/common/ProcessorConstants.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.common;
//import com.amazonaws.services.simpleworkflow.client.asynchrony.CurrentContext;
import com.amazonaws.services.simpleworkflow.flow.DataConverter;
import com.amazonaws.services.simpleworkflow.flow.JsonDataConverter;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activities;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activity;
import com.amazonaws.services.simpleworkflow.flow.annotations.Execute;
import com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetry;
import com.amazonaws.services.simpleworkflow.flow.annotations.GetState;
import com.amazonaws.services.simpleworkflow.flow.annotations.Signal;
import com.amazonaws.services.simpleworkflow.flow.annotations.Workflow;
public class ProcessorConstants {
public static final String CLIENT_INTERFACE_SUFFIX = "Client";
public static final String CLIENT_IMPL_SUFFIX = "ClientImpl";
public static final String CLIENT_FACTORY_SUFFIX = "ClientFactory";
public static final String CLIENT_FACTORY_IMPL_SUFFIX = "ClientFactoryImpl";
public static final String CLIENT_EXTERNAL_INTERFACE_SUFFIX = "ClientExternal";
public static final String CLIENT_EXTERNAL_IMPL_SUFFIX = "ClientExternalImpl";
public static final String CLIENT_EXTERNAL_FACTORY_SUFFIX = "ClientExternalFactory";
public static final String CLIENT_EXTERNAL_FACTORY_IMPL_SUFFIX = "ClientExternalFactoryImpl";
public static final String SELF_CLIENT_INTERFACE_SUFFIX = "SelfClient";
public static final String SELF_CLIENT_IMPL_SUFFIX = "SelfClientImpl";
public static final String WORKFLOW_ANNOTATION_TYPE_CLASS_NAME = Workflow.class.getName();
public static final String ACTIVITIES_ANNOTATION_TYPE_CLASS_NAME = Activities.class.getName();
public static final String EXPONENTIALRETRY_ANNOTATION = ExponentialRetry.class.getName();
public static final String EXECUTE_ANNOTATION = Execute.class.getName();
public static final String ACTIVITY_ANNOTATION = Activity.class.getName();
public static final String SIGNAL_ANNOTATION = Signal.class.getName();
public static final String GETSTATE_ANNOTATION = GetState.class.getName();
public static final String JAVA_LANG_OVERRIDE = Override.class.getName();
public static final Class<? extends DataConverter> DEFAULT_DATACONVERTER = JsonDataConverter.class;
}
| 2,613 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/common/PrimitiveTypeHelper.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.common;
import java.util.HashMap;
import java.util.Map;
public class PrimitiveTypeHelper {
private static final String[] primitiveTypes = { "boolean", "byte", "char", "short", "int", "long", "float", "double", "void" };
private static final String[] wrapperTypes = { "Boolean", "Byte", "Character",
"Short", "Integer", "Long", "Float", "Double", "Void" };
public static final String[] methods = { "booleanValue", "byteValue", "charValue", "shortValue", "intValue", "longValue",
"floatValue", "doubleValue" };
private static Map<String, String> primitiveToWrapper = new HashMap<String, String>();
private static Map<String, String> wrapperToPrimitive = new HashMap<String, String>();
private static Map<String, String> toPrimitiveMethods = new HashMap<String, String>();
static {
for (int i = 0; i < primitiveTypes.length; i++) {
primitiveToWrapper.put(primitiveTypes[i], wrapperTypes[i]);
wrapperToPrimitive.put(wrapperTypes[i], primitiveTypes[i]);
if (i < primitiveTypes.length - 1) {
toPrimitiveMethods.put(primitiveTypes[i], methods[i]);
}
}
}
public static String getWrapper(String primitive) {
String result = primitiveToWrapper.get(primitive);
if (result == null) {
throw new IllegalArgumentException(primitive);
}
return result;
}
public static String getPrimitive(String wrapper) {
String result = wrapperToPrimitive.get(wrapper);
if (result == null) {
throw new IllegalArgumentException(wrapper);
}
return result;
}
public static String getToPrimitiveMethod(String primitive) {
String result = toPrimitiveMethods.get(primitive);
if (result == null) {
throw new IllegalArgumentException(primitive);
}
return result;
}
}
| 2,614 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/objectmodel/MethodParameter.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.objectmodel;
public class MethodParameter {
private String parameterName;
private String parameterType;
private String parameterTypeUnboxed;
public MethodParameter() {
}
public MethodParameter(String parameterName, String parameterType) {
this.parameterName = parameterName;
this.parameterType = parameterType;
}
public String getParameterName() {
return parameterName;
}
public void setParameterName(String parameterName) {
this.parameterName = parameterName;
}
public MethodParameter withParameterName(String parameterName) {
this.parameterName = parameterName;
return this;
}
public String getParameterType() {
return parameterType;
}
public void setParameterType(String parameterType) {
this.parameterType = parameterType;
}
public MethodParameter withParameterType(String parameterType) {
this.parameterType = parameterType;
return this;
}
public String getParameterTypeUnboxed() {
return parameterTypeUnboxed;
}
public void setParameterTypeUnboxed(String parameterTypeUnboxed) {
this.parameterTypeUnboxed = parameterTypeUnboxed;
}
public MethodParameter withParameterTypeUnboxed(String parameterTypeUnboxed) {
this.parameterTypeUnboxed = parameterTypeUnboxed;
return this;
}
}
| 2,615 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/objectmodel/Activities.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.objectmodel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Activities extends TypeDefinition {
private List<ActivityMethod> activities;
public Activities(String prefix, String version, String dataConverter, String interfaceName, String qualifiedName) {
super(prefix, version, dataConverter, interfaceName, qualifiedName);
}
@SuppressWarnings("unchecked")
@Override
public List<? extends Activities> getSuperTypes() {
return (List<? extends Activities>)super.getSuperTypes();
}
public List<ActivityMethod> getActivities() {
if (activities == null) {
activities = new ArrayList<ActivityMethod>();
}
return activities;
}
public void setActivities(List<ActivityMethod> activities) {
List<ActivityMethod> activitiesCopy = new ArrayList<ActivityMethod>();
if (activities != null) {
activitiesCopy.addAll(activities);
}
this.activities = activitiesCopy;
}
public Activities withActivities(ActivityMethod... activities) {
for (ActivityMethod activity : activities) {
getActivities().add(activity);
}
return this;
}
public Activities withActivities(Collection<ActivityMethod> activities) {
List<ActivityMethod> activitiesCopy = new ArrayList<ActivityMethod>();
if (activities != null) {
activitiesCopy.addAll(activities);
}
this.activities = activitiesCopy;
return this;
}
}
| 2,616 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/objectmodel/Method.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.objectmodel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public abstract class Method {
private String methodName;
private String methodReturnType;
private String methodReturnTypeNoGenerics;
private String methodReturnTypeUnboxed;
private List<MethodParameter> methodParameters;
private String annotationsToCopy;
private List<String> thrownExceptions;
private boolean hasGenericReturnType;
private boolean primitiveReturnType;
public Method() {
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public Method withMethodName(String methodName) {
this.methodName = methodName;
return this;
}
public String getMethodReturnType() {
return methodReturnType;
}
public void setMethodReturnType(String methodReturnType) {
this.methodReturnType = methodReturnType;
}
public Method withMethodReturnType(String methodReturnType) {
this.methodReturnType = methodReturnType;
return this;
}
public String getMethodReturnTypeNoGenerics() {
return methodReturnTypeNoGenerics;
}
public void setMethodReturnTypeNoGenerics(String methodReturnTypeNoGenerics) {
this.methodReturnTypeNoGenerics = methodReturnTypeNoGenerics;
}
public String getMethodReturnTypeUnboxed() {
return methodReturnTypeUnboxed;
}
public void setMethodReturnTypeUnboxed(String methodReturnTypeUnboxed) {
this.methodReturnTypeUnboxed = methodReturnTypeUnboxed;
}
public Method withMethodReturnTypeUnboxed(String methodReturnTypeUnboxed) {
this.methodReturnTypeUnboxed = methodReturnTypeUnboxed;
return this;
}
public List<MethodParameter> getMethodParameters() {
if (methodParameters == null) {
methodParameters = new ArrayList<MethodParameter>();
}
return methodParameters;
}
public void setMethodParameters(List<MethodParameter> methodParameters) {
List<MethodParameter> methodParametersCopy = new ArrayList<MethodParameter>();
if (methodParameters != null) {
methodParametersCopy.addAll(methodParameters);
}
this.methodParameters = methodParametersCopy;
}
public Method withMethodParameters(MethodParameter... methodParameters) {
for (MethodParameter methodParameter : methodParameters) {
getMethodParameters().add(methodParameter);
}
return this;
}
public Method withMethodParameters(Collection<MethodParameter> methodParameters) {
List<MethodParameter> methodParametersCopy = new ArrayList<MethodParameter>();
if (methodParameters != null) {
methodParametersCopy.addAll(methodParameters);
}
this.methodParameters = methodParametersCopy;
return this;
}
public String getAnnotationsToCopy() {
return annotationsToCopy;
}
public void setAnnotationsToCopy(String annotationsToCopy) {
this.annotationsToCopy = annotationsToCopy;
}
public List<String> getThrownExceptions() {
if (thrownExceptions == null) {
thrownExceptions = new ArrayList<String>();
}
return thrownExceptions;
}
public void setThrownExceptions(List<String> thrownExceptions) {
List<String> thrownExceptionsCopy = new ArrayList<String>();
if (thrownExceptions != null) {
thrownExceptionsCopy.addAll(thrownExceptions);
}
this.thrownExceptions = thrownExceptionsCopy;
}
public Method withThrownExceptions(String... thrownExceptions) {
for (String thrownException : thrownExceptions) {
getThrownExceptions().add(thrownException);
}
return this;
}
public Method withThrownExceptions(Collection<String> thrownExceptions) {
List<String> thrownExceptionsCopy = new ArrayList<String>();
if (thrownExceptions != null) {
thrownExceptionsCopy.addAll(thrownExceptions);
}
this.thrownExceptions = thrownExceptionsCopy;
return this;
}
public boolean isHasGenericReturnType() {
return hasGenericReturnType;
}
public void setHasGenericReturnType(boolean hasGenericReturnType) {
this.hasGenericReturnType = hasGenericReturnType;
}
public Method withHasGenericReturnType(boolean hasGenericReturnType) {
this.hasGenericReturnType = hasGenericReturnType;
return this;
}
public boolean isPrimitiveReturnType() {
return primitiveReturnType;
}
public void setPrimitiveReturnType(boolean primitiveReturnType) {
this.primitiveReturnType = primitiveReturnType;
}
public Method withPrimitiveReturnType(boolean primitiveReturnType) {
this.primitiveReturnType = primitiveReturnType;
return this;
}
}
| 2,617 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/objectmodel/SignalMethod.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.objectmodel;
public class SignalMethod extends Method {
private final String signalName;
public SignalMethod(String signalName) {
this.signalName = signalName;
}
public String getSignalName() {
return signalName;
}
}
| 2,618 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/objectmodel/TypeDefinition.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.objectmodel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
public class TypeDefinition {
private final String prefix;
private final String version;
private final String dataConverter;
private final String interfaceName;
private final String qualifiedName;
private final String packageName;
private List<? extends TypeDefinition> superTypes;
public TypeDefinition(String prefix, String version, String dataConverter, String interfaceName,
String qualifiedName) {
this.prefix = prefix;
this.version = version;
this.dataConverter = dataConverter;
this.interfaceName = interfaceName;
this.qualifiedName = qualifiedName;
this.packageName = qualifiedName.substring(0, qualifiedName.length() - interfaceName.length() - 1);
}
public String getPrefix() {
return prefix;
}
public String getVersion() {
return version;
}
public String getDataConverter() {
return dataConverter;
}
public String getInterfaceName() {
return interfaceName;
}
public String getQualifiedName() {
return qualifiedName;
}
public String getPackageName() {
return packageName;
}
public List<? extends TypeDefinition> getSuperTypes() {
if (superTypes == null) {
superTypes = new ArrayList<TypeDefinition>();
}
return superTypes;
}
public void setSuperTypes(List<? extends TypeDefinition> superTypes) {
List<TypeDefinition> superTypesCopy = new ArrayList<TypeDefinition>();
if (superTypes != null) {
superTypesCopy.addAll(superTypes);
}
this.superTypes = superTypesCopy;
}
public Collection<? extends TypeDefinition> getAllSuperTypes() {
HashMap<String, TypeDefinition> allSuperTypesMap = new HashMap<String, TypeDefinition>();
for (TypeDefinition type: getSuperTypes()) {
for (TypeDefinition superType: type.getAllSuperTypes()) {
if (!allSuperTypesMap.containsKey(superType.getQualifiedName())) {
allSuperTypesMap.put(superType.getQualifiedName(), superType);
}
}
allSuperTypesMap.put(type.getQualifiedName(), type);
}
return allSuperTypesMap.values();
}
}
| 2,619 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/objectmodel/ActivityMethod.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.objectmodel;
public class ActivityMethod extends Method {
private final String activityName;
private final String activityVersion;
public ActivityMethod(String activityName, String activityVersion) {
this.activityName = activityName;
this.activityVersion = activityVersion;
}
public String getActivityName() {
return activityName;
}
public String getActivityVersion() {
return activityVersion;
}
}
| 2,620 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/objectmodel/GetStateMethod.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.objectmodel;
public class GetStateMethod extends Method {
public GetStateMethod() {
}
}
| 2,621 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/objectmodel/ExecuteMethod.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.objectmodel;
public class ExecuteMethod extends Method {
private final String workflowName;
private final String workflowVersion;
public ExecuteMethod(String workflowName, String workflowVersion) {
this.workflowName = workflowName;
this.workflowVersion = workflowVersion;
}
public String getWorkflowName() {
return workflowName;
}
public String getWorkflowVersion() {
return workflowVersion;
}
}
| 2,622 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/objectmodel/Workflow.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.objectmodel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Workflow extends TypeDefinition {
private ExecuteMethod executeMethod;
private GetStateMethod getStateMethod;
private List<SignalMethod> signals;
public Workflow(String prefix, String version, String dataConverter, String interfaceName, String qualifiedName) {
super(prefix, version, dataConverter, interfaceName, qualifiedName);
}
@SuppressWarnings("unchecked")
@Override
public List<? extends Workflow> getSuperTypes() {
return (List<? extends Workflow>)super.getSuperTypes();
}
public ExecuteMethod getExecuteMethod() {
return executeMethod;
}
public void setExecuteMethod(ExecuteMethod executeMethod) {
this.executeMethod = executeMethod;
}
public Workflow withExecuteMethod(ExecuteMethod executeMethod) {
this.executeMethod = executeMethod;
return this;
}
public GetStateMethod getGetStateMethod() {
return getStateMethod;
}
public void setGetStateMethod(GetStateMethod getStateMethod) {
this.getStateMethod = getStateMethod;
}
public Workflow withGetStateMethod(GetStateMethod getStateMethod) {
this.getStateMethod = getStateMethod;
return this;
}
public List<SignalMethod> getSignals() {
if (signals == null) {
signals = new ArrayList<SignalMethod>();
}
return signals;
}
public void setSignals(List<SignalMethod> signals) {
List<SignalMethod> signalsCopy = new ArrayList<SignalMethod>();
if (signals != null) {
signalsCopy.addAll(signals);
}
this.signals = signalsCopy;
}
public Workflow withSignals(SignalMethod... signals) {
for (SignalMethod signal : signals) {
getSignals().add(signal);
}
return this;
}
public Workflow withSignals(Collection<SignalMethod> signals) {
List<SignalMethod> signalsCopy = new ArrayList<SignalMethod>();
if (signals != null) {
signalsCopy.addAll(signals);
}
this.signals = signalsCopy;
return this;
}
}
| 2,623 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/annotationprocessor/ProcessorUtils.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.annotationprocessor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.SimpleAnnotationValueVisitor6;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.common.PrimitiveTypeHelper;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.common.ProcessorConstants;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activities;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activity;
import com.amazonaws.services.simpleworkflow.flow.annotations.Execute;
import com.amazonaws.services.simpleworkflow.flow.annotations.NullDataConverter;
import com.amazonaws.services.simpleworkflow.flow.annotations.Signal;
import com.amazonaws.services.simpleworkflow.flow.annotations.Workflow;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
final class ProcessorUtils {
private static final String JAVA_LANG_PREFIX = "java.lang.";
public static boolean isPrimitive(TypeMirror typeMirror) {
return typeMirror.getKind().isPrimitive();
}
public static boolean isVoidType(TypeMirror typeMirror) {
return typeMirror.getKind() == TypeKind.VOID;
}
public static boolean isJavaLangType(TypeMirror typeMirror) {
return isTypePackage(typeMirror, JAVA_LANG_PREFIX);
}
public static boolean isTypePackage(TypeMirror typeMirror, String packageName) {
if (typeMirror != null && !isVoidType(typeMirror)) {
String fullName = typeMirror.toString();
if (fullName.startsWith(packageName)) {
return !fullName.substring(packageName.length()).contains(".");
}
}
return false;
}
public static boolean isDeclaredType(TypeMirror typeMirror) {
return typeMirror.getKind() == TypeKind.DECLARED;
}
public static boolean isPromiseType(TypeMirror typeMirror) {
if (typeMirror != null && !isVoidType(typeMirror)) {
String fullName = typeMirror.toString();
if (fullName != null && !fullName.isEmpty()) {
return fullName.startsWith(Promise.class.getName());
}
}
return false;
}
public static boolean isGenericType(TypeMirror typeMirror) {
if (typeMirror != null && isDeclaredType(typeMirror)) {
DeclaredType declaredType = (DeclaredType) typeMirror;
return declaredType.getTypeArguments().size() > 0;
}
return false;
}
public static boolean isArrayType(TypeMirror typeMirror) {
return typeMirror.getKind() == TypeKind.ARRAY;
}
public static String getTypeName(TypeMirror typeMirror, String generatedTypePackageName) {
return getTypeName(typeMirror, false, 1, generatedTypePackageName);
}
public static String getTypeNameUnboxed(TypeMirror typeMirror, String generatedTypePackageName) {
return getTypeName(typeMirror, true, 1, generatedTypePackageName);
}
private static String getTypeName(TypeMirror typeMirror, boolean unboxed, int depth, String generatedTypePackageName) {
String typeName;
if (isPrimitive(typeMirror)) {
if (unboxed) {
typeName = typeMirror.toString();
} else {
typeName = PrimitiveTypeHelper.getWrapper(typeMirror.toString());
}
}
else if (isVoidType(typeMirror)) {
typeName = "Void";
}
else if (depth == 1 && isPromiseType(typeMirror)) {
DeclaredType pType = (DeclaredType) typeMirror;
List<? extends TypeMirror> typeArguments = pType.getTypeArguments();
if (typeArguments.size() == 0) {
typeName = "Void";
}
else {
typeName = getTypeName(typeArguments.iterator().next(), unboxed, depth + 1, generatedTypePackageName);
}
}
else if (isArrayType(typeMirror)) {
ArrayType aType = (ArrayType) typeMirror;
typeName = getTypeName(aType.getComponentType(), unboxed, depth + 1, generatedTypePackageName) + "[]";
}
else {
typeName = typeMirror.toString();
}
if (isJavaLangType(typeMirror)) {
typeName = typeMirror.toString().substring(JAVA_LANG_PREFIX.length());
}
if (isTypePackage(typeMirror, generatedTypePackageName)) {
typeName = typeMirror.toString().substring(generatedTypePackageName.length() + 1);
}
return typeName;
}
public static String getJustTypeName(TypeMirror typeMirror, String generatedTypePackageName) {
return getJustTypeName(typeMirror, 1, generatedTypePackageName);
}
private static String getJustTypeName(TypeMirror typeMirror, int depth, String generatedTypePackageName) {
String typeName;
if (isPrimitive(typeMirror)) {
typeName = PrimitiveTypeHelper.getWrapper(typeMirror.toString());
}
else if (depth == 1 && isPromiseType(typeMirror)) {
DeclaredType pType = (DeclaredType) typeMirror;
List<? extends TypeMirror> typeArguments = pType.getTypeArguments();
if (typeArguments.size() == 0) {
typeName = "Void";
}
else {
typeName = getJustTypeName(typeArguments.iterator().next(), depth + 1, generatedTypePackageName);
}
}
else if (isVoidType(typeMirror))
{
typeName = "Void";
}
else if (isArrayType(typeMirror)) {
ArrayType aType = (ArrayType) typeMirror;
typeName = getJustTypeName(aType.getComponentType(), depth + 1, generatedTypePackageName) + "[]";
}
else {
DeclaredType pType = (DeclaredType) typeMirror;
typeName = pType.asElement().toString();
}
if (typeMirror instanceof DeclaredType && isJavaLangType(typeMirror)) {
DeclaredType pType = (DeclaredType) typeMirror;
typeName = pType.asElement().toString().substring(JAVA_LANG_PREFIX.length());
}
if (typeMirror instanceof DeclaredType && isTypePackage(typeMirror, generatedTypePackageName)) {
DeclaredType pType = (DeclaredType) typeMirror;
typeName = pType.asElement().toString().substring(generatedTypePackageName.length() + 1);
}
return typeName;
}
public static DeclaredType getDeclaredType(ProcessingEnvironment processingEnv, String type) {
TypeElement typeElem = processingEnv.getElementUtils().getTypeElement(type);
if (typeElem != null) {
return processingEnv.getTypeUtils().getDeclaredType(typeElem);
}
return null;
}
/*
* public static boolean hasWaitAnnotation(ProcessingEnvironment
* processingEnv, VariableElement element) { return
* element.getAnnotation(Wait.class) != null; }
*
* public static boolean hasNoWaitAnnotation(ProcessingEnvironment
* processingEnv, VariableElement element) { return
* element.getAnnotation(NoWait.class) != null; }
*
* public static boolean isValue(ProcessingEnvironment processingEnv,
* VariableElement element) { return isTypeOf(processingEnv, element,
* "com.amazonaws.services.simpleworkflow.client.asynchrony.Promise"); }
*
* public static boolean isSettable(ProcessingEnvironment processingEnv,
* VariableElement element) { return isTypeOf(processingEnv, element,
* "com.amazonaws.services.simpleworkflow.client.asynchrony.Settable"); }
*
* public static boolean isCollection(ProcessingEnvironment processingEnv,
* VariableElement element) { return isTypeOf(processingEnv, element,
* "java.util.Collection"); }
*
* public static boolean isValueArray(ProcessingEnvironment processingEnv,
* VariableElement element) {
*
* if (element.asType().getKind() != TypeKind.ARRAY) { return false; }
* TypeMirror arrayComponentType = ((ArrayType)
* element.asType()).getComponentType(); TypeMirror parentType =
* processingEnv.getElementUtils().getTypeElement(
* "com.amazonaws.services.simpleworkflow.client.asynchrony.Promise"
* ).asType(); return
* processingEnv.getTypeUtils().isAssignable(arrayComponentType,
* parentType); }
*
* public static boolean isCollectionWaitParameter(ProcessingEnvironment
* processingEnv, VariableElement element) { return
* isValueArray(processingEnv, element) || isCollection(processingEnv,
* element); }
*
* public static boolean isTypeOf(ProcessingEnvironment processingEnv,
* VariableElement element, String typeOf) { Types types =
* processingEnv.getTypeUtils(); TypeMirror parentType =
* processingEnv.getElementUtils().getTypeElement(typeOf).asType(); return
* types.isAssignable(element.asType(), parentType); }
*
* public static boolean isWaitParameter(ProcessingEnvironment
* processingEnv, VariableElement parameter) { return
* (((isValue(processingEnv, parameter) && !isSettable(processingEnv,
* parameter)) || isCollectionWaitParameter(processingEnv, parameter)) &&
* !hasNoWaitAnnotation(processingEnv, parameter)); }
*/
public static String getActivitiesNamePrefix(TypeElement activitiesElement) {
if (activitiesElement == null) {
return "";
}
Activities annotation = activitiesElement.getAnnotation(Activities.class);
String activityPrefix = annotation.activityNamePrefix();
if (activityPrefix == null) {
activityPrefix = activitiesElement.getSimpleName().toString();
}
return activityPrefix;
}
public static String getActivitiesVersion(TypeElement activitiesElement) {
if (activitiesElement == null) return null;
Activities annotation = activitiesElement.getAnnotation(Activities.class);
if (annotation == null) return null;
return annotation.version();
}
public static String getParentActivitiesVersion(ProcessingEnvironment processingEnv, TypeElement activities) {
for (TypeMirror superInterfaceType : activities.getInterfaces()) {
Element superInterfaceDeclaration = processingEnv.getTypeUtils().asElement(superInterfaceType);
String parentVersion = getActivitiesVersion((TypeElement) superInterfaceDeclaration);
if (parentVersion != null && !parentVersion.isEmpty()) {
return parentVersion;
}
}
return null;
}
public static String getActivitiesDataConverter(ProcessingEnvironment env, TypeElement activitiesElement,
DeclaredType activitiesAnnotation) {
if (activitiesElement == null) {
return ProcessorConstants.DEFAULT_DATACONVERTER.getName();
}
AnnotationValue dataConverter = getAnnotationValueForClassAttribute(env, activitiesElement, activitiesAnnotation,
"dataConverter");
String dataConverterTypeName = dataConverter != null ? dataConverter.getValue().toString() : null;
if (dataConverterTypeName == null || dataConverterTypeName.equals(NullDataConverter.class.getName())) {
dataConverterTypeName = ProcessorConstants.DEFAULT_DATACONVERTER.getName();
}
return dataConverterTypeName;
}
public static String computeActivityName(String prefix, String interfaceName, ExecutableElement activity) {
assert(activity != null);
String activityName = null;
Activity activityAnnotation = activity.getAnnotation(Activity.class);
if (activityAnnotation != null && !activityAnnotation.name().isEmpty()) {
activityName = activityAnnotation.name();
}
else {
if (prefix == null || prefix.isEmpty()) {
activityName = interfaceName + "." + activity.getSimpleName().toString();
}
else {
activityName = prefix + activity.getSimpleName().toString();
}
}
return activityName;
}
public static String computeActivityVersion(String version,
ExecutableElement activity) {
Activity activityAnnotation = activity.getAnnotation(Activity.class);
if (activityAnnotation != null && !activityAnnotation.version().isEmpty()) {
version = activityAnnotation.version();
}
return version;
}
public static String getWorkflowDataConverter(ProcessingEnvironment env, TypeElement workflowElement,
DeclaredType workflowAnnotation) {
if (workflowElement == null) {
return ProcessorConstants.DEFAULT_DATACONVERTER.getName();
}
AnnotationValue dataConverter = getAnnotationValueForClassAttribute(env, workflowElement, workflowAnnotation,
"dataConverter");
String dataConverterTypeName = dataConverter != null ? dataConverter.getValue().toString() : null;
if (dataConverterTypeName == null || dataConverterTypeName.equals(NullDataConverter.class.getName())) {
dataConverterTypeName = ProcessorConstants.DEFAULT_DATACONVERTER.getName();
}
return dataConverterTypeName;
}
private static AnnotationValue getAnnotationValueForClassAttribute(ProcessingEnvironment env, TypeElement typeElement,
DeclaredType annotationType, String attribute) {
AnnotationValue elementValue = null;
for (AnnotationMirror mirror : typeElement.getAnnotationMirrors()) {
if (env.getTypeUtils().isSameType(mirror.getAnnotationType(), annotationType)) {
Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = mirror.getElementValues();
for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : elementValues.entrySet()) {
ExecutableElement elementKey = entry.getKey();
if (attribute.equals(elementKey.getSimpleName().toString())) {
elementValue = entry.getValue();
break;
}
}
}
}
return elementValue;
}
public static String computeWorkflowName(String interfaceName, ExecutableElement workflow) {
assert(workflow != null);
String workflowName = null;
Execute options = workflow.getAnnotation(Execute.class);
if (options != null && !options.name().isEmpty()) {
workflowName = options.name();
}
else {
workflowName = interfaceName + "." + workflow.getSimpleName().toString();
}
return workflowName;
}
public static String computeWorkflowVersion(ExecutableElement workflow) {
String version = "1.0"; // Default
Execute options = workflow.getAnnotation(Execute.class);
if (!options.version().isEmpty()) {
version = options.version();
}
return version;
}
public static String computeSignalName(ExecutableElement signal) {
String signalName = signal.getSimpleName().toString();
Signal signalOptions = signal.getAnnotation(Signal.class);
if (signalOptions != null && signalOptions.name() != null && !signalOptions.name().equals("")) {
signalName = signalOptions.name();
}
return signalName;
}
public static String getAnnotationsText(ProcessingEnvironment env, ExecutableElement method, Set<DeclaredType> annotationsToExcludeFromCopying) {
StringBuilder annotationsText = new StringBuilder();
for (AnnotationMirror mirror : method.getAnnotationMirrors()) {
boolean toInclude = true;
if (annotationsToExcludeFromCopying != null) {
for (DeclaredType toExclude : annotationsToExcludeFromCopying) {
if (env.getTypeUtils().isSameType(mirror.getAnnotationType(), toExclude)) {
toInclude = false;
break;
}
}
}
if (toInclude) {
StringBuilder annotationText = new StringBuilder();
ProcessorUtils.writeAnnotation(annotationText, mirror);
annotationsText.append(annotationText.toString());
}
}
return annotationsText.toString();
}
public static void writeAnnotation(StringBuilder builder, AnnotationMirror annotation) {
DeclaredType annotationDeclaration = annotation.getAnnotationType();
builder.append("@" + annotationDeclaration.asElement().toString() + "(");
boolean isFirst = true;
for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation.getElementValues().entrySet()) {
ExecutableElement elementKey = entry.getKey();
AnnotationValue elementValue = entry.getValue();
builder.append("\n");
if (isFirst) {
isFirst = false;
}
else {
builder.append(", ");
}
builder.append(elementKey.getSimpleName() + "=");
writeAnnotationValue(builder, elementValue);
}
builder.append(")\n");
}
@SuppressWarnings("unchecked")
public static void writeAnnotationValue(final StringBuilder builder, AnnotationValue annotationValue) {
SimpleAnnotationValueVisitor6<Void, Void> annotationValueWriter = new SimpleAnnotationValueVisitor6<Void, Void>() {
@Override
public Void visitString(String value, Void processingEnv) {
builder.append("\"");
builder.append(value);
builder.append("\"");
return null;
}
@Override
public Void visitAnnotation(AnnotationMirror value, Void processingEnv) {
writeAnnotation(builder, (AnnotationMirror) value);
return null;
}
@Override
public Void visitType(TypeMirror value, Void processingEnv) {
builder.append(value.toString());
builder.append(".class");
return null;
}
@Override
public Void visitEnumConstant(VariableElement value, Void processingEnv) {
String enumTypeName = value.asType().toString();
String simpleName = value.getSimpleName().toString();
builder.append(enumTypeName + "." + simpleName);
return null;
}
@Override
public Void visitArray(List<? extends AnnotationValue> value, Void processingEnv) {
builder.append("{ ");
boolean isFirst = true;
for (AnnotationValue val : (Collection<AnnotationValue>) value) {
if (isFirst) {
isFirst = false;
}
else {
builder.append(", ");
}
writeAnnotationValue(builder, val);
}
builder.append(" }");
return null;
}
@Override
protected Void defaultAction(Object value, Void processingEnv) {
builder.append(value.toString());
return null;
}
};
annotationValue.accept(annotationValueWriter, null);
}
public static com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Activities getActivitiesModel(
ProcessingEnvironment processingEnv, TypeElement activities, DeclaredType activitiesAnnotationType,
Set<DeclaredType> annotationsToExcludeFromCopying) {
ActivitiesDeclarationVisitor visitor = new ActivitiesDeclarationVisitor(processingEnv, (TypeElement) activities,
activitiesAnnotationType, annotationsToExcludeFromCopying);
visitor.scan(activities, processingEnv);
return visitor.getActivitiesDefinition();
}
public static com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Workflow getWorkflowModel(
ProcessingEnvironment processingEnv, TypeElement workflow, DeclaredType workflowAnnotationType,
Set<DeclaredType> annotationsToExcludeFromCopying) {
WorkflowTypeVisitor visitor = new WorkflowTypeVisitor(processingEnv, (TypeElement) workflow, workflowAnnotationType,
annotationsToExcludeFromCopying);
visitor.scan(workflow, processingEnv);
return visitor.getWorkflowDefinition();
}
public static List<com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Activities> getAllSuperActivities(
ProcessingEnvironment processingEnv, TypeElement activities, DeclaredType activitiesAnnotationType,
Set<DeclaredType> annotationsToExcludeFromCopying) {
List<com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Activities> superActivities = new ArrayList<com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Activities>();
for (TypeMirror superInterfaceType : activities.getInterfaces()) {
Element superInterfaceDeclaration = processingEnv.getTypeUtils().asElement(superInterfaceType);
Activities annotation = superInterfaceDeclaration != null ? superInterfaceDeclaration.getAnnotation(Activities.class) : null;
if (annotation != null) {
superActivities.add(getActivitiesModel(processingEnv, (TypeElement) superInterfaceDeclaration,
activitiesAnnotationType, annotationsToExcludeFromCopying));
}
}
return superActivities;
}
public static List<com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Workflow> getAllSuperWorkflows(
ProcessingEnvironment processingEnv, TypeElement workflow, DeclaredType workflowAnnotationType,
Set<DeclaredType> annotationsToExcludeFromCopying) {
List<com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Workflow> superWorkflows = new ArrayList<com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Workflow>();
for (TypeMirror superInterfaceType : workflow.getInterfaces()) {
Element superInterfaceDeclaration = processingEnv.getTypeUtils().asElement(superInterfaceType);
Workflow annotation = superInterfaceDeclaration != null ? superInterfaceDeclaration.getAnnotation(Workflow.class) : null;
if (annotation != null) {
superWorkflows.add(getWorkflowModel(processingEnv, (TypeElement) superInterfaceDeclaration,
workflowAnnotationType, annotationsToExcludeFromCopying));
}
}
return superWorkflows;
}
}
| 2,624 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/annotationprocessor/WorkflowTypeVisitor.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.annotationprocessor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementScanner6;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.ExecuteMethod;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.GetStateMethod;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Method;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.MethodParameter;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.SignalMethod;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Workflow;
import com.amazonaws.services.simpleworkflow.flow.annotations.Execute;
import com.amazonaws.services.simpleworkflow.flow.annotations.GetState;
import com.amazonaws.services.simpleworkflow.flow.annotations.Signal;
public class WorkflowTypeVisitor extends ElementScanner6<Void, ProcessingEnvironment> {
private Workflow workflowDefinition;
private Set<DeclaredType> annotationsToExcludeFromCopying;
public WorkflowTypeVisitor(ProcessingEnvironment processingEnv, TypeElement workflow, DeclaredType workflowAnnotationType,
Set<DeclaredType> annotationsToExcludeFromCopying) {
this.annotationsToExcludeFromCopying = annotationsToExcludeFromCopying;
String dataConverter = ProcessorUtils.getWorkflowDataConverter(processingEnv, workflow, workflowAnnotationType);
String interfaceName = workflow.getSimpleName().toString();
String qualifiedName = workflow.toString();
this.workflowDefinition = new Workflow(null, null, dataConverter, interfaceName, qualifiedName);
List<Workflow> superTypes = ProcessorUtils.getAllSuperWorkflows(processingEnv, workflow, workflowAnnotationType,
annotationsToExcludeFromCopying);
this.workflowDefinition.setSuperTypes(superTypes);
}
@Override
public Void visitExecutable(ExecutableElement method, ProcessingEnvironment env) {
if (method.getAnnotation(Execute.class) != null) {
String workflowName = ProcessorUtils.computeWorkflowName(
workflowDefinition.getInterfaceName(), method);
String workflowVersion = ProcessorUtils.computeWorkflowVersion(method);
ExecuteMethod executeMethod = new ExecuteMethod(workflowName, workflowVersion);
setMethodInfo(method, executeMethod, workflowDefinition.getPackageName());
executeMethod.setAnnotationsToCopy(ProcessorUtils.getAnnotationsText(env, method, annotationsToExcludeFromCopying));
workflowDefinition.setExecuteMethod(executeMethod);
}
else if (method.getAnnotation(Signal.class) != null) {
String signalName = ProcessorUtils.computeSignalName(method);
SignalMethod signalMethod = new SignalMethod(signalName);
setMethodInfo(method, signalMethod, workflowDefinition.getPackageName());
workflowDefinition.getSignals().add(signalMethod);
}
else if (method.getAnnotation(GetState.class) != null) {
GetStateMethod getStateMethod = new GetStateMethod();
setMethodInfo(method, getStateMethod, workflowDefinition.getPackageName());
workflowDefinition.setGetStateMethod(getStateMethod);
}
return super.visitExecutable(method, env);
}
public Workflow getWorkflowDefinition() {
return workflowDefinition;
}
private void setMethodInfo(ExecutableElement methodDeclaration, Method method, String generatedTypePackageName) {
method.setMethodName(methodDeclaration.getSimpleName().toString());
TypeMirror returnType = methodDeclaration.getReturnType();
method.setMethodReturnType(ProcessorUtils.getTypeName(returnType, generatedTypePackageName));
method.setMethodReturnTypeNoGenerics(ProcessorUtils.getJustTypeName(returnType, generatedTypePackageName));
method.setMethodReturnTypeUnboxed(ProcessorUtils.getTypeNameUnboxed(returnType, generatedTypePackageName));
method.setHasGenericReturnType(ProcessorUtils.isGenericType(returnType));
method.setPrimitiveReturnType(ProcessorUtils.isPrimitive(returnType));
List<? extends VariableElement> parameters = methodDeclaration.getParameters();
for (VariableElement parameter: parameters)
{
TypeMirror paramterType = parameter.asType();
String parameterTypeName = ProcessorUtils.getTypeName(paramterType, generatedTypePackageName);
String parameterName = parameter.toString();
MethodParameter methodParam = new MethodParameter(parameterName, parameterTypeName);
methodParam.setParameterTypeUnboxed(ProcessorUtils.getTypeNameUnboxed(paramterType, generatedTypePackageName));
method.getMethodParameters().add(methodParam);
}
List<String> thrownTypes = new ArrayList<String>();
for (TypeMirror thrownExceptionType: methodDeclaration.getThrownTypes()) {
thrownTypes.add(thrownExceptionType.toString());
}
method.setThrownExceptions(thrownTypes);
}
}
| 2,625 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/annotationprocessor/WorkflowValidator.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.annotationprocessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementScanner6;
import javax.tools.Diagnostic.Kind;
import com.amazonaws.services.simpleworkflow.flow.annotations.Execute;
import com.amazonaws.services.simpleworkflow.flow.annotations.GetState;
import com.amazonaws.services.simpleworkflow.flow.annotations.Signal;
import com.amazonaws.services.simpleworkflow.flow.annotations.Workflow;
public class WorkflowValidator extends ElementScanner6<Boolean, ProcessingEnvironment> {
private boolean hasErrors = false;
private boolean hasExecute = false;
private boolean hasGetState = false;
public boolean isHasErrors() {
return hasErrors;
}
public boolean isHasExecute() {
return hasExecute;
}
public boolean isHasGetState() {
return hasGetState;
}
@Override
public Boolean visitType(TypeElement e, ProcessingEnvironment p) {
if (e.getAnnotation(Workflow.class) != null) {
if (e.getKind().isClass()) {
reportError(p, "@Workflow can only be used on an interface.", e);
}
if (e.getNestingKind().isNested()) {
reportError(p, "@Workflow not allowed on inner or nested types.", e);
}
}
return super.visitType(e, p);
}
@Override
public Boolean visitExecutable(ExecutableElement e, ProcessingEnvironment p) {
int annotationCount = 0;
if (e.getAnnotation(Execute.class) != null) {
if (hasExecute) {
reportError(p, "Only one method allowed with @Execute annotation.", e);
} else {
hasExecute = true;
}
annotationCount++;
TypeMirror returnType = e.getReturnType();
if (!(ProcessorUtils.isVoidType(returnType) || ProcessorUtils.isPromiseType(returnType))) {
reportError(p, "Method with @Execute annotations is only allowed to have void or Promise as return types.", e);
}
}
if (e.getAnnotation(Signal.class) != null) {
if (!ProcessorUtils.isVoidType(e.getReturnType())) {
reportError(p, "Signal method cannot have a return type.", e);
}
annotationCount++;
}
if (e.getAnnotation(GetState.class) != null) {
if (hasGetState) {
reportError(p, "Only one method allowed with @GetState annotation.", e);
}
else {
hasGetState = true;
}
TypeMirror returnType = e.getReturnType();
if (ProcessorUtils.isVoidType(returnType)) {
reportError(p, "GetState method cannot have void as return type.", e);
} else if (ProcessorUtils.isPromiseType(returnType)) {
reportError(p, "GetState method cannot have Promise as return type.", e);
}
annotationCount++;
}
if (annotationCount > 1) {
reportError(p, "Annotations @Execute, @Signal and @GetState are exclusive.", e);
}
for (VariableElement parameter: e.getParameters()) {
TypeMirror parameterType = parameter.asType();
if (ProcessorUtils.isPromiseType(parameterType)) {
reportError(p, "@Workflow methods are not allowed to have Promise parameter types.", parameter);
}
}
return super.visitExecutable(e, p);
}
private void reportError(ProcessingEnvironment environment, String message, Element element) {
hasErrors = true;
environment.getMessager().printMessage(Kind.ERROR, message, element);
}
}
| 2,626 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/annotationprocessor/ActivitiesValidator.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.annotationprocessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementScanner6;
import javax.tools.Diagnostic.Kind;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activities;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activity;
public class ActivitiesValidator extends ElementScanner6<Boolean, ProcessingEnvironment> {
private boolean hasErrors = false;
private String version;
private String parentVersion;
public boolean isHasErrors() {
return hasErrors;
}
@Override
public Boolean visitType(TypeElement e, ProcessingEnvironment p) {
if (e.getAnnotation(Activities.class) != null) {
if (e.getKind().isClass()) {
reportError(p, "@Activities can only be used on an interface.", e);
}
if (e.getNestingKind().isNested()) {
reportError(p, "@Activities not allowed on inner or nested types.", e);
}
version = ProcessorUtils.getActivitiesVersion(e);
parentVersion = ProcessorUtils.getParentActivitiesVersion(p, e);
}
return super.visitType(e, p);
}
@Override
public Boolean visitExecutable(ExecutableElement e, ProcessingEnvironment p) {
TypeMirror returnType = e.getReturnType();
if (!ProcessorUtils.isVoidType(returnType) && ProcessorUtils.isPromiseType(returnType)) {
reportError(p, "Activity methods are not allowed to have Promise return type.", e);
}
for (VariableElement parameter: e.getParameters()) {
TypeMirror parameterType = parameter.asType();
if (ProcessorUtils.isPromiseType(parameterType)) {
reportError(p, "Activity methods are not allowed to have Promise parameter type.", parameter);
}
}
if ((version == null || version.isEmpty()) && (parentVersion == null || parentVersion.isEmpty())) {
Activity activityAnnotation = e.getAnnotation(Activity.class);
if (activityAnnotation == null || activityAnnotation.name().isEmpty()) {
reportError(p, "Activity version not specified.", e);
}
}
return super.visitExecutable(e, p);
}
private void reportError(ProcessingEnvironment environment, String message, Element element) {
hasErrors = true;
environment.getMessager().printMessage(Kind.ERROR, message, element);
}
}
| 2,627 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/annotationprocessor/ActivitiesDeclarationVisitor.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.annotationprocessor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementScanner6;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.common.SharedProcessorUtils;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Activities;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.ActivityMethod;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Method;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.MethodParameter;
public class ActivitiesDeclarationVisitor extends ElementScanner6<Void, ProcessingEnvironment> {
private Set<DeclaredType> annotationsToExcludeFromCopying;
private final Activities activitiesDefinition;
private Activities parentActivities;
public ActivitiesDeclarationVisitor(ProcessingEnvironment processingEnv, TypeElement activities, DeclaredType activitiesAnnotationType,
Set<DeclaredType> annotationsToExcludeFromCopying) {
this.annotationsToExcludeFromCopying = annotationsToExcludeFromCopying;
String prefix = ProcessorUtils.getActivitiesNamePrefix(activities);
String version = ProcessorUtils.getActivitiesVersion(activities);
String dataConverter = ProcessorUtils.getActivitiesDataConverter(processingEnv, activities, activitiesAnnotationType);
String interfaceName = activities.getSimpleName().toString();
String qualifiedName = activities.toString();
this.activitiesDefinition = new Activities(prefix, version, dataConverter, interfaceName, qualifiedName);
List<Activities> superTypes = ProcessorUtils.getAllSuperActivities(processingEnv, activities, activitiesAnnotationType,
annotationsToExcludeFromCopying);
this.activitiesDefinition.setSuperTypes(superTypes);
this.parentActivities = SharedProcessorUtils.getParentActivities(activitiesDefinition);
}
public Activities getActivitiesDefinition() {
return activitiesDefinition;
}
@Override
public Void visitExecutable(ExecutableElement method, ProcessingEnvironment env) {
String prefix = activitiesDefinition.getPrefix();
String version = activitiesDefinition.getVersion();
if (parentActivities != null) {
if (prefix == null || prefix.isEmpty()) {
prefix = parentActivities.getPrefix();
}
if (version == null || version.isEmpty()) {
version = parentActivities.getVersion();
}
}
String activityName = ProcessorUtils.computeActivityName(
prefix, activitiesDefinition.getInterfaceName(), method);
String activityVersion = ProcessorUtils.computeActivityVersion(version,
method);
ActivityMethod activity = new ActivityMethod(activityName, activityVersion);
setMethodInfo(method, activity, activitiesDefinition.getPackageName());
activity.setAnnotationsToCopy(ProcessorUtils.getAnnotationsText(env, method, annotationsToExcludeFromCopying));
activitiesDefinition.getActivities().add(activity);
return super.visitExecutable(method, env);
}
private void setMethodInfo(ExecutableElement methodDeclaration, Method method, String generatedTypePackageName) {
method.setMethodName(methodDeclaration.getSimpleName().toString());
TypeMirror returnType = methodDeclaration.getReturnType();
method.setMethodReturnType(ProcessorUtils.getTypeName(returnType, generatedTypePackageName));
method.setMethodReturnTypeNoGenerics(ProcessorUtils.getJustTypeName(returnType, generatedTypePackageName));
method.setMethodReturnTypeUnboxed(ProcessorUtils.getTypeNameUnboxed(returnType, generatedTypePackageName));
method.setHasGenericReturnType(ProcessorUtils.isGenericType(returnType));
method.setPrimitiveReturnType(ProcessorUtils.isPrimitive(returnType));
List<? extends VariableElement> parameters = methodDeclaration.getParameters();
for (VariableElement parameter: parameters)
{
TypeMirror paramterType = parameter.asType();
String parameterTypeName = ProcessorUtils.getTypeName(paramterType, generatedTypePackageName);
String parameterName = parameter.toString();
MethodParameter methodParam = new MethodParameter(parameterName, parameterTypeName);
methodParam.setParameterTypeUnboxed(ProcessorUtils.getTypeNameUnboxed(paramterType, generatedTypePackageName));
method.getMethodParameters().add(methodParam);
}
List<String> thrownTypes = new ArrayList<String>();
for (TypeMirror thrownExceptionType: methodDeclaration.getThrownTypes()) {
thrownTypes.add(thrownExceptionType.toString());
}
method.setThrownExceptions(thrownTypes);
}
}
| 2,628 |
0 | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony | Create_ds/aws-swf-build-tools/src/main/java/com/amazonaws/eclipse/simpleworkflow/asynchrony/annotationprocessor/AsynchronyDeciderAnnotationProcessor.java | /*
* Copyright 2012 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.eclipse.simpleworkflow.asynchrony.annotationprocessor;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.tools.Diagnostic.Kind;
import javax.tools.JavaFileObject;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.common.ProcessorConstants;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.freemarker.ActivitiesCodeGenerator;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.freemarker.SourceFileCreator;
import com.amazonaws.eclipse.simpleworkflow.asynchrony.freemarker.WorkflowCodeGenerator;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activities;
import com.amazonaws.services.simpleworkflow.flow.annotations.Workflow;
@SupportedAnnotationTypes({ "com.amazonaws.services.simpleworkflow.flow.annotations.Activities",
"com.amazonaws.services.simpleworkflow.flow.annotations.Workflow" })
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class AsynchronyDeciderAnnotationProcessor extends AbstractProcessor {
private Set<DeclaredType> annotationsToExcludeFromCopying;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!roundEnv.processingOver()) {
processingEnv.getMessager().printMessage(Kind.NOTE, "AsynchronyDeciderAnnotationProcessor.process() invoked.");
this.annotationsToExcludeFromCopying = new HashSet<DeclaredType>();
this.annotationsToExcludeFromCopying.add(ProcessorUtils.getDeclaredType(processingEnv,
ProcessorConstants.EXECUTE_ANNOTATION));
this.annotationsToExcludeFromCopying.add(ProcessorUtils.getDeclaredType(processingEnv,
ProcessorConstants.ACTIVITY_ANNOTATION));
this.annotationsToExcludeFromCopying.add(ProcessorUtils.getDeclaredType(processingEnv,
ProcessorConstants.SIGNAL_ANNOTATION));
this.annotationsToExcludeFromCopying.add(ProcessorUtils.getDeclaredType(processingEnv,
ProcessorConstants.GETSTATE_ANNOTATION));
this.annotationsToExcludeFromCopying.add(ProcessorUtils.getDeclaredType(processingEnv,
ProcessorConstants.JAVA_LANG_OVERRIDE));
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(Activities.class);
for (Element annotatedElement : annotatedElements) {
ActivitiesValidator activitiesValidator = new ActivitiesValidator();
activitiesValidator.scan(annotatedElement, processingEnv);
if (!activitiesValidator.isHasErrors() && annotatedElement instanceof TypeElement) {
processingEnv.getMessager().printMessage(Kind.NOTE,
"Processing @Activities for " + annotatedElement.getSimpleName());
processActivities(annotatedElement);
}
}
annotatedElements = roundEnv.getElementsAnnotatedWith(Workflow.class);
for (Element annotatedElement : annotatedElements) {
WorkflowValidator workflowValidator = new WorkflowValidator();
workflowValidator.scan(annotatedElement, processingEnv);
if (!workflowValidator.isHasErrors() && annotatedElement instanceof TypeElement) {
processingEnv.getMessager().printMessage(Kind.NOTE,
"Processing @Workflow for " + annotatedElement.getSimpleName());
processWorkflow(roundEnv, annotatedElement);
}
}
}
else {
processingEnv.getMessager().printMessage(Kind.NOTE, "Processing finished");
}
return false;
}
private void processActivities(final Element activities) {
DeclaredType activitiesAnnotationType = ProcessorUtils.getDeclaredType(processingEnv,
ProcessorConstants.ACTIVITIES_ANNOTATION_TYPE_CLASS_NAME);
com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Activities activitiesDefinition = ProcessorUtils.getActivitiesModel(
processingEnv, (TypeElement) activities, activitiesAnnotationType, annotationsToExcludeFromCopying);
String packageName = processingEnv.getElementUtils().getPackageOf(activities).getQualifiedName().toString();
SourceFileCreator fileCreator = new SourceFileCreator() {
//@Override
public PrintWriter createSourceFile(String packageName, String className) {
OutputStream fileStream = null;
try {
JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(packageName + "." + className,
activities);
fileStream = sourceFile.openOutputStream();
}
catch (IOException e) {
processingEnv.getMessager().printMessage(Kind.ERROR,
"Unable to generate target class for element [reason: " + e.toString() + "]", activities);
}
if (fileStream != null)
return new PrintWriter(fileStream);
return null;
}
};
ActivitiesCodeGenerator codeGenerator = new ActivitiesCodeGenerator(packageName, activities.getSimpleName().toString(),
activitiesDefinition, fileCreator);
codeGenerator.generateCode();
}
private void processWorkflow(RoundEnvironment roundEnv, final Element workflow) {
DeclaredType workflowAnnotationType = ProcessorUtils.getDeclaredType(processingEnv,
ProcessorConstants.WORKFLOW_ANNOTATION_TYPE_CLASS_NAME);
com.amazonaws.eclipse.simpleworkflow.asynchrony.objectmodel.Workflow workflowDefinition = ProcessorUtils.getWorkflowModel(
processingEnv, (TypeElement) workflow, workflowAnnotationType, annotationsToExcludeFromCopying);
String packageName = processingEnv.getElementUtils().getPackageOf(workflow).getQualifiedName().toString();
SourceFileCreator fileCreator = new SourceFileCreator() {
//@Override
public PrintWriter createSourceFile(String packageName, String className) {
OutputStream fileStream = null;
try {
JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(packageName + "." + className, workflow);
fileStream = sourceFile.openOutputStream();
}
catch (IOException e) {
processingEnv.getMessager().printMessage(Kind.ERROR,
"Unable to generate" + " target class for elmenet [reason: " + e.toString() + "]", workflow);
}
if (fileStream != null)
return new PrintWriter(fileStream);
return null;
}
};
WorkflowCodeGenerator workflowCodeGenerator = new WorkflowCodeGenerator(packageName, workflow.getSimpleName().toString(),
workflowDefinition, fileCreator);
workflowCodeGenerator.generateCode();
}
}
| 2,629 |
0 | Create_ds/okreplay/okreplay-sample/src/androidTest/java/okreplay | Create_ds/okreplay/okreplay-sample/src/androidTest/java/okreplay/sample/ExampleInstrumentedFooTest.java | package okreplay.sample;
import com.jakewharton.espresso.OkHttp3IdlingResource;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.espresso.IdlingResource;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import okreplay.AndroidTapeRoot;
import okreplay.AssetManager;
import okreplay.MatchRules;
import okreplay.OkReplay;
import okreplay.OkReplayConfig;
import okreplay.OkReplayRuleChain;
import okreplay.TapeMode;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedFooTest {
private final DependencyGraph graph = DependencyGraph.Companion.instance();
private final ActivityTestRule<MainActivity> activityTestRule =
new ActivityTestRule<>(MainActivity.class);
private final AssetManager assetManager =
new AssetManager(InstrumentationRegistry.getInstrumentation().getTargetContext());
private final OkReplayConfig configuration = new OkReplayConfig.Builder()
.tapeRoot(new AndroidTapeRoot(assetManager, getClass().getSimpleName()))
.defaultMode(TapeMode.READ_WRITE)
.sslEnabled(true)
.interceptor(graph.getOkReplayInterceptor())
.defaultMatchRules(MatchRules.host, MatchRules.path, MatchRules.method)
.build();
@Rule
public final TestRule testRule =
new OkReplayRuleChain(configuration, activityTestRule).get();
private final IdlingResource okHttp3IdlingResource =
OkHttp3IdlingResource.create("OkHttp", graph.getOkHttpClient());
@Before
public void setUp() {
IdlingRegistry.getInstance().register(okHttp3IdlingResource);
}
@After
public void tearDown() {
IdlingRegistry.getInstance().register(okHttp3IdlingResource);
}
@Test
@OkReplay
public void foo() {
assertEquals("okreplay.sample", ApplicationProvider.getApplicationContext().getPackageName());
onView(withId(R.id.navigation_repositories)).perform(click());
onView(withId(R.id.message)).check(matches(withText(containsString("6502Android"))));
}
}
| 2,630 |
0 | Create_ds/okreplay/okreplay-sample/src/androidTest/java/okreplay | Create_ds/okreplay/okreplay-sample/src/androidTest/java/okreplay/sample/ExampleInstrumentedBarTest.java | package okreplay.sample;
import com.jakewharton.espresso.OkHttp3IdlingResource;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.espresso.IdlingResource;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import okreplay.AndroidTapeRoot;
import okreplay.MatchRules;
import okreplay.OkReplay;
import okreplay.OkReplayConfig;
import okreplay.OkReplayRuleChain;
import okreplay.TapeMode;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.CoreMatchers.containsString;
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedBarTest {
private final DependencyGraph graph = DependencyGraph.Companion.instance();
private final ActivityTestRule<MainActivity> activityTestRule =
new ActivityTestRule<>(MainActivity.class);
private final OkReplayConfig configuration = new OkReplayConfig.Builder()
.tapeRoot(new AndroidTapeRoot(InstrumentationRegistry.getInstrumentation().getTargetContext(), getClass()))
.defaultMode(TapeMode.READ_WRITE)
.sslEnabled(true)
.interceptor(graph.getOkReplayInterceptor())
.defaultMatchRules(MatchRules.host, MatchRules.path, MatchRules.method)
.build();
@Rule
public final TestRule testRule =
new OkReplayRuleChain(configuration, activityTestRule).get();
private final IdlingResource okHttp3IdlingResource =
OkHttp3IdlingResource.create("OkHttp", graph.getOkHttpClient());
@Before
public void setUp() {
IdlingRegistry.getInstance().register(okHttp3IdlingResource);
}
@After
public void tearDown() {
IdlingRegistry.getInstance().register(okHttp3IdlingResource);
}
@Test
@OkReplay
public void bar() {
onView(withId(R.id.navigation_repositories)).perform(click());
onView(withId(R.id.message)).check(matches(withText(containsString("AbsListViewHelper"))));
}
}
| 2,631 |
0 | Create_ds/okreplay/okreplay-sample/src/main/java/okreplay | Create_ds/okreplay/okreplay-sample/src/main/java/okreplay/sample/OkReplayAdapterFactory.java | package okreplay.sample;
import com.ryanharter.auto.value.moshi.MoshiAdapterFactory;
import com.squareup.moshi.JsonAdapter;
@MoshiAdapterFactory
public abstract class OkReplayAdapterFactory implements JsonAdapter.Factory {
public static JsonAdapter.Factory create() {
return new AutoValueMoshi_OkReplayAdapterFactory();
}
}
| 2,632 |
0 | Create_ds/okreplay/okreplay-sample/src/main/java/okreplay | Create_ds/okreplay/okreplay-sample/src/main/java/okreplay/sample/Repository.java | package okreplay.sample;
import androidx.annotation.Nullable;
import com.google.auto.value.AutoValue;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
@AutoValue abstract class Repository {
abstract String name();
@Nullable abstract String description();
public static JsonAdapter<Repository> jsonAdapter(Moshi moshi) {
return new AutoValue_Repository.MoshiJsonAdapter(moshi);
}
}
| 2,633 |
0 | Create_ds/okreplay/okreplay-tests/src/test/java | Create_ds/okreplay/okreplay-tests/src/test/java/okreplay/ClassAnnotatedTapeNameTest.java | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okreplay;
import com.google.common.io.Files;
import org.codehaus.groovy.runtime.ResourceGroovyMethods;
import org.junit.AfterClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.File;
import spock.lang.Issue;
@Issue("https://github.com/robfletcher/betamax/issues/36")
@OkReplay
public class ClassAnnotatedTapeNameTest {
private static final File TAPE_ROOT = Files.createTempDir();
private static final OkReplayConfig configuration = new OkReplayConfig.Builder()
.tapeRoot(TAPE_ROOT)
.interceptor(new OkReplayInterceptor())
.build();
@ClassRule public static RecorderRule recorder = new RecorderRule(configuration);
@AfterClass public static void deleteTempDir() {
ResourceGroovyMethods.deleteDir(TAPE_ROOT);
}
@Test public void tapeNameDefaultsToClassName() {
assert recorder.getTape().getName().equals("class annotated tape name test");
}
}
| 2,634 |
0 | Create_ds/okreplay/okreplay-tests/src/test/java | Create_ds/okreplay/okreplay-tests/src/test/java/okreplay/TapeNameTest.java | package okreplay;
import com.google.common.io.Files;
import org.codehaus.groovy.runtime.ResourceGroovyMethods;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import spock.lang.Issue;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
@Issue("https://github.com/robfletcher/betamax/issues/36")
public class TapeNameTest {
private static final File TAPE_ROOT = Files.createTempDir();
private final OkReplayConfig configuration = new OkReplayConfig.Builder()
.tapeRoot(TAPE_ROOT)
.interceptor(new OkReplayInterceptor())
.build();
@Rule public RecorderRule recorder = new RecorderRule(configuration);
@AfterClass public static void deleteTempDir() {
ResourceGroovyMethods.deleteDir(TAPE_ROOT);
}
@Test @OkReplay(tape = "explicit name") public void tapeCanBeNamedExplicitly() {
assertThat(recorder.getTape().getName(), equalTo("explicit name"));
}
@Test @OkReplay public void tapeNameDefaultsToTestName() {
assertThat(recorder.getTape().getName(), equalTo("tape name defaults to test name"));
}
}
| 2,635 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/RecorderListener.java | package okreplay;
public interface RecorderListener {
void onRecorderStart(Tape tape);
void onRecorderStop();
}
| 2,636 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/Message.java | package okreplay;
import java.nio.charset.Charset;
import okhttp3.Headers;
/**
* An abstraction of an HTTP request or response. Implementations can be backed by any sort of
* underlying implementation.
*/
interface Message {
/** @return all HTTP headers attached to this message. */
Headers headers();
/**
* @param name an HTTP header name.
* @return the comma-separated values for all HTTP headers with the specified name or `null` if
* there are no headers with that name.
*/
String header(String name);
/** @return `true` if the message currently contains a body, `false` otherwise. */
boolean hasBody();
/**
* Returns the message body as a string.
*
* @return the message body as a string.
* @throws IllegalStateException if the message does not have a body.
*/
String bodyAsText();
/**
* Returns the decoded message body. If the implementation stores the message body in an encoded
* form (e.g. gzipped) then it <em>must</em> be decoded before being returned by this method
*
* @return the message body as binary data.
* @throws IllegalStateException if the message does not have a body.
*/
byte[] body();
/** @return the MIME content type of the message not including any charset. */
String getContentType();
/** @return the charset of the message if it is text. */
Charset getCharset();
/** @return the content encoding of the message, e.g. _gzip_, _deflate_ or _none_. */
String getEncoding();
/** @return a copy of this Request object ready to be serialized to YAML */
YamlRecordedMessage toYaml();
}
| 2,637 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/HandlerException.java | package okreplay;
/** Thrown to indicates an exception with some part of the handling chain. */
abstract class HandlerException extends RuntimeException {
HandlerException(String message) {
super(message);
}
}
| 2,638 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/YamlTapeLoader.java | package okreplay;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.introspector.BeanAccess;
import org.yaml.snakeyaml.representer.Representer;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Locale;
import java.util.logging.Logger;
import static org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK;
class YamlTapeLoader implements TapeLoader<YamlTape> {
private static final Logger LOG = Logger.getLogger(YamlTapeLoader.class.getSimpleName());
private final TapeRoot tapeRoot;
YamlTapeLoader(File tapeRoot) {
this(new DefaultTapeRoot(tapeRoot));
}
YamlTapeLoader(TapeRoot tapeRoot) {
this.tapeRoot = tapeRoot;
}
@Override public YamlTape loadTape(String tapeName) {
String fileName = normalize(tapeName);
if (tapeRoot.tapeExists(fileName)) {
Reader reader = tapeRoot.readerFor(fileName);
YamlTape tape = readFrom(reader);
LOG.info(String.format(Locale.US,
"loaded tape with %d recorded interactions from file %s...", tape.size(), fileName));
return tape;
} else {
return newTape(tapeName);
}
}
@Override public void writeTape(final Tape tape) {
String fileName = normalize(tape.getName());
if (tape.isDirty()) {
//noinspection OverlyBroadCatchBlock
try {
Writer writer = tapeRoot.writerFor(fileName);
LOG.info(String.format("writing tape %s to file %s...", tape.getName(), fileName));
writeTo(tape, writer);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
YamlTape newTape(String name) {
YamlTape tape = new YamlTape();
tape.setName(name);
return tape;
}
YamlTape readFrom(Reader reader) {
try {
return (YamlTape) getYaml().load(reader);
} catch (YAMLException | ClassCastException e) {
throw new TapeLoadException("Invalid tape", e);
}
}
void writeTo(Tape tape, Writer writer) throws IOException {
try {
getYaml().dump(tape, writer);
} finally {
writer.close();
}
}
@Override public String normalize(String tapeName) {
return FilenameNormalizer.toFilename(tapeName) + ".yaml";
}
private static Yaml getYaml() {
Representer representer = new TapeRepresenter();
representer.addClassTag(YamlTape.class, YamlTape.TAPE_TAG);
Constructor constructor = new TapeConstructor();
constructor.addTypeDescription(new TypeDescription(YamlTape.class, YamlTape.TAPE_TAG));
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(BLOCK);
dumperOptions.setWidth(256);
Yaml yaml = new Yaml(constructor, representer, dumperOptions);
yaml.setBeanAccess(BeanAccess.FIELD);
return yaml;
}
}
| 2,639 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/RecordedMessage.java | package okreplay;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import okhttp3.Headers;
import okhttp3.MediaType;
abstract class RecordedMessage extends AbstractMessage {
final Headers headers;
final byte[] body;
RecordedMessage(Headers headers, byte[] body) {
this.headers = headers;
this.body = body;
}
@Override public final boolean hasBody() {
return body != null;
}
@Override public Headers headers() {
return headers;
}
@Override public byte[] body() {
return body;
}
LinkedHashMap<String, String> headersAsMap() {
Map<String, String> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (int i = 0, size = headers.size(); i < size; i++) {
String name = headers.name(i);
result.put(name, headers.value(i));
}
return new LinkedHashMap<>(result);
}
Object maybeBodyAsString() {
if (body == null) {
return null;
} else {
// Try to determine if the body content type is text
String mediaType = MediaType.parse(getContentType()).type();
// For text or application media types, assume it's readable text and return the body
// as a String
if (mediaType.equals("text") || mediaType.equals("application")) {
return bodyAsText();
} else {
return body;
}
}
}
} | 2,640 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/YamlRecordedResponse.java | package okreplay;
import java.util.Collections;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
public class YamlRecordedResponse extends YamlRecordedMessage {
private final int status;
YamlRecordedResponse(Map<String, String> headers, Object body, int status) {
super(headers, body);
this.status = status;
}
/** For SnakeYAML */
@SuppressWarnings("unused") public YamlRecordedResponse() {
this(Collections.<String, String>emptyMap(), null, 0);
}
public int code() {
return status;
}
@Override Response toImmutable() {
Object body = body();
MediaType mediaType = MediaType.parse(contentType());
ResponseBody responseBody = null;
if (body != null) {
responseBody = body instanceof String
? ResponseBody.create(mediaType, (String) body)
: ResponseBody.create(mediaType, (byte[]) body);
}
return new RecordedResponse.Builder()
.code(code())
.headers(okhttp3.Headers.of(headers()))
.body(responseBody)
.build();
}
}
| 2,641 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/Tape.java | package okreplay;
/** Represents a set of recorded HTTP interactions that can be played back or appended to. */
public interface Tape {
/** @return The name of the tape. */
String getName();
/** @param mode the new record mode of the tape. */
void setMode(TapeMode mode);
TapeMode getMode();
/** @param matchRule the rules used to match recordings on the tape. */
void setMatchRule(MatchRule matchRule);
MatchRule getMatchRule();
/** @return `true` if the tape is readable, `false` otherwise. */
boolean isReadable();
/** @return `true` if the tape is writable, `false` otherwise. */
boolean isWritable();
/** @return `true` if access is sequential, `false` otherwise. */
boolean isSequential();
/** @return the number of recorded HTTP interactions currently stored on the tape. */
int size();
/**
* Attempts to find a recorded interaction on the tape that matches the
* supplied request.
*
* @param request the HTTP request to match.
* @return `true` if a matching recorded interaction was found, `false` otherwise.
*/
boolean seek(Request request);
/**
* Retrieves a previously recorded response that matches the request.
*
* @param request the HTTP request to match.
* @throws IllegalStateException if no matching recorded interaction exists.
*/
Response play(Request request) throws HandlerException;
/**
* Records a new interaction to the tape. If `request` matches an existing
* interaction this method will overwrite
* it. Otherwise the newly recorded interaction is appended to the tape.
*
* @param request the request to record.
* @param response the response to record.
* @throws UnsupportedOperationException if this `Tape` implementation is not writable.
*/
void record(Request request, Response response);
/**
* @return `true` if the tape content has changed since last being loaded from disk, `false`
* otherwise.
*/
boolean isDirty();
}
| 2,642 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/MemoryTape.java | package okreplay;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static java.util.Collections.unmodifiableList;
import static okreplay.Util.VIA;
/**
* Represents a set of recorded HTTP interactions that can be played back or
* appended to.
*/
abstract class MemoryTape implements Tape {
private String name;
private List<YamlRecordedInteraction> interactions = new ArrayList<>();
private transient TapeMode mode = OkReplayConfig.DEFAULT_MODE;
private transient MatchRule matchRule = OkReplayConfig.DEFAULT_MATCH_RULE;
private final transient AtomicInteger orderedIndex = new AtomicInteger();
@Override public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override public TapeMode getMode() {
return mode;
}
@Override public void setMode(TapeMode mode) {
this.mode = mode;
}
@Override public MatchRule getMatchRule() {
return this.matchRule;
}
@Override public void setMatchRule(MatchRule matchRule) {
this.matchRule = matchRule;
}
@Override public boolean isReadable() {
return mode.isReadable();
}
@Override public boolean isWritable() {
return mode.isWritable();
}
@Override public boolean isSequential() {
return mode.isSequential();
}
@Override public int size() {
return interactions.size();
}
public List<YamlRecordedInteraction> getInteractions() {
return unmodifiableList(interactions);
}
public void setInteractions(List<YamlRecordedInteraction> interactions) {
this.interactions = new ArrayList<>(interactions);
}
@Override public boolean seek(Request request) {
if (isSequential()) {
try {
// TODO: it's a complete waste of time using an AtomicInteger when this method is called
// before play in a non-transactional way
int index = orderedIndex.get();
RecordedInteraction interaction = interactions.get(index).toImmutable();
Request nextRequest = interaction == null ? null : interaction.request();
return nextRequest != null && matchRule.isMatch(request, nextRequest);
} catch (IndexOutOfBoundsException e) {
throw new NonWritableTapeException();
}
} else {
return findMatch(request) >= 0;
}
}
@Override public Response play(final Request request) {
if (!mode.isReadable()) {
throw new IllegalStateException("the tape is not readable");
}
if (mode.isSequential()) {
int nextIndex = orderedIndex.getAndIncrement();
RecordedInteraction nextInteraction = interactions.get(nextIndex).toImmutable();
if (nextInteraction == null) {
throw new IllegalStateException(String.format("No recording found at position %s",
nextIndex));
}
if (!matchRule.isMatch(request, nextInteraction.request())) {
throw new IllegalStateException(String.format("Request %s does not match recorded " +
"request" + " %s", stringify(request), stringify(nextInteraction.request())));
}
return nextInteraction.response();
} else {
int position = findMatch(request);
if (position < 0) {
throw new IllegalStateException("no matching recording found");
} else {
return interactions.get(position).toImmutable().response();
}
}
}
private String stringify(Request request) {
byte[] body = request.body() != null ? request.body() : new byte[0];
String bodyLog = " (binary " + body.length + "-byte body omitted)";
return "method: " + request.method() + ", " + "uri: " + request.url() + ", " + "headers: " +
request.headers() + ", " + bodyLog;
}
@Override public synchronized void record(Request request, Response response) {
if (!mode.isWritable()) {
throw new IllegalStateException("the tape is not writable");
}
RecordedInteraction interaction = new RecordedInteraction(new Date(), recordRequest(request),
recordResponse(response));
if (mode.isSequential()) {
interactions.add(interaction.toYaml());
} else {
int position = findMatch(request);
if (position >= 0) {
interactions.set(position, interaction.toYaml());
} else {
interactions.add(interaction.toYaml());
}
}
}
@Override public String toString() {
return String.format("Tape[%s]", name);
}
private synchronized int findMatch(final Request request) {
return Util.indexOf(interactions.iterator(), new Predicate<YamlRecordedInteraction>() {
@Override public boolean apply(YamlRecordedInteraction input) {
return matchRule.isMatch(request, input.toImmutable().request());
}
});
}
private Request recordRequest(Request request) {
return request.newBuilder()
.removeHeader(VIA)
.build();
}
private Response recordResponse(Response response) {
return response.newBuilder()
.removeHeader(VIA)
.removeHeader(Headers.X_OKREPLAY)
.build();
}
}
| 2,643 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/FilenameNormalizer.java | package okreplay;
import java.text.Normalizer;
public final class FilenameNormalizer {
public static String toFilename(String tapeName) {
return Normalizer.normalize(tapeName, Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
.replaceAll("[^\\w\\d]+", "_")
.replaceFirst("^_", "")
.replaceFirst("_$", "");
}
private FilenameNormalizer() {
}
}
| 2,644 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/Util.java | package okreplay;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Iterator;
import javax.annotation.Nullable;
import static java.lang.String.format;
final class Util {
static final String VIA = "Via";
static final String CONTENT_TYPE = "Content-Type";
static boolean isNullOrEmpty(String str) {
return str == null || str.trim().isEmpty();
}
static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
static int checkPositionIndex(int index, int size) {
return checkPositionIndex(index, size, "index");
}
static int checkPositionIndex(int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
}
return index;
}
static String badPositionIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index > size
return format("%s (%s) must not be greater than size (%s)", desc, index, size);
}
}
static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
}
static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
}
static <T> int indexOf(Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(predicate, "predicate");
for (int i = 0; iterator.hasNext(); i++) {
T current = iterator.next();
if (predicate.apply(current)) {
return i;
}
}
return -1;
}
static <T> boolean all(Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(predicate);
while (iterator.hasNext()) {
T element = iterator.next();
if (!predicate.apply(element)) {
return false;
}
}
return true;
}
}
| 2,645 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/MatchRules.java | package okreplay;
import java.util.Arrays;
/** Standard {@link MatchRule} implementations. */
public enum MatchRules implements MatchRule {
method {
@Override public boolean isMatch(Request a, Request b) {
return a.method().equalsIgnoreCase(b.method());
}
}, uri {
@Override public boolean isMatch(Request a, Request b) {
return a.url().equals(b.url());
}
}, host {
@Override public boolean isMatch(Request a, Request b) {
return a.url().url().getHost().equals(b.url().url().getHost());
}
}, path {
@Override public boolean isMatch(Request a, Request b) {
return a.url().url().getPath().equals(b.url().url().getPath());
}
}, port {
@Override public boolean isMatch(Request a, Request b) {
return a.url().url().getPort() == b.url().url().getPort();
}
}, query {
@Override public boolean isMatch(Request a, Request b) {
return a.url().url().getQuery().equals(b.url().url().getQuery());
}
}, queryParams {
/** Compare query parameters instead of query string representation. */
@Override public boolean isMatch(Request a, Request b) {
if ((a.url().url().getQuery() != null) && (b.url().url().getQuery() != null)) {
// both request have a query, split query params and compare
String[] aParameters = a.url().url().getQuery().split("&");
String[] bParameters = b.url().url().getQuery().split("&");
Arrays.sort(aParameters);
Arrays.sort(bParameters);
return Arrays.equals(aParameters, bParameters);
} else {
return (a.url().url().getQuery() == null) && (b.url().url().getQuery() == null);
}
}
}, authorization {
@Override public boolean isMatch(Request a, Request b) {
return a.header("Authorization").equals(b.header("Authorization"));
}
}, accept {
@Override public boolean isMatch(Request a, Request b) {
return a.header("Accept").equals(b.header("Accept"));
}
}, body {
@Override public boolean isMatch(Request a, Request b) {
return Arrays.equals(a.body(), b.body());
}
}
}
| 2,646 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/Response.java | package okreplay;
import okhttp3.Protocol;
public interface Response extends Message {
/** @return the HTTP status code of the response. */
int code();
/** @return the content MIME type of the response. */
String getContentType();
RecordedResponse.Builder newBuilder();
Protocol protocol();
} | 2,647 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/ComposedMatchRule.java | package okreplay;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import static okreplay.Util.all;
public class ComposedMatchRule implements MatchRule {
public static MatchRule of(MatchRule... rules) {
return new ComposedMatchRule(new LinkedHashSet<>(Arrays.asList(rules)));
}
public static MatchRule of(Collection<MatchRule> rules) {
return new ComposedMatchRule(new LinkedHashSet<>(rules));
}
private final Set<MatchRule> rules;
private ComposedMatchRule(Set<MatchRule> rules) {
this.rules = rules;
}
@Override public boolean isMatch(final Request a, final Request b) {
return all(rules.iterator(), new Predicate<MatchRule>() {
@Override public boolean apply(MatchRule rule) {
return rule.isMatch(a, b);
}
});
}
@Override public int hashCode() {
return rules.hashCode();
}
@Override public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ComposedMatchRule that = (ComposedMatchRule) o;
return rules.equals(that.rules);
}
}
| 2,648 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/YamlRecordedRequest.java | package okreplay;
import java.net.URI;
import java.util.Collections;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.internal.http.HttpMethod;
public class YamlRecordedRequest extends YamlRecordedMessage {
private final String method;
private final URI uri;
YamlRecordedRequest(Map<String, String> headers, Object body, String method, URI uri) {
super(headers, body);
this.method = method;
this.uri = uri;
}
/** For SnakeYAML */
@SuppressWarnings("unused") public YamlRecordedRequest() {
this(Collections.<String, String>emptyMap(), null, null, null);
}
public String method() {
return method;
}
public URI uri() {
return uri;
}
@Override Request toImmutable() {
Object body = body();
MediaType mediaType = MediaType.parse(contentType());
RequestBody requestBody = null;
if (body != null) {
requestBody = body instanceof String
? RequestBody.create(mediaType, (String) body)
: RequestBody.create(mediaType, (byte[]) body);
} else if (HttpMethod.requiresRequestBody(method)) {
// The method required a body but none was given. Use an empty one.
requestBody = RequestBody.create(mediaType, new byte[0]);
}
return new RecordedRequest.Builder()
.headers(okhttp3.Headers.of(headers()))
.method(method, requestBody)
.url(HttpUrl.get(uri))
.build();
}
}
| 2,649 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/Network.java | package okreplay;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
class Network {
static Collection<String> getLocalAddresses() {
try {
InetAddress local = InetAddress.getLocalHost();
return Arrays.asList(local.getHostName(), local.getHostAddress(), "localhost",
"127.0.0.1");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
| 2,650 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/TapeRoot.java | package okreplay;
import java.io.File;
import java.io.Reader;
import java.io.Writer;
@SuppressWarnings("WeakerAccess")
public interface TapeRoot {
/** Returns a reader for reading a tape in the provided path. Throws if the file doesnt exist. */
Reader readerFor(String tapeFileName);
/** Returns a writer for writing to a new tape in the provided path. */
Writer writerFor(String tapePath);
/** Return whether a tape file in the provided path already exists. */
boolean tapeExists(String tapeFileName);
/** Returns the root directory. */
File get();
}
| 2,651 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/RecordedResponse.java | package okreplay;
import java.io.IOException;
import java.util.Map;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.ResponseBody;
class RecordedResponse extends RecordedMessage implements Response {
private final int code;
private final Protocol protocol;
private RecordedResponse(Builder builder) {
super(builder.headers.build(), builder.body);
this.code = builder.code;
this.protocol = builder.protocol;
}
RecordedResponse(int code, Map<String, String> headers, byte[] body) {
super(Headers.of(headers), body);
this.code = code;
this.protocol = Protocol.HTTP_1_1;
}
@Override public int code() {
return code;
}
@Override public Builder newBuilder() {
return new Builder(this);
}
@Override public Protocol protocol() {
return protocol;
}
@Override public YamlRecordedResponse toYaml() {
return new YamlRecordedResponse(headersAsMap(), maybeBodyAsString(), code);
}
static class Builder {
private Protocol protocol = Protocol.HTTP_1_1;
private int code = -1;
private Headers.Builder headers;
private byte[] body;
Builder() {
headers = new Headers.Builder();
}
private Builder(RecordedResponse response) {
this.code = response.code;
this.headers = response.headers.newBuilder();
this.body = response.body;
this.protocol = response.protocol;
}
Builder protocol(Protocol protocol) {
this.protocol = protocol;
return this;
}
Builder code(int code) {
this.code = code;
return this;
}
/**
* Sets the header named {@code name} to {@code value}. If this request already has any headers
* with that name, they are all replaced.
*/
Builder header(String name, String value) {
headers.set(name, value);
return this;
}
/**
* Adds a header with {@code name} and {@code value}. Prefer this method for multiply-valued
* headers like "Set-Cookie".
*/
Builder addHeader(String name, String value) {
headers.add(name, value);
return this;
}
Builder removeHeader(String name) {
headers.removeAll(name);
return this;
}
/** Removes all headers on this builder and adds {@code headers}. */
Builder headers(Headers headers) {
this.headers = headers.newBuilder();
return this;
}
Builder body(ResponseBody body) {
try {
this.body = body.bytes();
} catch (IOException e) {
throw new RuntimeException(e);
}
MediaType contentType = body.contentType();
if (contentType != null && headers.get(Util.CONTENT_TYPE) == null) {
addHeader(Util.CONTENT_TYPE, contentType.toString());
}
return this;
}
RecordedResponse build() {
if (code < 0)
throw new IllegalStateException("code < 0: " + code);
return new RecordedResponse(this);
}
}
} | 2,652 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/OkHttpRequestAdapter.java | package okreplay;
class OkHttpRequestAdapter {
/** Construct a OkReplay Request based on the provided OkHttp Request */
static Request adapt(okhttp3.Request request) {
return new RecordedRequest.Builder()
.url(request.url())
.method(request.method(), request.body())
.headers(request.headers())
.build();
}
}
| 2,653 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/TapeConstructor.java | package okreplay;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.NodeId;
class TapeConstructor extends Constructor {
TapeConstructor() {
yamlClassConstructors.put(NodeId.mapping, new ConstructTape());
}
private class ConstructTape extends ConstructMapping {
@Override protected Object createEmptyJavaBean(MappingNode node) {
if (YamlTape.class.equals(node.getType())) {
return new YamlTape();
} else {
return super.createEmptyJavaBean(node);
}
}
}
}
| 2,654 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/NonWritableTapeException.java | package okreplay;
public class NonWritableTapeException extends HandlerException {
NonWritableTapeException(String message) {
super(message);
}
NonWritableTapeException() {
super("Tape is not writable");
}
}
| 2,655 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/ProxyServer.java | package okreplay;
public class ProxyServer implements RecorderListener {
private final OkReplayConfig configuration;
private final OkReplayInterceptor interceptor;
private boolean running;
public ProxyServer(OkReplayConfig configuration, OkReplayInterceptor interceptor) {
this.configuration = configuration;
this.interceptor = interceptor;
}
@Override public void onRecorderStart(Tape tape) {
if (!isRunning()) {
start(tape);
}
}
@Override public void onRecorderStop() {
if (isRunning()) {
stop();
}
}
private boolean isRunning() {
return running;
}
public void start(final Tape tape) {
if (isRunning()) {
throw new IllegalStateException("OkReplay proxy server is already running");
}
interceptor.start(configuration, tape);
running = true;
}
public void stop() {
if (!isRunning()) {
throw new IllegalStateException("OkReplay proxy server is already stopped");
}
interceptor.stop();
running = false;
}
}
| 2,656 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/OkReplayConfig.java | package okreplay;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* The configuration used by okreplay.
* <p>
* `OkReplayConfig` instances are created with a builder. For example:
* <p>
* [source,java]
* ----
* OkReplayConfig configuration = new OkReplayConfig.Builder()
* .tapeRoot(tapeRoot)
* .ignoreLocalhost(true)
* .build();
* ----
*
* @see Builder
*/
@SuppressWarnings("WeakerAccess")
public class OkReplayConfig {
public static final String DEFAULT_TAPE_ROOT = "src/test/resources/okreplay/tapes";
public static final TapeMode DEFAULT_MODE = TapeMode.READ_ONLY;
public static final MatchRule DEFAULT_MATCH_RULE = ComposedMatchRule.of(MatchRules.method,
MatchRules.uri);
private final TapeRoot tapeRoot;
private final TapeMode defaultMode;
private final Collection<String> ignoreHosts;
private final boolean ignoreLocalhost;
private final MatchRule defaultMatchRule;
private final boolean sslEnabled;
private final OkReplayInterceptor interceptor;
protected OkReplayConfig(Builder builder) {
this.tapeRoot = builder.tapeRoot;
this.defaultMode = builder.defaultMode;
this.defaultMatchRule = builder.defaultMatchRule;
this.ignoreHosts = builder.ignoreHosts;
this.ignoreLocalhost = builder.ignoreLocalhost;
this.sslEnabled = builder.sslEnabled;
this.interceptor = builder.interceptor;
}
/**
* The base directory where tape files are stored.
*/
public TapeRoot getTapeRoot() {
return tapeRoot;
}
/**
* The default mode for an inserted tape.
*/
public TapeMode getDefaultMode() {
return defaultMode;
}
public MatchRule getDefaultMatchRule() {
return defaultMatchRule;
}
/**
* Hosts that are ignored by okreplay. Any connections made will be allowed to proceed
* normally and not be intercepted.
*/
public Collection<String> getIgnoreHosts() {
if (isIgnoreLocalhost()) {
Set<String> set = new LinkedHashSet<>(ignoreHosts);
set.addAll(Network.getLocalAddresses());
return Collections.unmodifiableSet(set);
} else {
return ignoreHosts;
}
}
/**
* If `true` then all connections to localhost addresses are ignored.
* <p>
* This is equivalent to including the following in the collection returned by {@link
* #getIgnoreHosts()}: * `"localhost"` * `"127.0.0.1"` * `InetAddress.getLocalHost()
* .getHostName()`
* * `InetAddress.getLocalHost().getHostAddress()`
*/
public boolean isIgnoreLocalhost() {
return ignoreLocalhost;
}
public OkReplayInterceptor interceptor() {
return interceptor;
}
/**
* If set to true add support for proxying SSL (disable certificate
* checking).
*/
public boolean isSslEnabled() {
return sslEnabled;
}
/**
* Called by the `Recorder` instance so that the configuration can add listeners.
* <p>
* You should **not** call this method yourself.
*/
public void registerListeners(Collection<RecorderListener> listeners) {
listeners.add(new ProxyServer(this, interceptor));
}
public static class Builder {
TapeRoot tapeRoot = new DefaultTapeRoot(new File(OkReplayConfig.DEFAULT_TAPE_ROOT));
TapeMode defaultMode = OkReplayConfig.DEFAULT_MODE;
MatchRule defaultMatchRule = OkReplayConfig.DEFAULT_MATCH_RULE;
List<String> ignoreHosts = Collections.emptyList();
boolean ignoreLocalhost;
boolean sslEnabled;
OkReplayInterceptor interceptor;
public Builder() {
try {
URL propertiesFile = OkReplayConfig.class.getResource("/okreplay.properties");
if (propertiesFile != null) {
Properties properties = new Properties();
properties.load(propertiesFile.openStream());
withProperties(properties);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Builder withProperties(Properties properties) {
if (properties.containsKey("okreplay.tapeRoot")) {
tapeRoot(new File(properties.getProperty("okreplay.tapeRoot")));
}
if (properties.containsKey("okreplay.defaultMode")) {
defaultMode(TapeMode.valueOf(properties.getProperty("okreplay.defaultMode")));
}
if (properties.containsKey("okreplay.defaultMatchRules")) {
String property = properties.getProperty("okreplay.defaultMatchRules");
List<MatchRule> rules = new ArrayList<>();
for (String s : property.split(",")) {
rules.add(MatchRules.valueOf(s));
}
defaultMatchRule(ComposedMatchRule.of(rules));
}
if (properties.containsKey("okreplay.ignoreHosts")) {
ignoreHosts(Arrays.asList(properties.getProperty("okreplay.ignoreHosts").split(",")));
}
if (properties.containsKey("okreplay.ignoreLocalhost")) {
ignoreLocalhost(Boolean.valueOf(properties.getProperty("okreplay.ignoreLocalhost")));
}
if (properties.containsKey("okreplay.sslEnabled")) {
sslEnabled(TypedProperties.getBoolean(properties, "okreplay.sslEnabled"));
}
return this;
}
public Builder tapeRoot(File tapeRoot) {
return tapeRoot(new DefaultTapeRoot(tapeRoot));
}
public Builder tapeRoot(TapeRoot tapeRoot) {
this.tapeRoot = tapeRoot;
return this;
}
public Builder defaultMode(TapeMode defaultMode) {
this.defaultMode = defaultMode;
return this;
}
public Builder interceptor(OkReplayInterceptor interceptor) {
this.interceptor = interceptor;
return this;
}
public Builder defaultMatchRule(MatchRule defaultMatchRule) {
this.defaultMatchRule = defaultMatchRule;
return this;
}
public Builder defaultMatchRules(MatchRule... defaultMatchRules) {
this.defaultMatchRule = ComposedMatchRule.of(defaultMatchRules);
return this;
}
public Builder ignoreHosts(Collection<String> ignoreHosts) {
this.ignoreHosts = new ArrayList<>(ignoreHosts);
return this;
}
public Builder ignoreLocalhost(boolean ignoreLocalhost) {
this.ignoreLocalhost = ignoreLocalhost;
return this;
}
public Builder sslEnabled(boolean sslEnabled) {
this.sslEnabled = sslEnabled;
return this;
}
public OkReplayConfig build() {
return new OkReplayConfig(this);
}
}
}
| 2,657 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/Headers.java | package okreplay;
public class Headers {
public static final String X_OKREPLAY = "X-OkReplay";
static final String VIA_HEADER = "OkReplay";
private Headers() {
}
}
| 2,658 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/Predicate.java | package okreplay;
import javax.annotation.Nullable;
public interface Predicate<T> {
/**
* Returns the result of applying this predicate to {@code input} (Java 8 users, see notes in the
* class documentation above). This method is <i>generally expected</i>, but not absolutely
* required, to have the following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal
* Objects.equal}{@code (a, b)} implies that {@code predicate.apply(a) ==
* predicate.apply(b))}.
* </ul>
*
* @throws NullPointerException if {@code input} is null and this predicate does not accept null
* arguments
*/
boolean apply(@Nullable T input);
/**
* Indicates whether another object is equal to this predicate.
*
* <p>Most implementations will have no reason to override the behavior of {@link Object#equals}.
* However, an implementation may also choose to return {@code true} whenever {@code object} is a
* {@link Predicate} that it considers <i>interchangeable</i> with this one. "Interchangeable"
* <i>typically</i> means that {@code this.apply(t) == that.apply(t)} for all {@code t} of type
* {@code T}). Note that a {@code false} result from this method does not imply that the
* predicates are known <i>not</i> to be interchangeable.
*/
@Override
boolean equals(@Nullable Object object);
} | 2,659 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/TapeLoader.java | package okreplay;
/** The interface for factories that load tapes from file storage. */
public interface TapeLoader<T extends Tape> {
/**
* Loads the named tape or returns a new blank tape if an existing tape cannot be located.
*
* @param name the name of the tape.
* @return a tape loaded from a file or a new blank tape.
*/
T loadTape(String name);
void writeTape(Tape tape);
/** @return an appropriate filename for storing a tape with the supplied name. */
String normalize(String tapeName);
}
| 2,660 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/OkHttpResponseAdapter.java | package okreplay;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.BufferedSource;
class OkHttpResponseAdapter {
/** Construct a OkHttp Response from a previously recorded interaction */
static okhttp3.Response adapt(okhttp3.Request okhttpRequest, Response recordedResponse) {
ResponseBody responseBody = ResponseBody.create(
MediaType.parse(recordedResponse.getContentType()), recordedResponse.body());
return new okhttp3.Response.Builder()
.headers(recordedResponse.headers())
.body(responseBody)
.code(recordedResponse.code())
.protocol(recordedResponse.protocol())
.request(okhttpRequest)
.message("")
.build();
}
/** Construct a OkReplay Response based on the provided OkHttp response */
static Response adapt(final okhttp3.Response okhttpResponse, ResponseBody body) {
return new RecordedResponse.Builder()
.headers(okhttpResponse.headers())
.body(body)
.protocol(okhttpResponse.protocol())
.code(okhttpResponse.code())
.build();
}
static ResponseBody cloneResponseBody(ResponseBody responseBody) {
try {
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE);
return ResponseBody.create(responseBody.contentType(), responseBody.contentLength(),
source.buffer().clone());
} catch (IOException e) {
throw new RuntimeException("Failed to read response body", e);
}
}
}
| 2,661 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/YamlTape.java | package okreplay;
import org.yaml.snakeyaml.nodes.Tag;
class YamlTape extends MemoryTape {
static final Tag TAPE_TAG = new Tag("!tape");
private transient boolean dirty;
@Override public boolean isDirty() {
return dirty;
}
@Override public void record(Request request, Response response) {
super.record(request, response);
dirty = true;
}
}
| 2,662 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/YamlRecordedMessage.java | package okreplay;
import java.util.Map;
import okhttp3.MediaType;
import static okreplay.AbstractMessage.DEFAULT_CONTENT_TYPE;
import static okreplay.Util.CONTENT_TYPE;
import static okreplay.Util.isNullOrEmpty;
public abstract class YamlRecordedMessage {
private final Map<String, String> headers;
private final Object body;
YamlRecordedMessage(Map<String, String> headers, Object body) {
this.headers = headers;
this.body = body;
}
String contentType() {
String header = headers.get(CONTENT_TYPE);
if (isNullOrEmpty(header)) {
return DEFAULT_CONTENT_TYPE;
} else {
return MediaType.parse(header).toString();
}
}
public Map<String, String> headers() {
return headers;
}
public String header(String name) {
return headers.get(name);
}
public Object body() {
return body;
}
abstract Message toImmutable();
}
| 2,663 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/YamlRecordedInteraction.java | package okreplay;
import java.util.Date;
public class YamlRecordedInteraction {
private final Date recorded;
private final YamlRecordedRequest request;
private final YamlRecordedResponse response;
private transient RecordedInteraction immutableInteraction;
YamlRecordedInteraction(Date recorded, YamlRecordedRequest request,
YamlRecordedResponse response) {
this.recorded = recorded;
this.request = request;
this.response = response;
}
/** For SnakeYAML */
@SuppressWarnings("unused") public YamlRecordedInteraction() {
this(null, null, null);
}
RecordedInteraction toImmutable() {
if (immutableInteraction == null) {
immutableInteraction = createImmutable();
}
return immutableInteraction;
}
private RecordedInteraction createImmutable() {
return new RecordedInteraction(recorded, request.toImmutable(), response.toImmutable());
}
}
| 2,664 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/DefaultTapeRoot.java | package okreplay;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import static okreplay.Util.newReader;
import static okreplay.Util.newWriter;
public class DefaultTapeRoot implements TapeRoot {
private static final String FILE_CHARSET = "UTF-8";
protected final File root;
public DefaultTapeRoot(File root) {
this.root = root;
}
@Override public Reader readerFor(String tapeFileName) {
File file = new File(root, tapeFileName);
try {
return newReader(file, Charset.forName(FILE_CHARSET));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
@Override public Writer writerFor(String tapePath) {
File file = new File(root, tapePath);
//noinspection ResultOfMethodCallIgnored
file.getParentFile().mkdirs();
try {
return newWriter(file, Charset.forName(FILE_CHARSET));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
@Override public boolean tapeExists(String tapeFileName) {
return new File(root, tapeFileName).isFile();
}
@Override public File get() {
return root;
}
}
| 2,665 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/TapeLoadException.java | package okreplay;
public class TapeLoadException extends RuntimeException {
public TapeLoadException() {
super();
}
public TapeLoadException(String message) {
super(message);
}
public TapeLoadException(String message, Throwable cause) {
super(message, cause);
}
public TapeLoadException(Throwable cause) {
super(cause);
}
}
| 2,666 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/TapeRepresenter.java | package okreplay;
import org.yaml.snakeyaml.introspector.BeanAccess;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.introspector.PropertyUtils;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Represent;
import org.yaml.snakeyaml.representer.Representer;
import java.beans.IntrospectionException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* Applies a fixed ordering to properties and excludes `null` valued
* properties, empty collections and empty maps.
*/
class TapeRepresenter extends Representer {
TapeRepresenter() {
setPropertyUtils(new TapePropertyUtils());
representers.put(URI.class, new RepresentURI());
}
@Override
protected NodeTuple representJavaBeanProperty(Object bean, Property property, Object value, Tag
customTag) {
NodeTuple tuple = super.representJavaBeanProperty(bean, property, value, customTag);
if (isNullValue(tuple) || isEmptySequence(tuple) || isEmptyMapping(tuple)) {
return null;
}
return tuple;
}
@Override protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) {
return super.representMapping(tag, sort(mapping), flowStyle);
}
private <K, V> Map<K, V> sort(Map<K, V> self) {
return new TreeMap<>(self);
}
private boolean isNullValue(NodeTuple tuple) {
return tuple.getValueNode().getTag().equals(Tag.NULL);
}
private boolean isEmptySequence(NodeTuple tuple) {
return tuple.getValueNode() instanceof SequenceNode && ((SequenceNode) tuple.getValueNode())
.getValue().isEmpty();
}
private boolean isEmptyMapping(NodeTuple tuple) {
return tuple.getValueNode() instanceof MappingNode && ((MappingNode) tuple.getValueNode())
.getValue().isEmpty();
}
private class RepresentURI implements Represent {
public Node representData(Object data) {
return representScalar(Tag.STR, data.toString());
}
}
private class TapePropertyUtils extends PropertyUtils {
@Override protected Set<Property> createPropertySet(Class<?> type, BeanAccess bAccess) {
try {
Set<Property> properties = super.createPropertySet(type, bAccess);
if (Tape.class.isAssignableFrom(type)) {
return sort(properties, "name", "interactions");
} else if (YamlRecordedInteraction.class.isAssignableFrom(type)) {
return sort(properties, "recorded", "request", "response");
} else if (YamlRecordedRequest.class.isAssignableFrom(type)) {
return sort(properties, "method", "uri", "headers", "body");
} else if (YamlRecordedResponse.class.isAssignableFrom(type)) {
return sort(properties, "status", "headers", "body");
} else {
return properties;
}
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
}
private Set<Property> sort(Set<Property> properties, String... names) {
List<Property> list = new ArrayList<>(properties);
Collections.sort(list, OrderedPropertyComparator.forNames(names));
return new LinkedHashSet<>(list);
}
}
private static class OrderedPropertyComparator implements Comparator<Property> {
private final List<String> propertyNames;
static OrderedPropertyComparator forNames(String... propertyNames) {
return new OrderedPropertyComparator(propertyNames);
}
private OrderedPropertyComparator(String... propertyNames) {
this.propertyNames = Arrays.asList(propertyNames);
}
@Override public int compare(Property a, Property b) {
return Integer.compare(propertyNames.indexOf(a.getName()), propertyNames.indexOf(b.getName()));
}
}
}
| 2,667 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/MatchRule.java | package okreplay;
/**
* A rule used to determine whether a recorded HTTP interaction on tape matches a new request being
* made.
*/
public interface MatchRule {
boolean isMatch(Request a, Request b);
}
| 2,668 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/RecordedRequest.java | package okreplay;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import okhttp3.CacheControl;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.internal.http.HttpMethod;
import okio.Buffer;
import static okreplay.Util.CONTENT_TYPE;
class RecordedRequest extends RecordedMessage implements Request {
private final String method;
private final HttpUrl url;
private RecordedRequest(Builder builder) {
super(builder.headers.build(), builder.body);
this.url = builder.url;
this.method = builder.method;
}
RecordedRequest(String method, String url) {
this(method, url, Collections.<String, String>emptyMap());
}
RecordedRequest(String method, String url, Map<String, String> headers) {
this(method, url, headers, null);
}
RecordedRequest(String method, String url, Map<String, String> headers, byte[] body) {
super(Headers.of(headers), body);
this.method = method;
this.url = HttpUrl.parse(url);
}
@Override public String method() {
return method;
}
@Override public HttpUrl url() {
return url;
}
@Override public Builder newBuilder() {
return new Builder(this);
}
@Override public YamlRecordedRequest toYaml() {
return new YamlRecordedRequest(headersAsMap(), maybeBodyAsString(), method, url.uri());
}
static class Builder {
private HttpUrl url;
private String method;
private Headers.Builder headers;
private byte[] body;
Builder() {
this.method = "GET";
this.headers = new Headers.Builder();
}
private Builder(RecordedRequest request) {
this.url = request.url;
this.method = request.method;
this.body = request.body;
this.headers = request.headers.newBuilder();
}
Builder url(HttpUrl url) {
if (url == null)
throw new NullPointerException("url == null");
this.url = url;
return this;
}
/**
* Sets the URL target of this request.
*
* @throws IllegalArgumentException if {@code url} is not a valid HTTP or HTTPS URL. Avoid this
* exception by calling {@link HttpUrl#parse}; it returns null
* for invalid URLs.
*/
Builder url(String url) {
if (url == null)
throw new NullPointerException("url == null");
// Silently replace websocket URLs with HTTP URLs.
if (url.regionMatches(true, 0, "ws:", 0, 3)) {
url = "http:" + url.substring(3);
} else if (url.regionMatches(true, 0, "wss:", 0, 4)) {
url = "https:" + url.substring(4);
}
HttpUrl parsed = HttpUrl.parse(url);
if (parsed == null)
throw new IllegalArgumentException("unexpected url: " + url);
return url(parsed);
}
/**
* Sets the URL target of this request.
*
* @throws IllegalArgumentException if the scheme of {@code url} is not {@code http} or {@code
* https}.
*/
Builder url(URL url) {
if (url == null)
throw new NullPointerException("url == null");
HttpUrl parsed = HttpUrl.get(url);
if (parsed == null)
throw new IllegalArgumentException("unexpected url: " + url);
return url(parsed);
}
/**
* Sets the header named {@code name} to {@code value}. If this request already has any headers
* with that name, they are all replaced.
*/
Builder header(String name, String value) {
headers.set(name, value);
return this;
}
/**
* Adds a header with {@code name} and {@code value}. Prefer this method for multiply-valued
* headers like "Cookie".
*
* <p>Note that for some headers including {@code Content-Length} and {@code Content-Encoding},
* OkHttp may replace {@code value} with a header derived from the request body.
*/
Builder addHeader(String name, String value) {
headers.add(name, value);
return this;
}
Builder removeHeader(String name) {
headers.removeAll(name);
return this;
}
/** Removes all headers on this builder and adds {@code headers}. */
Builder headers(Headers headers) {
this.headers = headers.newBuilder();
return this;
}
/**
* Sets this request's {@code Cache-Control} header, replacing any cache control headers already
* present. If {@code cacheControl} doesn't define any directives, this clears this request's
* cache-control headers.
*/
Builder cacheControl(CacheControl cacheControl) {
String value = cacheControl.toString();
if (value.isEmpty())
return removeHeader("Cache-Control");
return header("Cache-Control", value);
}
Builder get() {
return method("GET", null);
}
Builder head() {
return method("HEAD", null);
}
Builder post(RequestBody body) {
return method("POST", body);
}
Builder delete(RequestBody body) {
return method("DELETE", body);
}
Builder delete() {
return delete(RequestBody.create(null, new byte[0]));
}
Builder put(RequestBody body) {
return method("PUT", body);
}
Builder patch(RequestBody body) {
return method("PATCH", body);
}
Builder method(String method, RequestBody body) {
if (method == null)
throw new NullPointerException("method == null");
if (method.length() == 0)
throw new IllegalArgumentException("method.length() == 0");
if (body != null && !HttpMethod.permitsRequestBody(method)) {
throw new IllegalArgumentException("method " + method + " must not have a request body.");
}
if (body == null && HttpMethod.requiresRequestBody(method)) {
throw new IllegalArgumentException("method " + method + " must have a request body.");
}
this.method = method;
if (body != null) {
try {
Buffer buffer = new Buffer();
body.writeTo(buffer);
this.body = buffer.readByteArray();
MediaType contentType = body.contentType();
if (contentType != null) {
addHeader(CONTENT_TYPE, contentType.toString());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return this;
}
RecordedRequest build() {
if (url == null)
throw new IllegalStateException("url == null");
return new RecordedRequest(this);
}
}
} | 2,669 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/TypedProperties.java | package okreplay;
import java.util.Properties;
class TypedProperties extends Properties {
private static boolean getBoolean(Properties properties, String key, boolean defaultValue) {
String value = properties.getProperty(key);
return value != null ? Boolean.valueOf(value) : defaultValue;
}
static boolean getBoolean(Properties properties, String key) {
return getBoolean(properties, key, false);
}
private static int getInteger(Properties properties, String key, int defaultValue) {
String value = properties.getProperty(key);
return value != null ? Integer.parseInt(value) : defaultValue;
}
public static int getInteger(Properties properties, String key) {
return getInteger(properties, key, 0);
}
}
| 2,670 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/RecordedInteraction.java | package okreplay;
import java.util.Date;
class RecordedInteraction {
private final Date recorded;
private final Request request;
private final Response response;
RecordedInteraction(Date recorded, Request request, Response response) {
this.recorded = recorded;
this.request = request;
this.response = response;
}
Date recorded() {
return recorded;
}
Request request() {
return request;
}
Response response() {
return response;
}
YamlRecordedInteraction toYaml() {
return new YamlRecordedInteraction(recorded,
(YamlRecordedRequest) request.toYaml(), (YamlRecordedResponse) response.toYaml());
}
}
| 2,671 |
0 | Create_ds/okreplay/okreplay-core/src/main/java | Create_ds/okreplay/okreplay-core/src/main/java/okreplay/Request.java | package okreplay;
import okhttp3.HttpUrl;
public interface Request extends Message {
/** @return the request method. */
String method();
/** @return the target URL of the request. */
HttpUrl url();
RecordedRequest.Builder newBuilder();
} | 2,672 |
0 | Create_ds/okreplay/okreplay-noop/src/main/java | Create_ds/okreplay/okreplay-noop/src/main/java/okreplay/OkReplayInterceptor.java | package okreplay;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Response;
public class OkReplayInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
return chain.proceed(chain.request());
}
}
| 2,673 |
0 | Create_ds/elsy/examples/java-library/src/test/java/com/cisco | Create_ds/elsy/examples/java-library/src/test/java/com/cisco/example/NoteImplTest.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.example;
import com.cisco.example.impl.NoteImpl;
import org.junit.Assert;
import org.junit.Test;
public class NoteImplTest {
@Test
public void testNote(){
final NoteImpl n1 = new NoteImpl(5L, "a note");
final NoteImpl n2 = new NoteImpl(5L, "a note");
final NoteImpl n3 = new NoteImpl(5L, "a different note");
Assert.assertEquals(n1, n2);
Assert.assertNotEquals(n1, n3);
}
}
| 2,674 |
0 | Create_ds/elsy/examples/java-library/src/main/java/com/cisco/example | Create_ds/elsy/examples/java-library/src/main/java/com/cisco/example/impl/NoteImpl.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.example.impl;
import com.cisco.example.api.Note;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class NoteImpl implements Note {
private long id;
private String content;
public NoteImpl(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return 0;
}
public String getContent() {
return null;
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
| 2,675 |
0 | Create_ds/elsy/examples/java-library/src/main/java/com/cisco/example | Create_ds/elsy/examples/java-library/src/main/java/com/cisco/example/api/Note.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.example.api;
/**
* A simple text note
*/
public interface Note {
/**
* @return the id of the note
*/
long getId();
/**
* @return the actual note content.
*/
String getContent();
}
| 2,676 |
0 | Create_ds/elsy/examples/java-note-service/src/test/java/com/cisco | Create_ds/elsy/examples/java-note-service/src/test/java/com/cisco/resources/NoteResourceTest.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.resources;
import com.cisco.api.Note;
import com.cisco.db.NotesDao;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.Arrays;
import java.util.List;
public class NoteResourceTest {
@Test
public void testReturn() {
final NotesDao dao = Mockito.mock(NotesDao.class);
final List<Note> notes = Arrays.asList(new Note(5L, "testNote", System.currentTimeMillis()));
Mockito.when(dao.findAll()).thenReturn(notes);
final NotesResource resource = new NotesResource(dao);
Assert.assertEquals(notes, resource.getNotes());
}
}
| 2,677 |
0 | Create_ds/elsy/examples/java-note-service/src/main/java/com | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco/JavaNoteServiceApplication.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco;
import com.cisco.db.NotesDao;
import com.cisco.resources.NotesResource;
import io.dropwizard.Application;
import io.dropwizard.configuration.EnvironmentVariableSubstitutor;
import io.dropwizard.configuration.SubstitutingSourceProvider;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.jdbi.DBIFactory;
import io.dropwizard.migrations.MigrationsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.skife.jdbi.v2.DBI;
public class JavaNoteServiceApplication extends Application<JavaNoteServiceConfiguration> {
public static void main(final String[] args) throws Exception {
new JavaNoteServiceApplication().run(args);
}
@Override
public String getName() {
return "Java Note Service";
}
@Override
public void initialize(final Bootstrap<JavaNoteServiceConfiguration> bootstrap) {
// Enable variable substitution with environment variables
bootstrap.setConfigurationSourceProvider(
new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
new EnvironmentVariableSubstitutor(false)
)
);
bootstrap.addBundle(new MigrationsBundle<JavaNoteServiceConfiguration>() {
@Override
public DataSourceFactory getDataSourceFactory(JavaNoteServiceConfiguration configuration) {
return configuration.getDataSourceFactory();
}
});
}
@Override
public void run(final JavaNoteServiceConfiguration config,
final Environment environment) {
final DBIFactory factory = new DBIFactory();
final DBI jdbi = factory.build(environment, config.getDataSourceFactory(), "mysql");
final NotesDao dao = jdbi.onDemand(NotesDao.class);
environment.jersey().register(new NotesResource(dao));
}
}
| 2,678 |
0 | Create_ds/elsy/examples/java-note-service/src/main/java/com | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco/JavaNoteServiceConfiguration.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
public class JavaNoteServiceConfiguration extends Configuration {
@Valid
@NotNull
private DataSourceFactory database = new DataSourceFactory();
@JsonProperty("database")
public DataSourceFactory getDataSourceFactory() {
return database;
}
public void setDatabase(DataSourceFactory database) {
this.database = database;
}
}
| 2,679 |
0 | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco/resources/NotesResource.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.resources;
import com.cisco.api.Note;
import com.cisco.db.NotesDao;
import com.codahale.metrics.annotation.Timed;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
@Path("/notes")
@Produces(MediaType.APPLICATION_JSON)
public class NotesResource {
private final NotesDao dao;
public NotesResource(NotesDao dao) {
this.dao = dao;
}
@POST
@Timed
public long createNote(Note note) {
return dao.insert(note.getNote());
}
@GET
@Timed
public List<Note> getNotes() {
return dao.findAll();
}
}
| 2,680 |
0 | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco/db/NotesDao.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.db;
import com.cisco.api.Note;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.GetGeneratedKeys;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
import java.util.List;
@RegisterMapper(NotesMapper.class)
public interface NotesDao {
@SqlUpdate("insert into notes (note) values (:note)")
@GetGeneratedKeys
long insert(@Bind("note") String note);
@SqlQuery("select * from notes order by creationDate DESC")
List<Note> findAll();
}
| 2,681 |
0 | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco/db/NotesMapper.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.db;
import com.cisco.api.Note;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public class NotesMapper implements ResultSetMapper<Note> {
@Override
public Note map(int index, ResultSet r, StatementContext ctx) throws SQLException {
return new Note(r.getLong("id"), r.getString("note"), r.getTimestamp("creationDate").getTime());
}
}
| 2,682 |
0 | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco | Create_ds/elsy/examples/java-note-service/src/main/java/com/cisco/api/Note.java | /*
* Copyright 2016 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.Length;
public class Note {
private long id;
@Length(max = 140)
private String note;
private long creationDate;
public Note() {
// jackson deserialization
}
public Note(long id, String note, long creationDate) {
this.id = id;
this.note = note;
this.creationDate = creationDate;
}
@JsonProperty
public long getId() {
return id;
}
@JsonProperty
public String getNote() {
return note;
}
@JsonProperty
public long getCreationDate() {
return creationDate;
}
}
| 2,683 |
0 | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs/publish/PushRequestEventSourceJob.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejobs.publish;
import com.mantisrx.common.utils.MantisSourceJobConstants;
import io.mantisrx.connector.publish.core.QueryRegistry;
import io.mantisrx.connector.publish.source.http.PushHttpSource;
import io.mantisrx.connector.publish.source.http.SourceSink;
import io.mantisrx.runtime.Job;
import io.mantisrx.runtime.MantisJob;
import io.mantisrx.runtime.MantisJobProvider;
import io.mantisrx.runtime.Metadata;
import io.mantisrx.runtime.executor.LocalJobExecutorNetworked;
import io.mantisrx.runtime.parameter.type.IntParameter;
import io.mantisrx.runtime.parameter.validator.Validators;
import io.mantisrx.sourcejobs.publish.core.RequestPostProcessor;
import io.mantisrx.sourcejobs.publish.core.RequestPreProcessor;
import io.mantisrx.sourcejobs.publish.core.Utils;
import io.mantisrx.sourcejobs.publish.stages.EchoStage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PushRequestEventSourceJob extends MantisJobProvider<String> {
private static final Logger LOGGER = LoggerFactory.getLogger(PushRequestEventSourceJob.class);
private static final String MANTIS_CLIENT_ID = "MantisPushRequestEvents";
@Override
public Job<String> getJobInstance() {
String jobId = Utils.getEnvVariable("JOB_ID", "PushRequestEventSourceJobLocal-1");
String mantisClientId = MANTIS_CLIENT_ID + "_" + jobId;
QueryRegistry queryRegistry = new QueryRegistry.Builder()
.withClientIdPrefix(mantisClientId)
.build();
String customPortName = "MANTIS_WORKER_CUSTOM_PORT";
String consolePort = Utils.getEnvVariable(customPortName, "9090");
int port = 9090;
if (consolePort != null && !consolePort.isEmpty()) {
port = Integer.parseInt(consolePort);
}
return
MantisJob
.source(new PushHttpSource(queryRegistry, port))
.stage(new EchoStage(), EchoStage.config())
.sink(new SourceSink(
new RequestPreProcessor(queryRegistry),
new RequestPostProcessor(queryRegistry),
mantisClientId))
.parameterDefinition(new IntParameter()
.name(MantisSourceJobConstants.ECHO_STAGE_BUFFER_MILLIS)
.description("millis to buffer events before processing")
.validator(Validators.range(100, 1000))
.defaultValue(250)
.build())
.metadata(new Metadata.Builder()
.name("PushRequestEventSourceJob")
.description("Fetches request events from any source in a distributed manner. "
+ "The output is served via HTTP server using SSE protocol.")
.build())
.create();
}
public static void main(String[] args) {
LocalJobExecutorNetworked.execute(new PushRequestEventSourceJob().getJobInstance());
}
}
| 2,684 |
0 | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs/publish | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs/publish/core/RequestPostProcessor.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejobs.publish.core;
import java.util.List;
import java.util.Map;
import com.mantisrx.common.utils.MantisSourceJobConstants;
import io.mantisrx.connector.publish.core.QueryRegistry;
import io.mantisrx.runtime.Context;
import org.apache.log4j.Logger;
import rx.functions.Func2;
public class RequestPostProcessor implements Func2<Map<String, List<String>>, Context, Void> {
private static final Logger LOGGER = Logger.getLogger(RequestPostProcessor.class);
private final QueryRegistry queryRegistry;
public RequestPostProcessor(QueryRegistry queryRegistry) {
this.queryRegistry = queryRegistry;
}
@Override
public Void call(Map<String, List<String>> queryParams, Context context) {
LOGGER.info("RequestPostProcessor:queryParams: " + queryParams);
if (queryParams != null) {
if (queryParams.containsKey(MantisSourceJobConstants.SUBSCRIPTION_ID_PARAM_NAME) && queryParams.containsKey(MantisSourceJobConstants.CRITERION_PARAM_NAME)) {
final String subId = queryParams.get(MantisSourceJobConstants.SUBSCRIPTION_ID_PARAM_NAME).get(0);
final String query = queryParams.get(MantisSourceJobConstants.CRITERION_PARAM_NAME).get(0);
String targetApp = queryParams.containsKey(MantisSourceJobConstants.TARGET_APP_NAME_KEY) ? queryParams.get(MantisSourceJobConstants.TARGET_APP_NAME_KEY).get(0) : QueryRegistry.ANY;
if (subId != null && query != null) {
queryRegistry.deregisterQuery(targetApp, subId, query);
}
}
}
return null;
}
}
| 2,685 |
0 | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs/publish | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs/publish/core/Utils.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejobs.publish.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Utils {
public static String getEnvVariable(String envVariableName, String defaultValue) {
String v = System.getenv(envVariableName);
if (v != null && !v.isEmpty()) {
return v;
}
return defaultValue;
}
public static List<String> convertCommaSeparatedStringToList(String filterBy) {
List<String> terms = new ArrayList<>();
if (filterBy != null && !filterBy.isEmpty()) {
terms = Arrays.asList(filterBy.split("\\s*,\\s*"));
}
return terms;
}
}
| 2,686 |
0 | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs/publish | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs/publish/core/RequestPreProcessor.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejobs.publish.core;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.mantisrx.common.utils.MantisSourceJobConstants;
import io.mantisrx.connector.publish.core.QueryRegistry;
import io.mantisrx.runtime.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Func2;
public class RequestPreProcessor implements Func2<Map<String, List<String>>, Context, Void> {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestPreProcessor.class);
private final QueryRegistry queryRegistry;
private final Map<String, String> emptyMap = new HashMap<String, String>();
public RequestPreProcessor(QueryRegistry queryRegistry) {
this.queryRegistry = queryRegistry;
}
@Override
public Void call(Map<String, List<String>> queryParams, Context context) {
LOGGER.info("RequestPreProcessor:queryParams: " + queryParams);
if (queryParams != null) {
if (queryParams.containsKey(MantisSourceJobConstants.SUBSCRIPTION_ID_PARAM_NAME) && queryParams.containsKey(MantisSourceJobConstants.CRITERION_PARAM_NAME)) {
final String subId = queryParams.get(MantisSourceJobConstants.SUBSCRIPTION_ID_PARAM_NAME).get(0);
final String query = queryParams.get(MantisSourceJobConstants.CRITERION_PARAM_NAME).get(0);
String targetApp = queryParams.containsKey(MantisSourceJobConstants.TARGET_APP_NAME_KEY) ? queryParams.get(MantisSourceJobConstants.TARGET_APP_NAME_KEY).get(0) : QueryRegistry.ANY;
if (subId != null && query != null) {
queryRegistry.registerQuery(targetApp, subId, query, emptyMap, false);
}
}
}
return null;
}
}
| 2,687 |
0 | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs/publish | Create_ds/mantis-source-jobs/publish-source-job/src/main/java/io/mantisrx/sourcejobs/publish/stages/EchoStage.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejobs.publish.stages;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.mantisrx.common.utils.MantisSourceJobConstants;
import io.mantisrx.common.codec.Codecs;
import io.mantisrx.publish.netty.proto.MantisEventEnvelope;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.ScalarToScalar;
import io.mantisrx.runtime.computation.ScalarComputation;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import io.mantisrx.runtime.parameter.type.IntParameter;
import io.mantisrx.runtime.parameter.validator.Validators;
import org.apache.log4j.Logger;
import rx.Observable;
public class EchoStage implements ScalarComputation<String, String> {
private static final Logger LOGGER = Logger.getLogger(EchoStage.class);
private String clusterName;
private int bufferDuration = 100;
private String sourceNamePrefix;
private ObjectReader mantisEventEnvelopeReader;
private final ObjectMapper mapper = new ObjectMapper();
@Override
public void init(Context context) {
clusterName = context.getWorkerInfo().getJobClusterName();
bufferDuration = (int) context.getParameters().get(MantisSourceJobConstants.ECHO_STAGE_BUFFER_MILLIS);
sourceNamePrefix = "{" + MantisSourceJobConstants.MANTIS_META_SOURCE_NAME + ":" + "\"" + clusterName + "\",";
mantisEventEnvelopeReader = mapper.readerFor(MantisEventEnvelope.class);
}
private String insertSourceJobName(String event) {
StringBuilder sb = new StringBuilder(sourceNamePrefix);
int indexofbrace = event.indexOf('{');
if (indexofbrace != -1) {
event = sb.append(event.substring(indexofbrace + 1)).toString();
}
return event;
}
public Observable<String> call(Context context,
Observable<String> events) {
return events
.buffer(bufferDuration, TimeUnit.MILLISECONDS)
.flatMapIterable(i -> i)
.filter((event) -> !event.isEmpty())
.flatMap((envelopeStr) -> {
try {
MantisEventEnvelope envelope = mantisEventEnvelopeReader.readValue(envelopeStr);
return Observable.from(envelope.getEventList())
.map((event) -> event.getData());
} catch (IOException e) {
LOGGER.error(e.getMessage());
// Could not parse just send it along.
return Observable.just(envelopeStr);
}
})
.map(this::insertSourceJobName)
.onErrorResumeNext((t1) -> {
LOGGER.error("Exception occurred in : " + clusterName + " error is " + t1.getMessage());
return Observable.empty();
});
}
public static List<ParameterDefinition<?>> getParameters() {
List<ParameterDefinition<?>> params = new ArrayList<>();
// buffer duration
params.add(new IntParameter()
.name(MantisSourceJobConstants.ECHO_STAGE_BUFFER_MILLIS)
.description("buffer time in millis")
.validator(Validators.range(100, 10000))
.defaultValue(250)
.build());
return params;
}
public static ScalarToScalar.Config<String, String> config() {
return new ScalarToScalar.Config<String, String>()
.codec(Codecs.string())
.concurrentInput()
.withParameters(getParameters());
}
} | 2,688 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/test/java/io/mantisrx/sourcejob | Create_ds/mantis-source-jobs/kafka-source-job/src/test/java/io/mantisrx/sourcejob/kafka/QueryableKafkaSourceJobTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import info.batey.kafka.unit.KafkaUnit;
import io.mantisrx.connector.kafka.KafkaSourceParameters;
import io.mantisrx.connector.kafka.source.serde.ParserType;
import io.mantisrx.runtime.executor.LocalJobExecutorNetworked;
import io.mantisrx.runtime.parameter.Parameter;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import rx.schedulers.Schedulers;
// Test ignored until kafka-unit dependency for kafka v2.2.+ is released after merging PR https://github.com/chbatey/kafka-unit/pull/69
@Ignore
public class QueryableKafkaSourceJobTest {
private static final KafkaUnit kafkaServer = new KafkaUnit(5000, 9092);
private static final AtomicInteger topicNum = new AtomicInteger(1);
@BeforeClass
public static void startup() {
kafkaServer.startup();
}
@AfterClass
public static void shutdown() {
kafkaServer.shutdown();
}
@Test
@Ignore
public void testKafkaSourceSingleConsumerReadsAllMessagesInOrderFromSinglePartition() throws InterruptedException {
// TODO modify Local executor to allow for passing in a static PortSelector for the sink port for integration testing and
// countdown latch on receiving message from sink port
String testTopic = "testTopic" + topicNum.incrementAndGet();
int numPartitions = 1;
kafkaServer.createTopic(testTopic, numPartitions);
int numMessages = 1;
AtomicInteger counter = new AtomicInteger();
Schedulers.newThread().createWorker().schedulePeriodically(() -> {
ProducerRecord<String, String> keyedMessage = new ProducerRecord<>(testTopic, "{\"messageNum\":" + counter.incrementAndGet() + "}");
kafkaServer.sendMessages(keyedMessage);
}, 1, 1, TimeUnit.SECONDS);
LocalJobExecutorNetworked.execute(new QueryableKafkaSourceJob().getJobInstance(),
new Parameter(KafkaSourceParameters.TOPIC, testTopic),
new Parameter(KafkaSourceParameters.NUM_KAFKA_CONSUMER_PER_WORKER, "1"),
new Parameter(KafkaSourceParameters.PARSER_TYPE, ParserType.SIMPLE_JSON.getPropName()),
new Parameter(KafkaSourceParameters.PARSE_MSG_IN_SOURCE, "true"),
new Parameter(KafkaSourceParameters.PREFIX + ConsumerConfig.GROUP_ID_CONFIG, "QueryableKafkaSourceLocal"),
new Parameter(KafkaSourceParameters.PREFIX + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"),
new Parameter(KafkaSourceParameters.PREFIX + ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"));
final CountDownLatch latch = new CountDownLatch(numMessages);
assertTrue("timed out waiting to get all messages from Kafka", latch.await(10, TimeUnit.MINUTES));
kafkaServer.deleteTopic(testTopic);
}
}
| 2,689 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/CustomizedAutoAckTaggingStage.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka;
import static io.mantisrx.runtime.parameter.ParameterUtils.STAGE_CONCURRENCY;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.collect.Lists;
import io.mantisrx.connector.kafka.KafkaAckable;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.ScalarToScalar;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import io.mantisrx.runtime.parameter.type.IntParameter;
import io.mantisrx.runtime.parameter.type.StringParameter;
import io.mantisrx.runtime.parameter.validator.Validators;
import io.mantisrx.sourcejob.kafka.core.TaggedData;
import io.mantisrx.sourcejob.kafka.core.utils.JsonUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Func1;
public class CustomizedAutoAckTaggingStage extends AutoAckTaggingStage {
private static Logger logger = LoggerFactory.getLogger(CustomizedAutoAckTaggingStage.class);
private String jobName;
private String timestampField = "_ts_";
private AtomicLong latestTimeStamp = new AtomicLong();
private boolean isFlattenFields = false;
private List<String> fieldsToFlatten = new ArrayList<>();
private Func1<Map<String, Object>, Map<String, Object>> preMapperFunc = t -> t;
@Override
public void init(Context context) {
super.init(context);
jobName = context.getWorkerInfo().getJobName();
String timeStampFieldParam = System.getenv("JOB_PARAM_timeStampField");
if (timeStampFieldParam != null && !timeStampFieldParam.isEmpty()) {
this.timestampField = timeStampFieldParam;
}
String flattenFieldsStr = System.getenv("JOB_PARAM_fieldsToFlatten");
if (flattenFieldsStr != null && !flattenFieldsStr.isEmpty() && !flattenFieldsStr.equals("NONE")) {
String[] fields = flattenFieldsStr.split(",");
if (fields.length > 0) {
isFlattenFields = true;
for (String field : fields) {
fieldsToFlatten.add(field.trim());
}
logger.info("Field flattening enabled for fields {}", fieldsToFlatten);
}
}
}
private void flattenFields(Map<String, Object> rawData) {
for (String field : fieldsToFlatten) {
flattenField(rawData, field);
}
}
private void flattenField(Map<String, Object> rawData, String fieldName) {
String dataJson = (String) rawData.get(fieldName);
try {
Map<String, Object> geoDataMap = JsonUtility.jsonToMap(dataJson);
Iterator<Entry<String, Object>> it = geoDataMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Object> e = it.next();
String key = e.getKey();
Object val = e.getValue();
if (key != null && val != null) {
rawData.put(fieldName + "." + key, val);
}
}
} catch (Exception e) {
logger.warn("Error flattening field " + fieldName + " error -> " + e.getMessage());
}
}
@Override
protected Map<String, Object> applyPreMapping(final Context context, final Map<String, Object> rawData) {
if (rawData == null) {
throw new RuntimeException("rawData is null");
}
long now = System.currentTimeMillis();
if (rawData.containsKey(timestampField)) {
long ts = (Long) rawData.get(timestampField);
long latestTsYet = latestTimeStamp.get();
if (ts > latestTsYet) {
latestTimeStamp.compareAndSet(latestTsYet, ts);
}
// TODO DynamicGauge.set("manits.source.timelag", (now - latestTimeStamp.get()));
}
try {
preMapperFunc.call(rawData);
} catch (Exception e) {
// TODO DynamicCounter.increment("mantis.source.premapping.failed", "mantisJobName", jobName);
logger.warn("Exception applying premapping function " + e.getMessage());
}
final Map<String, Object> modifiedData = new HashMap<>(rawData);
modifiedData.put(MANTIS_META_SOURCE_NAME, jobName);
modifiedData.put(MANTIS_META_SOURCE_TIMESTAMP, now);
if (isFlattenFields) {
flattenFields(modifiedData);
}
return modifiedData;
}
public static ScalarToScalar.Config<KafkaAckable, TaggedData> config() {
ScalarToScalar.Config<KafkaAckable, TaggedData> config = new ScalarToScalar.Config<KafkaAckable, TaggedData>()
.concurrentInput()
.codec(AutoAckTaggingStage.taggedDataCodec())
.withParameters(getParameters());
String jobParamPrefix = "JOB_PARAM_";
String stageConcurrencyParam = jobParamPrefix + STAGE_CONCURRENCY;
String concurrency = System.getenv(stageConcurrencyParam);
if (concurrency != null && !concurrency.isEmpty()) {
logger.info("Job param: " + stageConcurrencyParam + " value: " + concurrency);
try {
config = config.concurrentInput(Integer.parseInt(concurrency));
} catch (NumberFormatException ignored) {
}
}
return config;
}
static List<ParameterDefinition<?>> getParameters() {
List<ParameterDefinition<?>> params = Lists.newArrayList();
// queryable source parameters
params.add(new StringParameter()
.name("fieldsToFlatten")
.description("comma separated list of fields to flatten")
.validator(Validators.notNullOrEmpty())
.defaultValue("NONE")
.build());
params.add(new StringParameter()
.name("timeStampField")
.description("the timestamp field in the event. used to calculate lag")
.validator(Validators.notNullOrEmpty())
.defaultValue("_ts_")
.build());
params.add(new IntParameter()
.name(STAGE_CONCURRENCY)
.description("Parameter to control number of computation workers to use for stage processing")
.defaultValue(1)
.validator(Validators.range(1, 8))
.build());
return params;
}
}
| 2,690 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/AutoAckTaggingStage.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka;
import static io.mantisrx.connector.kafka.source.MantisKafkaSourceConfig.DEFAULT_PARSE_MSG_IN_SOURCE;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import io.mantisrx.connector.kafka.KafkaAckable;
import io.mantisrx.connector.kafka.KafkaSourceParameters;
import io.mantisrx.connector.kafka.source.serde.ParseException;
import io.mantisrx.connector.kafka.source.serde.Parser;
import io.mantisrx.connector.kafka.source.serde.ParserType;
import io.mantisrx.runtime.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AutoAckTaggingStage extends AbstractAckableTaggingStage {
private static final Logger LOG = LoggerFactory.getLogger(AutoAckTaggingStage.class);
public AutoAckTaggingStage() {
}
private static final Logger logger = LoggerFactory.getLogger(AutoAckTaggingStage.class);
/**
* default impl to ack the received data and returned parse kafka data
*
* @param ackable
*
* @return
*/
@Override
protected Map<String, Object> processAndAck(final Context context, KafkaAckable ackable) {
try {
Boolean messageParsedInSource = (Boolean) context.getParameters().get(KafkaSourceParameters.PARSE_MSG_IN_SOURCE, DEFAULT_PARSE_MSG_IN_SOURCE);
String messageParserType = (String) context.getParameters().get(KafkaSourceParameters.PARSER_TYPE, ParserType.SIMPLE_JSON.getPropName());
if (messageParsedInSource) {
final Optional<Map<String, Object>> parsedEventO = ackable.getKafkaData().getParsedEvent();
return parsedEventO.orElse(Collections.emptyMap());
} else {
final Parser parser = ParserType.parser(messageParserType).getParser();
if (parser.canParse(ackable.getKafkaData().getRawBytes())) {
return parser.parseMessage(ackable.getKafkaData().getRawBytes());
} else {
LOG.warn("cannot parse message {}", ackable.getKafkaData().getRawBytes().toString());
throw new ParseException("cannot parse message");
}
}
} catch (Throwable t) {
if (t instanceof ParseException) {
logger.warn("failed to parse message", t);
} else {
logger.error("caught unexpected exception", t);
}
} finally {
ackable.ack();
}
return Collections.emptyMap();
}
// no op
@Override
protected Map<String, Object> preProcess(Map<String, Object> rawData) {
return rawData;
}
}
| 2,691 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/AbstractAckableTaggingStage.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.connector.kafka.KafkaAckable;
import io.mantisrx.mql.jvm.core.Query;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.computation.ScalarComputation;
import io.mantisrx.sourcejob.kafka.core.TaggedData;
import io.mantisrx.sourcejob.kafka.sink.MQLQueryManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
public abstract class AbstractAckableTaggingStage implements ScalarComputation<KafkaAckable, TaggedData> {
public static final String MANTIS_META_IS_COMPLETE_DATA = "mantis.meta.isCompleteData";
public static final String MANTIS_META_SOURCE_NAME = "mantis.meta.sourceName";
public static final String MANTIS_META_SOURCE_TIMESTAMP = "mantis.meta.timestamp";
public static final String MANTIS_QUERY_COUNTER = "mantis_query_out";
public static final String MQL_COUNTER = "mql_out";
public static final String MQL_FAILURE = "mql_failure";
public static final String MQL_CLASSLOADER_ERROR = "mql_classloader_error";
private static final Logger logger = LoggerFactory.getLogger(AbstractAckableTaggingStage.class);
private static final String MANTIS_META = "mantis.meta";
protected AtomicBoolean trackIsComplete = new AtomicBoolean(false);
private AtomicBoolean errorLogged = new AtomicBoolean(false);
public Observable<TaggedData> call(Context context, Observable<KafkaAckable> data) {
context.getMetricsRegistry().registerAndGet(new Metrics.Builder()
.name("mql")
.addCounter(MQL_COUNTER)
.addCounter(MQL_FAILURE)
.addCounter(MQL_CLASSLOADER_ERROR)
.addCounter(MANTIS_QUERY_COUNTER).build());
return data
.map(ackable -> {
Map<String, Object> rawData = processAndAck(context, ackable);
return preProcess(rawData);
})
.filter((d) -> !d.isEmpty())
.map(mapData -> applyPreMapping(context, mapData))
.filter((d) -> !d.isEmpty())
.flatMapIterable(d -> tagData(d, context));
}
protected abstract Map<String, Object> processAndAck(final Context context, KafkaAckable ackable);
protected abstract Map<String, Object> preProcess(final Map<String, Object> rawData);
protected Map<String, Object> applyPreMapping(final Context context, final Map<String, Object> rawData) {
return rawData;
}
private boolean isMetaEvent(Map<String, Object> d) {
return d.containsKey(MANTIS_META_IS_COMPLETE_DATA) || d.containsKey(MANTIS_META);
}
@SuppressWarnings("unchecked")
protected List<TaggedData> tagData(Map<String, Object> d, Context context) {
List<TaggedData> taggedDataList = new ArrayList<>();
boolean metaEvent = isMetaEvent(d);
Metrics metrics = context.getMetricsRegistry().getMetric("mql");
Collection<Query> queries = MQLQueryManager.getInstance().getRegisteredQueries();
Iterator<Query> it = queries.iterator();
while (it.hasNext()) {
Query query = it.next();
try {
if (metaEvent) {
TaggedData tg = new TaggedData(d);
tg.addMatchedClient(query.getSubscriptionId());
taggedDataList.add(tg);
} else if (query.matches(d)) {
Map<String, Object> projected = query.project(d);
projected.put(MANTIS_META_SOURCE_NAME, d.get(MANTIS_META_SOURCE_NAME));
projected.put(MANTIS_META_SOURCE_TIMESTAMP, d.get(MANTIS_META_SOURCE_TIMESTAMP));
TaggedData tg = new TaggedData(projected);
tg.addMatchedClient(query.getSubscriptionId());
taggedDataList.add(tg);
}
} catch (Exception ex) {
if (ex instanceof ClassNotFoundException) {
logger.error("Error loading MQL: " + ex.getMessage());
ex.printStackTrace();
metrics.getCounter(MQL_CLASSLOADER_ERROR).increment();
} else {
ex.printStackTrace();
metrics.getCounter(MQL_FAILURE).increment();
logger.error("MQL Error: " + ex.getMessage());
logger.error("MQL Query: " + query.getRawQuery());
logger.error("MQL Datum: " + d);
}
} catch (Error e) {
metrics.getCounter(MQL_FAILURE).increment();
if (!errorLogged.get()) {
logger.error("caught Error when processing MQL {} on {}", query.getRawQuery(), d.toString(), e);
errorLogged.set(true);
}
}
}
return taggedDataList;
}
public static Codec<TaggedData> taggedDataCodec() {
return new Codec<TaggedData>() {
@Override
public TaggedData decode(byte[] bytes) {
return new TaggedData(new HashMap<>());
}
@Override
public byte[] encode(final TaggedData value) {
return new byte[128];
}
};
}
}
| 2,692 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/QueryableKafkaSourceJob.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka;
import com.netflix.spectator.api.DefaultRegistry;
import io.mantisrx.connector.kafka.KafkaSourceParameters;
import io.mantisrx.connector.kafka.source.KafkaSource;
import io.mantisrx.connector.kafka.source.serde.ParserType;
import io.mantisrx.runtime.Job;
import io.mantisrx.runtime.MantisJob;
import io.mantisrx.runtime.MantisJobProvider;
import io.mantisrx.runtime.executor.LocalJobExecutorNetworked;
import io.mantisrx.runtime.parameter.Parameter;
import io.mantisrx.sourcejob.kafka.core.TaggedData;
import io.mantisrx.sourcejob.kafka.sink.QueryRequestPostProcessor;
import io.mantisrx.sourcejob.kafka.sink.QueryRequestPreProcessor;
import io.mantisrx.sourcejob.kafka.sink.TaggedDataSourceSink;
import org.apache.kafka.clients.consumer.ConsumerConfig;
/**
* Generic queryable source job to connect to configured kafka topic
*/
public class QueryableKafkaSourceJob extends MantisJobProvider<TaggedData> {
protected AutoAckTaggingStage getAckableTaggingStage() {
return new CustomizedAutoAckTaggingStage();
}
@Override
public Job<TaggedData> getJobInstance() {
KafkaSource kafkaSource = new KafkaSource(new DefaultRegistry());
return
MantisJob // kafkaSource to connect to kafka and stream events from the configured topic
.source(kafkaSource)
.stage(getAckableTaggingStage(), CustomizedAutoAckTaggingStage.config())
.sink(new TaggedDataSourceSink(new QueryRequestPreProcessor(), new QueryRequestPostProcessor()))
// required parameters
.create();
}
public static void main(String[] args) {
LocalJobExecutorNetworked.execute(new QueryableKafkaSourceJob().getJobInstance(),
new Parameter(KafkaSourceParameters.TOPIC, "nf_errors_log"),
new Parameter(KafkaSourceParameters.NUM_KAFKA_CONSUMER_PER_WORKER, "1"),
new Parameter(KafkaSourceParameters.PARSER_TYPE, ParserType.SIMPLE_JSON.getPropName()),
new Parameter(KafkaSourceParameters.PARSE_MSG_IN_SOURCE, "true"),
new Parameter(KafkaSourceParameters.PREFIX + ConsumerConfig.GROUP_ID_CONFIG, "QueryableKafkaSourceLocal"),
new Parameter(KafkaSourceParameters.PREFIX + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "100.66.49.176:7102"),
new Parameter(KafkaSourceParameters.PREFIX + ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest"));
}
}
| 2,693 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/core/TaggedData.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka.core;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.mantisrx.runtime.codec.JsonType;
public class TaggedData implements JsonType {
private final Set<String> matchedClients = new HashSet<String>();
private Map<String, Object> payLoad;
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown = true)
public TaggedData(@JsonProperty("data") Map<String, Object> data) {
this.payLoad = data;
}
public Set<String> getMatchedClients() {
return matchedClients;
}
public boolean matchesClient(String clientId) {
return matchedClients.contains(clientId);
}
public void addMatchedClient(String clientId) {
matchedClients.add(clientId);
}
public Map<String, Object> getPayload() {
return this.payLoad;
}
public void setPayload(Map<String, Object> newPayload) {
this.payLoad = newPayload;
}
}
| 2,694 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/core | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/core/utils/SourceJobConstants.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka.core.utils;
public class SourceJobConstants {
public static final String SUBSCRIPTION_ID_PARAM_NAME = "subscriptionId";
public static final String CRITERION_PARAM_NAME = "criterion";
public static final String FILTER_PARAM_NAME = "filter";
public static final String CLIENT_ID_PARAMETER_NAME = "clientId";
}
| 2,695 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/core | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/core/utils/JsonUtility.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka.core.utils;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
public class JsonUtility {
private static final JsonUtility INSTANCE = new JsonUtility();
private JsonUtility() {}
public static Map<String, Object> jsonToMap(String jsonString) {
return INSTANCE._jsonToMap(jsonString);
}
public static String mapToJson(Map<String, ? extends Object> map) {
return INSTANCE._mapToJson(map);
}
private final ObjectMapper objectMapper = new ObjectMapper();
private final ObjectReader objectReader = objectMapper.readerFor(Map.class);
private Map<String, Object> _jsonToMap(String jsonString) {
try {
return objectReader.readValue(jsonString);
} catch (IOException e) {
throw new RuntimeException("Unable to parse JSON", e);
}
}
private final ObjectWriter objectWriter = objectMapper.writerFor(Map.class);
private String _mapToJson(Map<String, ? extends Object> map) {
try {
return objectWriter.writeValueAsString(map);
} catch (IOException e) {
throw new RuntimeException("Unable to write JSON", e);
}
}
} | 2,696 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/sink/QueryRequestPostProcessor.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka.sink;
import static io.mantisrx.sourcejob.kafka.core.utils.SourceJobConstants.CRITERION_PARAM_NAME;
import static io.mantisrx.sourcejob.kafka.core.utils.SourceJobConstants.SUBSCRIPTION_ID_PARAM_NAME;
import java.util.List;
import java.util.Map;
import io.mantisrx.runtime.Context;
import org.apache.log4j.Logger;
import rx.functions.Func2;
public class QueryRequestPostProcessor implements Func2<Map<String, List<String>>, Context, Void> {
private static Logger logger = Logger.getLogger(QueryRequestPostProcessor.class);
public QueryRequestPostProcessor() { }
@Override
public Void call(Map<String, List<String>> queryParams, Context context) {
logger.info("RequestPostProcessor:queryParams: " + queryParams);
if (queryParams != null) {
if (queryParams.containsKey(SUBSCRIPTION_ID_PARAM_NAME) && queryParams.containsKey(CRITERION_PARAM_NAME)) {
final String subId = queryParams.get(SUBSCRIPTION_ID_PARAM_NAME).get(0);
final String query = queryParams.get(CRITERION_PARAM_NAME).get(0);
final String clientId = queryParams.get("clientId").get(0);
if (subId != null && query != null) {
try {
if (clientId != null && !clientId.isEmpty()) {
deregisterQuery(clientId + "_" + subId);
} else {
deregisterQuery(subId);
}
// TODO - DynamicGauge.set("activeQueries", BasicTagList.of("mantisJobId", context.getJobId(),
// "mantisJobName",context.getWorkerInfo().getJobName()), (double) MQLQueryManager.getInstance().getRegisteredQueries().size());
} catch (Throwable t) {
logger.error("Error propagating unsubscription notification", t);
}
}
}
}
return null;
}
private void deregisterQuery(String subId) {
QueryRefCountMap.INSTANCE.removeQuery(subId);
}
}
| 2,697 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/sink/MQL.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka.sink;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import io.mantisrx.mql.jvm.core.Query;
import io.mantisrx.mql.shaded.clojure.java.api.Clojure;
import io.mantisrx.mql.shaded.clojure.lang.IFn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.functions.Func1;
/**
* The MQL class provides a Java/Scala friendly static interface to MQL functionality which is written in Clojure.
* This class provides a few pieces of functionality;
* - It wraps the Clojure interop so that the user interacts with typed methods via the static interface.
* - It provides methods for accessing individual bits of query functionality, allowing interesting uses
* such as aggregator-mql which uses these components to implement the query in a horizontally scalable / distributed
* fashion on Mantis.
* - It functions as an Rx Transformer of MantisServerSentEvent to MQLResult allowing a user to inline all MQL
* functionality quickly as such: `myObservable.compose(MQL.parse(myQuery));`
*/
public class MQL {
//
// Clojure Interop
//
private static IFn require = Clojure.var("io.mantisrx.mql.shaded.clojure.core", "require");
static {
require.invoke(Clojure.read("io.mantisrx.mql.jvm.interfaces.core"));
require.invoke(Clojure.read("io.mantisrx.mql.jvm.interfaces.server"));
}
private static IFn cljMakeQuery = Clojure.var("io.mantisrx.mql.jvm.interfaces.server", "make-query");
private static IFn cljSuperset = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "queries->superset-projection");
private static IFn parser = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "parser");
private static IFn parses = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "parses?");
private static IFn getParseError = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "get-parse-error");
private static IFn queryToGroupByFn = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->groupby");
private static IFn queryToHavingPred = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->having-pred");
private static IFn queryToOrderBy = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->orderby");
private static IFn queryToLimit = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->limit");
private static IFn queryToExtrapolationFn = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->extrapolator");
private static IFn queryToAggregateFn = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "agg-query->projection");
private static IFn queryToWindow = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->window");
private static Logger logger = LoggerFactory.getLogger(MQL.class);
private static ConcurrentHashMap<HashSet<Query>, IFn> superSetProjectorCache = new ConcurrentHashMap<>();
private final String query;
private final boolean threadingEnabled;
private final Optional<String> sourceJobName;
public static void init() {
logger.info("Initializing MQL runtime.");
}
//
// Constructors and Static Factory Methods
//
public MQL(String query, boolean threadingEnabled) {
if (query == null) {
throw new IllegalArgumentException("MQL cannot be used as an operator with a null query.");
}
this.query = transformLegacyQuery(query);
if (!parses(query)) {
throw new IllegalArgumentException(getParseError(query));
}
this.threadingEnabled = threadingEnabled;
this.sourceJobName = Optional.empty();
}
public MQL(String query, String sourceJobName) {
if (query == null) {
throw new IllegalArgumentException("MQL cannot be used as an operator with a null query.");
}
this.query = transformLegacyQuery(query);
if (!parses(query)) {
throw new IllegalArgumentException(getParseError(query));
}
this.threadingEnabled = false;
this.sourceJobName = Optional.ofNullable(sourceJobName);
}
public static MQL parse(String query) {
return new MQL(query, false);
}
public static MQL parse(String query, boolean threadingEnabled) { return new MQL(query, threadingEnabled); }
public static MQL parse(String query, String sourceName) { return new MQL(query, sourceName); }
//
// Source Job Integration
//
/**
* Constructs an object implementing the Query interface.
* This includes functions;
* matches (Map<String, Object>>) -> Boolean
* Returns true iff the data contained within the map parameter satisfies the query's WHERE clause.
* project (Map<String, Object>>) -> Map<String, Object>>
* Returns the provided map in accordance with the SELECT clause of the query.
* sample (Map<String, Object>>) -> Boolean
* Returns true if the data should be sampled, this function is a tautology if no SAMPLE clause is provided.
*
* @param subscriptionId The ID representing the subscription.
* @param query The (valid) MQL query to parse.
*
* @return An object implementing the Query interface.
*/
public static Query makeQuery(String subscriptionId, String query) {
/*
if (!parses(query)) {
String error = getParseError(query);
logger.error("Failed to parse query [" + query + "]\nError: " + error + ".");
throw new IllegalArgumentException(error);
}
*/
return (Query) cljMakeQuery.invoke(subscriptionId, query.trim());
}
@SuppressWarnings("unchecked")
private static IFn computeSuperSetProjector(HashSet<Query> queries) {
ArrayList<String> qs = new ArrayList<>(queries.size());
for (Query query : queries) {
qs.add(query.getRawQuery());
}
return (IFn) cljSuperset.invoke(new ArrayList(qs));
}
/**
* Projects a single Map<String, Object> which contains a superset of all fields for the provided queries.
* This is useful in use cases such as the mantis-realtime-events library in which we desire to minimize the data
* egressed off box. This should minimize JSON serialization time as well as network bandwidth used to transmit
* the events.
* <p>
* NOTE: This function caches the projectors for performance reasons, this has implications for memory usage as each
* combination of queries results in a new cached function. In practice this has had little impact for <= 100
* queries.
*
* @param queries A Collection of Query objects generated using #makeQuery(String subscriptionId, String query).
* @param datum A Map representing the input event to be projected.
*
* @return A Map representing the union (superset) of all fields required for processing all queries passed in.
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> projectSuperSet(Collection<Query> queries, Map<String, Object> datum) {
IFn superSetProjector = superSetProjectorCache.computeIfAbsent(new HashSet<Query>(queries), (qs) -> {
return computeSuperSetProjector(qs);
});
return (Map<String, Object>) superSetProjector.invoke(datum);
}
//
// Partial Query Functionality
//
public static Func1<Map<String, Object>, Object> getGroupByFn(String query) {
IFn func = (IFn) queryToGroupByFn.invoke(query);
return func::invoke;
}
@SuppressWarnings("unchecked")
public static Func1<Map<String, Object>, Boolean> getHavingPredicate(String query) {
IFn func = (IFn) queryToHavingPred.invoke(query);
return (datum) -> (Boolean) func.invoke(datum);
}
@SuppressWarnings("unchecked")
public static Func1<Observable<Map<String, Object>>, Observable<Map<String, Object>>> getAggregateFn(String query) {
IFn func = (IFn) queryToAggregateFn.invoke(query);
return (obs) -> (Observable<Map<String, Object>>) func.invoke(obs);
}
@SuppressWarnings("unchecked")
public static Func1<Map<String, Object>, Map<String, Object>> getExtrapolationFn(String query) {
IFn func = (IFn) queryToExtrapolationFn.invoke(query);
return (datum) -> (Map<String, Object>) func.invoke(datum);
}
@SuppressWarnings("unchecked")
public static Func1<Observable<Map<String, Object>>, Observable<Map<String, Object>>> getOrderBy(String query) {
IFn func = (IFn) queryToOrderBy.invoke(query);
return obs -> (Observable<Map<String, Object>>) func.invoke(obs);
}
// public static List<Long> getWindow(String query) {
// clojure.lang.PersistentVector result = (clojure.lang.PersistentVector)queryToWindow.invoke(query);
// Long window = (Long)result.nth(0);
// Long shift = (Long)result.nth(1);
// return Arrays.asList(window, shift);
// }
public static Long getLimit(String query) {
return (Long) queryToLimit.invoke(query);
}
//
// Helper Functions
//
/**
* A predicate which indicates whether or not the MQL parser considers query to be a valid query.
*
* @param query A String representing the MQL query.
*
* @return A boolean indicating whether or not the query successfully parses.
*/
public static Boolean parses(String query) {
return (Boolean) parses.invoke(query);
}
/**
* A convenience function allowing a caller to determine what went wrong if a call to #parses(String query) returns
* false.
*
* @param query A String representing the MQL query.
*
* @return A String representing the parse error for an MQL query, null if no parse error occurred.
*/
public static String getParseError(String query) {
return (String) getParseError.invoke(query);
}
/**
* A helper which converts bare true/false queries to MQL.
*
* @param criterion A Mantis Query (old query language) query.
*
* @return A valid MQL query string assuming the input was valid.
*/
public static String transformLegacyQuery(String criterion) {
return criterion.toLowerCase().equals("true") ? "select * where true" :
criterion.toLowerCase().equals("false") ? "select * where false" :
criterion;
}
public static void main(String[] args) {
System.out.println(MQL.makeQuery("abc", "select * from stream where true"));
}
}
| 2,698 |
0 | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka | Create_ds/mantis-source-jobs/kafka-source-job/src/main/java/io/mantisrx/sourcejob/kafka/sink/TaggedDataSourceSink.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.sourcejob.kafka.sink;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.PortRequest;
import io.mantisrx.runtime.sink.ServerSentEventsSink;
import io.mantisrx.runtime.sink.Sink;
import io.mantisrx.runtime.sink.predicate.Predicate;
import io.mantisrx.sourcejob.kafka.core.TaggedData;
import rx.Observable;
import rx.functions.Func2;
public class TaggedDataSourceSink implements Sink<TaggedData> {
private Func2<Map<String, List<String>>, Context, Void> preProcessor = new NoOpProcessor();
private Func2<Map<String, List<String>>, Context, Void> postProcessor = new NoOpProcessor();
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static class NoOpProcessor implements Func2<Map<String, List<String>>, Context, Void> {
@Override
public Void call(Map<String, List<String>> t1, Context t2) {
return null;
}
}
public TaggedDataSourceSink() {
}
public TaggedDataSourceSink(Func2<Map<String, List<String>>, Context, Void> preProcessor,
Func2<Map<String, List<String>>, Context, Void> postProcessor) {
this.postProcessor = postProcessor;
this.preProcessor = preProcessor;
}
@Override
public void call(Context context, PortRequest portRequest,
Observable<TaggedData> observable) {
observable = observable
.filter((t1) -> !t1.getPayload().isEmpty());
ServerSentEventsSink<TaggedData> sink = new ServerSentEventsSink.Builder<TaggedData>()
.withEncoder((data) -> {
try {
String json = OBJECT_MAPPER.writeValueAsString(data.getPayload());
return json;
} catch (JsonProcessingException e) {
e.printStackTrace();
return "{\"error\":" + e.getMessage() + "}";
}
})
.withPredicate(new Predicate<TaggedData>("description", new TaggedEventFilter()))
.withRequestPreprocessor(preProcessor)
.withRequestPostprocessor(postProcessor)
.build();
observable.subscribe();
sink.call(context, portRequest, observable);
}
}
| 2,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.