repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmap.java
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import android.graphics.Canvas; import android.view.View; import com.orange.dgil.trail.android.animation.AnimManager; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; class QuillTrailBitmap implements IDrawingTool { private final View view;
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmap.java import android.graphics.Canvas; import android.view.View; import com.orange.dgil.trail.android.animation.AnimManager; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; class QuillTrailBitmap implements IDrawingTool { private final View view;
private final AnimManager animManager;
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmap.java
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import android.graphics.Canvas; import android.view.View; import com.orange.dgil.trail.android.animation.AnimManager; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; class QuillTrailBitmap implements IDrawingTool { private final View view; private final AnimManager animManager; private final BitmapDrawer bitmapDrawer; private final QuillBitmap quillBitmap; private final TrailBounds trailBounds; private final QuillTrailBitmapListener quillTrailBitmapListener; private final QuadCurveArray quadCurveArray; private boolean shouldDrawTrailEnd; private boolean inGesture; private int readIndex;
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmap.java import android.graphics.Canvas; import android.view.View; import com.orange.dgil.trail.android.animation.AnimManager; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; class QuillTrailBitmap implements IDrawingTool { private final View view; private final AnimManager animManager; private final BitmapDrawer bitmapDrawer; private final QuillBitmap quillBitmap; private final TrailBounds trailBounds; private final QuillTrailBitmapListener quillTrailBitmapListener; private final QuadCurveArray quadCurveArray; private boolean shouldDrawTrailEnd; private boolean inGesture; private int readIndex;
QuillTrailBitmap(DrawingToolsContext drawingToolsContext, BitmapDrawer bitmapDrawer, QuadCurveArray quadCurveArray, QuillTrailBitmapListener quillTrailBitmapListener) {
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmap.java
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import android.graphics.Canvas; import android.view.View; import com.orange.dgil.trail.android.animation.AnimManager; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray;
this.animManager = drawingToolsContext.getAnimManager(); this.quadCurveArray = quadCurveArray; this.bitmapDrawer = bitmapDrawer; this.quillTrailBitmapListener = quillTrailBitmapListener; quillBitmap = new QuillBitmap(view); trailBounds = new TrailBounds(drawingToolsContext.getTrailOptions().getQuillParameters(), quadCurveArray.getTrailRect()); } @Override public void reset() { if (quillBitmap.isLoaded()) { readIndex = 0; quillBitmap.reset(); } } @Override public void trimMemory() { quillBitmap.releaseBitmap(); } @Override public void forceRedrawForAnimation(boolean eraseBitmap) { quillBitmap.lazyLoading(); bitmapDrawer.forceColor(animManager.getAnimColor()); if (eraseBitmap) { quillBitmap.reset(); } for (int i = 0; i <= quadCurveArray.getLastPointIndex(); i++) {
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmap.java import android.graphics.Canvas; import android.view.View; import com.orange.dgil.trail.android.animation.AnimManager; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray; this.animManager = drawingToolsContext.getAnimManager(); this.quadCurveArray = quadCurveArray; this.bitmapDrawer = bitmapDrawer; this.quillTrailBitmapListener = quillTrailBitmapListener; quillBitmap = new QuillBitmap(view); trailBounds = new TrailBounds(drawingToolsContext.getTrailOptions().getQuillParameters(), quadCurveArray.getTrailRect()); } @Override public void reset() { if (quillBitmap.isLoaded()) { readIndex = 0; quillBitmap.reset(); } } @Override public void trimMemory() { quillBitmap.releaseBitmap(); } @Override public void forceRedrawForAnimation(boolean eraseBitmap) { quillBitmap.lazyLoading(); bitmapDrawer.forceColor(animManager.getAnimColor()); if (eraseBitmap) { quillBitmap.reset(); } for (int i = 0; i <= quadCurveArray.getLastPointIndex(); i++) {
TrailPoint point = quadCurveArray.get(i);
kendzi/kendzi-math
kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LineSegment2d.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector2dUtil.java // public class Vector2dUtil { // // private static double EPSILON = 0.00000001; // // public static Vector2d orthogonalLeft(Vector2d v) { // return new Vector2d(-v.y, v.x); // } // // public static Vector2d orthogonalRight(Vector2d v) { // return new Vector2d(v.y, -v.x); // } // // public static Vector2d bisector(Point2d p1, Point2d p2, Point2d p3) { // left // // XXX rename to bisectorLeft // return Vector2dUtil.bisector(Vector2dUtil.fromTo(p1, p2), Vector2dUtil.fromTo(p2, p3)); // } // // public static Vector2d bisector(Vector2d v1, Vector2d v2) { // // XXX rename to bisectorLeft // Vector2d norm1 = new Vector2d(v1); // norm1.normalize(); // // Vector2d norm2 = new Vector2d(v2); // norm2.normalize(); // // return bisectorNormalized(norm1, norm2); // } // // public static Vector2d bisectorNormalized(Vector2d norm1, Vector2d norm2) { // Vector2d e1v = orthogonalLeft(norm1); // Vector2d e2v = orthogonalLeft(norm2); // // // 90 - 180 || 180 - 270 // // if (norm1.dot(e2v) <= 0 && ) { //XXX >= !! // if (norm1.dot(norm2) > 0) { // // e1v.add(e2v); // return e1v; // // } // // // 0 - 180 // Vector2d ret = new Vector2d(norm1); // ret.negate(); // ret.add(norm2); // // if (e1v.dot(norm2) < 0) { // // 270 - 360 // ret.negate(); // } // return ret; // } // // private static boolean equalsEpsilon(double pNumber) { // if ((pNumber < 0 ? -pNumber : pNumber) > EPSILON) { // return false; // } // return false; // // } // // /** // * Cross product for 2d is same as doc // * // * @param u // * @param v // * @return // * @see {http://mathworld.wolfram.com/CrossProduct.html} // */ // public static double cross(Tuple2d u, Tuple2d v) { // return u.x * v.y - u.y * v.x; // } // // public static Vector2d fromTo(Point2d begin, Point2d end) { // return new Vector2d(end.x - begin.x, end.y - begin.y); // } // // public static Vector2d negate(Vector2d vector) { // return new Vector2d(-vector.x, -vector.y); // } // // }
import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import kendzi.math.geometry.point.Vector2dUtil;
package kendzi.math.geometry.line; public class LineSegment2d { Point2d begin; Point2d end; /** * XXX is need ? */ boolean openBegin; /** * XXX is need ? */ boolean openEnd; public LineSegment2d(Point2d begin, Point2d end) { super(); this.begin = begin; this.end = end; } /** Collision point of line and line segment. * @param x1 line segment begin point x * @param y1 line segment begin point y * @param x2 line segment end point x * @param y2 line segment end point y * * @param A line in linear form parameter A * @param B line in linear form parameter B * @param C line in linear form parameter C * * XXX better name is intersects ?! * @return collision point */ public static Point2d collide(double x1, double y1, double x2, double y2, double A, double B, double C ) { // XXX TODO FIXME when end of line segment is lies on line if (det(x1, y1, A, B, C) * det(x2, y2, A, B, C) < 0) { double A2 = y1 - y2; double B2 = x2 - x1; double C2 = x1 * y2 - x2 * y1; return LineLinear2d.collide(A, B, C, A2, B2, C2); } return null; } public Point2d intersect(LineSegment2d lineSegment) {
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector2dUtil.java // public class Vector2dUtil { // // private static double EPSILON = 0.00000001; // // public static Vector2d orthogonalLeft(Vector2d v) { // return new Vector2d(-v.y, v.x); // } // // public static Vector2d orthogonalRight(Vector2d v) { // return new Vector2d(v.y, -v.x); // } // // public static Vector2d bisector(Point2d p1, Point2d p2, Point2d p3) { // left // // XXX rename to bisectorLeft // return Vector2dUtil.bisector(Vector2dUtil.fromTo(p1, p2), Vector2dUtil.fromTo(p2, p3)); // } // // public static Vector2d bisector(Vector2d v1, Vector2d v2) { // // XXX rename to bisectorLeft // Vector2d norm1 = new Vector2d(v1); // norm1.normalize(); // // Vector2d norm2 = new Vector2d(v2); // norm2.normalize(); // // return bisectorNormalized(norm1, norm2); // } // // public static Vector2d bisectorNormalized(Vector2d norm1, Vector2d norm2) { // Vector2d e1v = orthogonalLeft(norm1); // Vector2d e2v = orthogonalLeft(norm2); // // // 90 - 180 || 180 - 270 // // if (norm1.dot(e2v) <= 0 && ) { //XXX >= !! // if (norm1.dot(norm2) > 0) { // // e1v.add(e2v); // return e1v; // // } // // // 0 - 180 // Vector2d ret = new Vector2d(norm1); // ret.negate(); // ret.add(norm2); // // if (e1v.dot(norm2) < 0) { // // 270 - 360 // ret.negate(); // } // return ret; // } // // private static boolean equalsEpsilon(double pNumber) { // if ((pNumber < 0 ? -pNumber : pNumber) > EPSILON) { // return false; // } // return false; // // } // // /** // * Cross product for 2d is same as doc // * // * @param u // * @param v // * @return // * @see {http://mathworld.wolfram.com/CrossProduct.html} // */ // public static double cross(Tuple2d u, Tuple2d v) { // return u.x * v.y - u.y * v.x; // } // // public static Vector2d fromTo(Point2d begin, Point2d end) { // return new Vector2d(end.x - begin.x, end.y - begin.y); // } // // public static Vector2d negate(Vector2d vector) { // return new Vector2d(-vector.x, -vector.y); // } // // } // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LineSegment2d.java import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import kendzi.math.geometry.point.Vector2dUtil; package kendzi.math.geometry.line; public class LineSegment2d { Point2d begin; Point2d end; /** * XXX is need ? */ boolean openBegin; /** * XXX is need ? */ boolean openEnd; public LineSegment2d(Point2d begin, Point2d end) { super(); this.begin = begin; this.end = end; } /** Collision point of line and line segment. * @param x1 line segment begin point x * @param y1 line segment begin point y * @param x2 line segment end point x * @param y2 line segment end point y * * @param A line in linear form parameter A * @param B line in linear form parameter B * @param C line in linear form parameter C * * XXX better name is intersects ?! * @return collision point */ public static Point2d collide(double x1, double y1, double x2, double y2, double A, double B, double C ) { // XXX TODO FIXME when end of line segment is lies on line if (det(x1, y1, A, B, C) * det(x2, y2, A, B, C) < 0) { double A2 = y1 - y2; double B2 = x2 - x1; double C2 = x1 * y2 - x2 * y1; return LineLinear2d.collide(A, B, C, A2, B2, C2); } return null; } public Point2d intersect(LineSegment2d lineSegment) {
Vector2d v1 = Vector2dUtil.fromTo(this.begin, this.end);
kendzi/kendzi-math
kendzi-straight-skeleton/src/test/java/kendzi/math/geometry/skeleton/path/FaceQueueUtilTest.java
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // }
import org.junit.Test; import static org.junit.Assert.*; import javax.vecmath.Point2d; import kendzi.math.geometry.skeleton.circular.Edge;
@Test(expected = IllegalStateException.class) public void test5() { FaceNode n1 = debugNewQueue("n1", true); FaceNode n2 = debugNewQueue("n2", true); n1.addPush(n2); fail(); } private FaceNode debugNode(final String name) { return new FaceNode(null) { @Override public String toString() { return name; } }; } private FaceNode debugNewQueue(final String name, boolean edge) { FaceQueue fq = new FaceQueue(); FaceNode fn = new FaceNode(null) { @Override public String toString() { return name; } }; fq.addFirst(fn); if (edge) {
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // } // Path: kendzi-straight-skeleton/src/test/java/kendzi/math/geometry/skeleton/path/FaceQueueUtilTest.java import org.junit.Test; import static org.junit.Assert.*; import javax.vecmath.Point2d; import kendzi.math.geometry.skeleton.circular.Edge; @Test(expected = IllegalStateException.class) public void test5() { FaceNode n1 = debugNewQueue("n1", true); FaceNode n2 = debugNewQueue("n2", true); n1.addPush(n2); fail(); } private FaceNode debugNode(final String name) { return new FaceNode(null) { @Override public String toString() { return name; } }; } private FaceNode debugNewQueue(final String name, boolean edge) { FaceQueue fq = new FaceQueue(); FaceNode fn = new FaceNode(null) { @Override public String toString() { return name; } }; fq.addFirst(fn); if (edge) {
fq.setEdge(new Edge(new Point2d(), new Point2d()));
kendzi/kendzi-math
kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/events/chains/ChainEnds.java
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java // public class Vertex extends CircularNode { // // private Point2d point; // // private double distance; // // private boolean processed; // // private Ray2d bisector; // // /** // * Previous edge. // */ // public Edge previousEdge; // // /** // * Next edge. // */ // public Edge nextEdge; // // public FaceNode leftFace; // // public FaceNode rightFace; // // public Vertex(Point2d point, double distance, Ray2d bisector, Edge previousEdge, Edge nextEdge) { // super(); // this.point = point; // this.distance = distance; // this.bisector = bisector; // this.previousEdge = previousEdge; // this.nextEdge = nextEdge; // // processed = false; // } // // public Vertex() { // // TODO Auto-generated constructor stub // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "VertexEntry [v=" + this.point + ", processed=" + this.processed + ", bisector=" + this.bisector // + ", previousEdge=" + this.previousEdge + ", nextEdge=" + this.nextEdge; // } // // @Override // public Vertex next() { // return (Vertex) super.next(); // } // // @Override // public Vertex previous() { // return (Vertex) super.previous(); // } // // public Point2d getPoint() { // return point; // } // // public double getDistance() { // return distance; // } // // public boolean isProcessed() { // return processed; // } // // public Ray2d getBisector() { // return bisector; // } // // public Edge getPreviousEdge() { // return previousEdge; // } // // public Edge getNextEdge() { // return nextEdge; // } // // public FaceNode getLeftFace() { // return leftFace; // } // // public FaceNode getRightFace() { // return rightFace; // } // // public void setProcessed(boolean processed) { // this.processed = processed; // } // // @Deprecated // public void setBisector(Ray2d bisector) { // this.bisector = bisector; // } // // }
import kendzi.math.geometry.skeleton.circular.Edge; import kendzi.math.geometry.skeleton.circular.Vertex;
package kendzi.math.geometry.skeleton.events.chains; public interface ChainEnds { public Edge getPreviousEdge(); public Edge getNextEdge();
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java // public class Vertex extends CircularNode { // // private Point2d point; // // private double distance; // // private boolean processed; // // private Ray2d bisector; // // /** // * Previous edge. // */ // public Edge previousEdge; // // /** // * Next edge. // */ // public Edge nextEdge; // // public FaceNode leftFace; // // public FaceNode rightFace; // // public Vertex(Point2d point, double distance, Ray2d bisector, Edge previousEdge, Edge nextEdge) { // super(); // this.point = point; // this.distance = distance; // this.bisector = bisector; // this.previousEdge = previousEdge; // this.nextEdge = nextEdge; // // processed = false; // } // // public Vertex() { // // TODO Auto-generated constructor stub // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "VertexEntry [v=" + this.point + ", processed=" + this.processed + ", bisector=" + this.bisector // + ", previousEdge=" + this.previousEdge + ", nextEdge=" + this.nextEdge; // } // // @Override // public Vertex next() { // return (Vertex) super.next(); // } // // @Override // public Vertex previous() { // return (Vertex) super.previous(); // } // // public Point2d getPoint() { // return point; // } // // public double getDistance() { // return distance; // } // // public boolean isProcessed() { // return processed; // } // // public Ray2d getBisector() { // return bisector; // } // // public Edge getPreviousEdge() { // return previousEdge; // } // // public Edge getNextEdge() { // return nextEdge; // } // // public FaceNode getLeftFace() { // return leftFace; // } // // public FaceNode getRightFace() { // return rightFace; // } // // public void setProcessed(boolean processed) { // this.processed = processed; // } // // @Deprecated // public void setBisector(Ray2d bisector) { // this.bisector = bisector; // } // // } // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/events/chains/ChainEnds.java import kendzi.math.geometry.skeleton.circular.Edge; import kendzi.math.geometry.skeleton.circular.Vertex; package kendzi.math.geometry.skeleton.events.chains; public interface ChainEnds { public Edge getPreviousEdge(); public Edge getNextEdge();
public Vertex getPreviousVertex();
kendzi/kendzi-math
kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/ray/Ray2d.java // public class Ray2d extends LineParametric2d { // public Ray2d(Point2d pA, Vector2d pU) { // super(pA, pU); // } // // public static Point2d collide(Ray2d ray, LineLinear2d line, double epsilon) { // // FIXME rewrite? // Point2d collide = LineLinear2d.collide(ray.getLinearForm(), line); // if (collide == null) { // return null; // } // // /* // * Portably there is better way to do this. this is from graphical. // */ // Vector2d collideVector = new Vector2d(collide); // collideVector.sub(ray.A); // // double dot = ray.U.dot(collideVector); // // if (dot < epsilon) { // return null; // } // // return collide; // } // // @Override // public String toString() { // return "Ray2d [A=" + A + ", U=" + U + "]"; // } // // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/path/FaceNode.java // public class FaceNode extends PathQueueNode<FaceNode> { // // private Vertex vertex; // // public FaceNode(Vertex vertex) { // super(); // this.vertex = vertex; // } // // public Vertex getVertex() { // return vertex; // } // // public boolean isQueueClosed() { // FaceQueue fq = getFaceQueue(); // return fq.isClosed(); // } // // public FaceQueue getFaceQueue() { // return (FaceQueue) list(); // } // // public boolean isQueueUnconnected() { // FaceQueue fq = getFaceQueue(); // return fq.isUnconnected(); // } // // public void queueClose() { // getFaceQueue().close(); // // TODO Auto-generated method stub // // } // // }
import javax.vecmath.Point2d; import kendzi.math.geometry.ray.Ray2d; import kendzi.math.geometry.skeleton.path.FaceNode;
package kendzi.math.geometry.skeleton.circular; /** * @author kendzi * */ public class Vertex extends CircularNode { private Point2d point; private double distance; private boolean processed;
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/ray/Ray2d.java // public class Ray2d extends LineParametric2d { // public Ray2d(Point2d pA, Vector2d pU) { // super(pA, pU); // } // // public static Point2d collide(Ray2d ray, LineLinear2d line, double epsilon) { // // FIXME rewrite? // Point2d collide = LineLinear2d.collide(ray.getLinearForm(), line); // if (collide == null) { // return null; // } // // /* // * Portably there is better way to do this. this is from graphical. // */ // Vector2d collideVector = new Vector2d(collide); // collideVector.sub(ray.A); // // double dot = ray.U.dot(collideVector); // // if (dot < epsilon) { // return null; // } // // return collide; // } // // @Override // public String toString() { // return "Ray2d [A=" + A + ", U=" + U + "]"; // } // // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/path/FaceNode.java // public class FaceNode extends PathQueueNode<FaceNode> { // // private Vertex vertex; // // public FaceNode(Vertex vertex) { // super(); // this.vertex = vertex; // } // // public Vertex getVertex() { // return vertex; // } // // public boolean isQueueClosed() { // FaceQueue fq = getFaceQueue(); // return fq.isClosed(); // } // // public FaceQueue getFaceQueue() { // return (FaceQueue) list(); // } // // public boolean isQueueUnconnected() { // FaceQueue fq = getFaceQueue(); // return fq.isUnconnected(); // } // // public void queueClose() { // getFaceQueue().close(); // // TODO Auto-generated method stub // // } // // } // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java import javax.vecmath.Point2d; import kendzi.math.geometry.ray.Ray2d; import kendzi.math.geometry.skeleton.path.FaceNode; package kendzi.math.geometry.skeleton.circular; /** * @author kendzi * */ public class Vertex extends CircularNode { private Point2d point; private double distance; private boolean processed;
private Ray2d bisector;
kendzi/kendzi-math
kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/ray/Ray2d.java // public class Ray2d extends LineParametric2d { // public Ray2d(Point2d pA, Vector2d pU) { // super(pA, pU); // } // // public static Point2d collide(Ray2d ray, LineLinear2d line, double epsilon) { // // FIXME rewrite? // Point2d collide = LineLinear2d.collide(ray.getLinearForm(), line); // if (collide == null) { // return null; // } // // /* // * Portably there is better way to do this. this is from graphical. // */ // Vector2d collideVector = new Vector2d(collide); // collideVector.sub(ray.A); // // double dot = ray.U.dot(collideVector); // // if (dot < epsilon) { // return null; // } // // return collide; // } // // @Override // public String toString() { // return "Ray2d [A=" + A + ", U=" + U + "]"; // } // // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/path/FaceNode.java // public class FaceNode extends PathQueueNode<FaceNode> { // // private Vertex vertex; // // public FaceNode(Vertex vertex) { // super(); // this.vertex = vertex; // } // // public Vertex getVertex() { // return vertex; // } // // public boolean isQueueClosed() { // FaceQueue fq = getFaceQueue(); // return fq.isClosed(); // } // // public FaceQueue getFaceQueue() { // return (FaceQueue) list(); // } // // public boolean isQueueUnconnected() { // FaceQueue fq = getFaceQueue(); // return fq.isUnconnected(); // } // // public void queueClose() { // getFaceQueue().close(); // // TODO Auto-generated method stub // // } // // }
import javax.vecmath.Point2d; import kendzi.math.geometry.ray.Ray2d; import kendzi.math.geometry.skeleton.path.FaceNode;
package kendzi.math.geometry.skeleton.circular; /** * @author kendzi * */ public class Vertex extends CircularNode { private Point2d point; private double distance; private boolean processed; private Ray2d bisector; /** * Previous edge. */ public Edge previousEdge; /** * Next edge. */ public Edge nextEdge;
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/ray/Ray2d.java // public class Ray2d extends LineParametric2d { // public Ray2d(Point2d pA, Vector2d pU) { // super(pA, pU); // } // // public static Point2d collide(Ray2d ray, LineLinear2d line, double epsilon) { // // FIXME rewrite? // Point2d collide = LineLinear2d.collide(ray.getLinearForm(), line); // if (collide == null) { // return null; // } // // /* // * Portably there is better way to do this. this is from graphical. // */ // Vector2d collideVector = new Vector2d(collide); // collideVector.sub(ray.A); // // double dot = ray.U.dot(collideVector); // // if (dot < epsilon) { // return null; // } // // return collide; // } // // @Override // public String toString() { // return "Ray2d [A=" + A + ", U=" + U + "]"; // } // // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/path/FaceNode.java // public class FaceNode extends PathQueueNode<FaceNode> { // // private Vertex vertex; // // public FaceNode(Vertex vertex) { // super(); // this.vertex = vertex; // } // // public Vertex getVertex() { // return vertex; // } // // public boolean isQueueClosed() { // FaceQueue fq = getFaceQueue(); // return fq.isClosed(); // } // // public FaceQueue getFaceQueue() { // return (FaceQueue) list(); // } // // public boolean isQueueUnconnected() { // FaceQueue fq = getFaceQueue(); // return fq.isUnconnected(); // } // // public void queueClose() { // getFaceQueue().close(); // // TODO Auto-generated method stub // // } // // } // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java import javax.vecmath.Point2d; import kendzi.math.geometry.ray.Ray2d; import kendzi.math.geometry.skeleton.path.FaceNode; package kendzi.math.geometry.skeleton.circular; /** * @author kendzi * */ public class Vertex extends CircularNode { private Point2d point; private double distance; private boolean processed; private Ray2d bisector; /** * Previous edge. */ public Edge previousEdge; /** * Next edge. */ public Edge nextEdge;
public FaceNode leftFace;
kendzi/kendzi-math
kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilTest.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // public static class SplitResult { // private final List<List<Point2d>> leftPolygons; // private final List<List<Point2d>> rightPolygons; // // public SplitResult(List<List<Point2d>> leftPolygons, List<List<Point2d>> rightPolygons) { // super(); // this.leftPolygons = leftPolygons; // this.rightPolygons = rightPolygons; // } // // /** // * @return the leftPolygons // */ // public List<List<Point2d>> getLeftPolygons() { // return leftPolygons; // } // // /** // * @return the rightPolygons // */ // public List<List<Point2d>> getRightPolygons() { // return rightPolygons; // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.SplitResult; import org.junit.Test;
package kendzi.math.geometry.polygon.split; /** * Tests for polygon split util. */ public class PlygonSplitUtilTest { private static final double EPSILON = 0.00001d; @SuppressWarnings("javadoc") @Test public void rect() { Point2d p0 = debugPoint(0, -1, -1); Point2d p1 = debugPoint(1, 1, -1); Point2d p2 = debugPoint(2, 1, 1); Point2d p3 = debugPoint(3, -1, 1); Point2d s0 = debugPoint("s0", -1, 0); Point2d s1 = debugPoint("s1", 1, 0); List<Point2d> polygon = new ArrayList<Point2d>(); polygon.add(p0); polygon.add(p1); polygon.add(p2); polygon.add(p3);
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // public static class SplitResult { // private final List<List<Point2d>> leftPolygons; // private final List<List<Point2d>> rightPolygons; // // public SplitResult(List<List<Point2d>> leftPolygons, List<List<Point2d>> rightPolygons) { // super(); // this.leftPolygons = leftPolygons; // this.rightPolygons = rightPolygons; // } // // /** // * @return the leftPolygons // */ // public List<List<Point2d>> getLeftPolygons() { // return leftPolygons; // } // // /** // * @return the rightPolygons // */ // public List<List<Point2d>> getRightPolygons() { // return rightPolygons; // } // // } // Path: kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.SplitResult; import org.junit.Test; package kendzi.math.geometry.polygon.split; /** * Tests for polygon split util. */ public class PlygonSplitUtilTest { private static final double EPSILON = 0.00001d; @SuppressWarnings("javadoc") @Test public void rect() { Point2d p0 = debugPoint(0, -1, -1); Point2d p1 = debugPoint(1, 1, -1); Point2d p2 = debugPoint(2, 1, 1); Point2d p3 = debugPoint(3, -1, 1); Point2d s0 = debugPoint("s0", -1, 0); Point2d s1 = debugPoint("s1", 1, 0); List<Point2d> polygon = new ArrayList<Point2d>(); polygon.add(p0); polygon.add(p1); polygon.add(p2); polygon.add(p3);
LinePoints2d line = new LinePoints2d(debugPoint("l1", 0, 0), debugPoint("l2", 1, 0));
kendzi/kendzi-math
kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilTest.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // public static class SplitResult { // private final List<List<Point2d>> leftPolygons; // private final List<List<Point2d>> rightPolygons; // // public SplitResult(List<List<Point2d>> leftPolygons, List<List<Point2d>> rightPolygons) { // super(); // this.leftPolygons = leftPolygons; // this.rightPolygons = rightPolygons; // } // // /** // * @return the leftPolygons // */ // public List<List<Point2d>> getLeftPolygons() { // return leftPolygons; // } // // /** // * @return the rightPolygons // */ // public List<List<Point2d>> getRightPolygons() { // return rightPolygons; // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.SplitResult; import org.junit.Test;
package kendzi.math.geometry.polygon.split; /** * Tests for polygon split util. */ public class PlygonSplitUtilTest { private static final double EPSILON = 0.00001d; @SuppressWarnings("javadoc") @Test public void rect() { Point2d p0 = debugPoint(0, -1, -1); Point2d p1 = debugPoint(1, 1, -1); Point2d p2 = debugPoint(2, 1, 1); Point2d p3 = debugPoint(3, -1, 1); Point2d s0 = debugPoint("s0", -1, 0); Point2d s1 = debugPoint("s1", 1, 0); List<Point2d> polygon = new ArrayList<Point2d>(); polygon.add(p0); polygon.add(p1); polygon.add(p2); polygon.add(p3); LinePoints2d line = new LinePoints2d(debugPoint("l1", 0, 0), debugPoint("l2", 1, 0));
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // public static class SplitResult { // private final List<List<Point2d>> leftPolygons; // private final List<List<Point2d>> rightPolygons; // // public SplitResult(List<List<Point2d>> leftPolygons, List<List<Point2d>> rightPolygons) { // super(); // this.leftPolygons = leftPolygons; // this.rightPolygons = rightPolygons; // } // // /** // * @return the leftPolygons // */ // public List<List<Point2d>> getLeftPolygons() { // return leftPolygons; // } // // /** // * @return the rightPolygons // */ // public List<List<Point2d>> getRightPolygons() { // return rightPolygons; // } // // } // Path: kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.SplitResult; import org.junit.Test; package kendzi.math.geometry.polygon.split; /** * Tests for polygon split util. */ public class PlygonSplitUtilTest { private static final double EPSILON = 0.00001d; @SuppressWarnings("javadoc") @Test public void rect() { Point2d p0 = debugPoint(0, -1, -1); Point2d p1 = debugPoint(1, 1, -1); Point2d p2 = debugPoint(2, 1, 1); Point2d p3 = debugPoint(3, -1, 1); Point2d s0 = debugPoint("s0", -1, 0); Point2d s1 = debugPoint("s1", 1, 0); List<Point2d> polygon = new ArrayList<Point2d>(); polygon.add(p0); polygon.add(p1); polygon.add(p2); polygon.add(p3); LinePoints2d line = new LinePoints2d(debugPoint("l1", 0, 0), debugPoint("l2", 1, 0));
SplitResult split = PlygonSplitUtil.split(polygon, line);
kendzi/kendzi-math
kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/events/chains/SingleEdgeChain.java
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java // public class Vertex extends CircularNode { // // private Point2d point; // // private double distance; // // private boolean processed; // // private Ray2d bisector; // // /** // * Previous edge. // */ // public Edge previousEdge; // // /** // * Next edge. // */ // public Edge nextEdge; // // public FaceNode leftFace; // // public FaceNode rightFace; // // public Vertex(Point2d point, double distance, Ray2d bisector, Edge previousEdge, Edge nextEdge) { // super(); // this.point = point; // this.distance = distance; // this.bisector = bisector; // this.previousEdge = previousEdge; // this.nextEdge = nextEdge; // // processed = false; // } // // public Vertex() { // // TODO Auto-generated constructor stub // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "VertexEntry [v=" + this.point + ", processed=" + this.processed + ", bisector=" + this.bisector // + ", previousEdge=" + this.previousEdge + ", nextEdge=" + this.nextEdge; // } // // @Override // public Vertex next() { // return (Vertex) super.next(); // } // // @Override // public Vertex previous() { // return (Vertex) super.previous(); // } // // public Point2d getPoint() { // return point; // } // // public double getDistance() { // return distance; // } // // public boolean isProcessed() { // return processed; // } // // public Ray2d getBisector() { // return bisector; // } // // public Edge getPreviousEdge() { // return previousEdge; // } // // public Edge getNextEdge() { // return nextEdge; // } // // public FaceNode getLeftFace() { // return leftFace; // } // // public FaceNode getRightFace() { // return rightFace; // } // // public void setProcessed(boolean processed) { // this.processed = processed; // } // // @Deprecated // public void setBisector(Ray2d bisector) { // this.bisector = bisector; // } // // }
import kendzi.math.geometry.skeleton.circular.Edge; import kendzi.math.geometry.skeleton.circular.Vertex;
package kendzi.math.geometry.skeleton.events.chains; public class SingleEdgeChain extends Chain { private Edge oppositeEdge;
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java // public class Vertex extends CircularNode { // // private Point2d point; // // private double distance; // // private boolean processed; // // private Ray2d bisector; // // /** // * Previous edge. // */ // public Edge previousEdge; // // /** // * Next edge. // */ // public Edge nextEdge; // // public FaceNode leftFace; // // public FaceNode rightFace; // // public Vertex(Point2d point, double distance, Ray2d bisector, Edge previousEdge, Edge nextEdge) { // super(); // this.point = point; // this.distance = distance; // this.bisector = bisector; // this.previousEdge = previousEdge; // this.nextEdge = nextEdge; // // processed = false; // } // // public Vertex() { // // TODO Auto-generated constructor stub // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "VertexEntry [v=" + this.point + ", processed=" + this.processed + ", bisector=" + this.bisector // + ", previousEdge=" + this.previousEdge + ", nextEdge=" + this.nextEdge; // } // // @Override // public Vertex next() { // return (Vertex) super.next(); // } // // @Override // public Vertex previous() { // return (Vertex) super.previous(); // } // // public Point2d getPoint() { // return point; // } // // public double getDistance() { // return distance; // } // // public boolean isProcessed() { // return processed; // } // // public Ray2d getBisector() { // return bisector; // } // // public Edge getPreviousEdge() { // return previousEdge; // } // // public Edge getNextEdge() { // return nextEdge; // } // // public FaceNode getLeftFace() { // return leftFace; // } // // public FaceNode getRightFace() { // return rightFace; // } // // public void setProcessed(boolean processed) { // this.processed = processed; // } // // @Deprecated // public void setBisector(Ray2d bisector) { // this.bisector = bisector; // } // // } // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/events/chains/SingleEdgeChain.java import kendzi.math.geometry.skeleton.circular.Edge; import kendzi.math.geometry.skeleton.circular.Vertex; package kendzi.math.geometry.skeleton.events.chains; public class SingleEdgeChain extends Chain { private Edge oppositeEdge;
private Vertex nextVertex;
kendzi/kendzi-math
kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/events/VertexSplitEvent.java
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java // public class Vertex extends CircularNode { // // private Point2d point; // // private double distance; // // private boolean processed; // // private Ray2d bisector; // // /** // * Previous edge. // */ // public Edge previousEdge; // // /** // * Next edge. // */ // public Edge nextEdge; // // public FaceNode leftFace; // // public FaceNode rightFace; // // public Vertex(Point2d point, double distance, Ray2d bisector, Edge previousEdge, Edge nextEdge) { // super(); // this.point = point; // this.distance = distance; // this.bisector = bisector; // this.previousEdge = previousEdge; // this.nextEdge = nextEdge; // // processed = false; // } // // public Vertex() { // // TODO Auto-generated constructor stub // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "VertexEntry [v=" + this.point + ", processed=" + this.processed + ", bisector=" + this.bisector // + ", previousEdge=" + this.previousEdge + ", nextEdge=" + this.nextEdge; // } // // @Override // public Vertex next() { // return (Vertex) super.next(); // } // // @Override // public Vertex previous() { // return (Vertex) super.previous(); // } // // public Point2d getPoint() { // return point; // } // // public double getDistance() { // return distance; // } // // public boolean isProcessed() { // return processed; // } // // public Ray2d getBisector() { // return bisector; // } // // public Edge getPreviousEdge() { // return previousEdge; // } // // public Edge getNextEdge() { // return nextEdge; // } // // public FaceNode getLeftFace() { // return leftFace; // } // // public FaceNode getRightFace() { // return rightFace; // } // // public void setProcessed(boolean processed) { // this.processed = processed; // } // // @Deprecated // public void setBisector(Ray2d bisector) { // this.bisector = bisector; // } // // }
import javax.vecmath.Point2d; import kendzi.math.geometry.skeleton.circular.Edge; import kendzi.math.geometry.skeleton.circular.Vertex;
package kendzi.math.geometry.skeleton.events; /** * @author kendzi * */ public class VertexSplitEvent extends SplitEvent { public VertexSplitEvent(Point2d point, double distance, Vertex parent) { super(point, distance, parent, null); }
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Vertex.java // public class Vertex extends CircularNode { // // private Point2d point; // // private double distance; // // private boolean processed; // // private Ray2d bisector; // // /** // * Previous edge. // */ // public Edge previousEdge; // // /** // * Next edge. // */ // public Edge nextEdge; // // public FaceNode leftFace; // // public FaceNode rightFace; // // public Vertex(Point2d point, double distance, Ray2d bisector, Edge previousEdge, Edge nextEdge) { // super(); // this.point = point; // this.distance = distance; // this.bisector = bisector; // this.previousEdge = previousEdge; // this.nextEdge = nextEdge; // // processed = false; // } // // public Vertex() { // // TODO Auto-generated constructor stub // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "VertexEntry [v=" + this.point + ", processed=" + this.processed + ", bisector=" + this.bisector // + ", previousEdge=" + this.previousEdge + ", nextEdge=" + this.nextEdge; // } // // @Override // public Vertex next() { // return (Vertex) super.next(); // } // // @Override // public Vertex previous() { // return (Vertex) super.previous(); // } // // public Point2d getPoint() { // return point; // } // // public double getDistance() { // return distance; // } // // public boolean isProcessed() { // return processed; // } // // public Ray2d getBisector() { // return bisector; // } // // public Edge getPreviousEdge() { // return previousEdge; // } // // public Edge getNextEdge() { // return nextEdge; // } // // public FaceNode getLeftFace() { // return leftFace; // } // // public FaceNode getRightFace() { // return rightFace; // } // // public void setProcessed(boolean processed) { // this.processed = processed; // } // // @Deprecated // public void setBisector(Ray2d bisector) { // this.bisector = bisector; // } // // } // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/events/VertexSplitEvent.java import javax.vecmath.Point2d; import kendzi.math.geometry.skeleton.circular.Edge; import kendzi.math.geometry.skeleton.circular.Vertex; package kendzi.math.geometry.skeleton.events; /** * @author kendzi * */ public class VertexSplitEvent extends SplitEvent { public VertexSplitEvent(Point2d point, double distance, Vertex parent) { super(point, distance, parent, null); }
public Edge getOppositeEdgePrevious() {
kendzi/kendzi-math
kendzi-math-geometry/src/main/java/kendzi/math/geometry/intersection/IntersectionUtil.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector3dUtil.java // public class Vector3dUtil { // public static Vector3d fromTo(Tuple3d from, Tuple3d to) { // Vector3d v = new Vector3d(to); // v.sub(from); // return v; // } // // }
import javax.vecmath.Point3d; import javax.vecmath.Vector3d; import kendzi.math.geometry.point.Vector3dUtil;
package kendzi.math.geometry.intersection; /** * Intersection util. * * @author Tomasz Kedziora (Kendzi) * */ public class IntersectionUtil { /** * Check whatever ray intersect triangle. * * @see <a * href="http://www.lighthouse3d.com/tutorials/maths/ray-triangle-intersection/">lighthouse3d * example</a> * @param p * ray start point * @param d * ray direction vector * @param v0 * triangle first point * @param v1 * triangle second point * @param v2 * triangle third point * @return if ray intersect triangle. */ public static boolean rayIntersectsTriangle(Point3d p, Vector3d d, Point3d v0, Point3d v1, Point3d v2) { double a, f, u, v;
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector3dUtil.java // public class Vector3dUtil { // public static Vector3d fromTo(Tuple3d from, Tuple3d to) { // Vector3d v = new Vector3d(to); // v.sub(from); // return v; // } // // } // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/intersection/IntersectionUtil.java import javax.vecmath.Point3d; import javax.vecmath.Vector3d; import kendzi.math.geometry.point.Vector3dUtil; package kendzi.math.geometry.intersection; /** * Intersection util. * * @author Tomasz Kedziora (Kendzi) * */ public class IntersectionUtil { /** * Check whatever ray intersect triangle. * * @see <a * href="http://www.lighthouse3d.com/tutorials/maths/ray-triangle-intersection/">lighthouse3d * example</a> * @param p * ray start point * @param d * ray direction vector * @param v0 * triangle first point * @param v1 * triangle second point * @param v2 * triangle third point * @return if ray intersect triangle. */ public static boolean rayIntersectsTriangle(Point3d p, Vector3d d, Point3d v0, Point3d v1, Point3d v2) { double a, f, u, v;
Vector3d e1 = Vector3dUtil.fromTo(v0, v1);
kendzi/kendzi-math
kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/path/FaceQueueUtil.java
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/utils/ValidateUtil.java // public class ValidateUtil { // public static void validateNotNull(Object obj, String msg) { // if (obj == null) { // throw new IllegalStateException("object can't be null: " + msg); // } // } // // public static void validateNull(Object obj, String msg) { // if (obj != null) { // throw new IllegalStateException("object should be null: " + msg); // } // } // // }
import kendzi.math.geometry.skeleton.utils.ValidateUtil;
package kendzi.math.geometry.skeleton.path; /** * Util for face queue. * * @author Tomasz Kedziora (Kendzi) * */ public class FaceQueueUtil { private FaceQueueUtil() { // } /** * Connect two nodes queue. Id both nodes comes from the same queue, queue * is closed. If nodes are from different queues nodes are moved to one of * them. * * @param firstFace * first face queue * @param secondFace * second face queue */ public static void connectQueues(FaceNode firstFace, FaceNode secondFace) {
// Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/utils/ValidateUtil.java // public class ValidateUtil { // public static void validateNotNull(Object obj, String msg) { // if (obj == null) { // throw new IllegalStateException("object can't be null: " + msg); // } // } // // public static void validateNull(Object obj, String msg) { // if (obj != null) { // throw new IllegalStateException("object should be null: " + msg); // } // } // // } // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/path/FaceQueueUtil.java import kendzi.math.geometry.skeleton.utils.ValidateUtil; package kendzi.math.geometry.skeleton.path; /** * Util for face queue. * * @author Tomasz Kedziora (Kendzi) * */ public class FaceQueueUtil { private FaceQueueUtil() { // } /** * Connect two nodes queue. Id both nodes comes from the same queue, queue * is closed. If nodes are from different queues nodes are moved to one of * them. * * @param firstFace * first face queue * @param secondFace * second face queue */ public static void connectQueues(FaceNode firstFace, FaceNode secondFace) {
ValidateUtil.validateNotNull(firstFace.list(), "firstFace.list");
kendzi/kendzi-math
kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/EnrichPolygonalChainUtilTest.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // }
import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import org.junit.Test;
package kendzi.math.geometry.polygon.split; /** * Tests for enriching polygonal chain. */ public class EnrichPolygonalChainUtilTest { @Test public void enrichOpenPolygonalChainByLineCrossing1() { Point2d p0 = debugPoint(0, 0, -1); Point2d p1 = debugPoint(1, 0, 1); Point2d s0 = debugPoint("s1", 0, 0); List<Point2d> openPolygonalChain = Arrays.asList(p0, p1);
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // Path: kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/EnrichPolygonalChainUtilTest.java import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import org.junit.Test; package kendzi.math.geometry.polygon.split; /** * Tests for enriching polygonal chain. */ public class EnrichPolygonalChainUtilTest { @Test public void enrichOpenPolygonalChainByLineCrossing1() { Point2d p0 = debugPoint(0, 0, -1); Point2d p1 = debugPoint(1, 0, 1); Point2d s0 = debugPoint("s1", 0, 0); List<Point2d> openPolygonalChain = Arrays.asList(p0, p1);
LinePoints2d splittingLine = new LinePoints2d(debugPoint("l1", 0, 0), debugPoint("l2", 1, 0));
kendzi/kendzi-math
kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LineUtil.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector2dUtil.java // public class Vector2dUtil { // // private static double EPSILON = 0.00000001; // // public static Vector2d orthogonalLeft(Vector2d v) { // return new Vector2d(-v.y, v.x); // } // // public static Vector2d orthogonalRight(Vector2d v) { // return new Vector2d(v.y, -v.x); // } // // public static Vector2d bisector(Point2d p1, Point2d p2, Point2d p3) { // left // // XXX rename to bisectorLeft // return Vector2dUtil.bisector(Vector2dUtil.fromTo(p1, p2), Vector2dUtil.fromTo(p2, p3)); // } // // public static Vector2d bisector(Vector2d v1, Vector2d v2) { // // XXX rename to bisectorLeft // Vector2d norm1 = new Vector2d(v1); // norm1.normalize(); // // Vector2d norm2 = new Vector2d(v2); // norm2.normalize(); // // return bisectorNormalized(norm1, norm2); // } // // public static Vector2d bisectorNormalized(Vector2d norm1, Vector2d norm2) { // Vector2d e1v = orthogonalLeft(norm1); // Vector2d e2v = orthogonalLeft(norm2); // // // 90 - 180 || 180 - 270 // // if (norm1.dot(e2v) <= 0 && ) { //XXX >= !! // if (norm1.dot(norm2) > 0) { // // e1v.add(e2v); // return e1v; // // } // // // 0 - 180 // Vector2d ret = new Vector2d(norm1); // ret.negate(); // ret.add(norm2); // // if (e1v.dot(norm2) < 0) { // // 270 - 360 // ret.negate(); // } // return ret; // } // // private static boolean equalsEpsilon(double pNumber) { // if ((pNumber < 0 ? -pNumber : pNumber) > EPSILON) { // return false; // } // return false; // // } // // /** // * Cross product for 2d is same as doc // * // * @param u // * @param v // * @return // * @see {http://mathworld.wolfram.com/CrossProduct.html} // */ // public static double cross(Tuple2d u, Tuple2d v) { // return u.x * v.y - u.y * v.x; // } // // public static Vector2d fromTo(Point2d begin, Point2d end) { // return new Vector2d(end.x - begin.x, end.y - begin.y); // } // // public static Vector2d negate(Vector2d vector) { // return new Vector2d(-vector.x, -vector.y); // } // // }
import javax.vecmath.Point2d; import javax.vecmath.Tuple2d; import javax.vecmath.Vector2d; import kendzi.math.geometry.point.Vector2dUtil;
} else if (matrixDet(C, D, A) * matrixDet(C, D, B) >= 0) { //System.out.println("Odcinki sie NIE przecinaja"); return null; } else { // znaki wyznacznikow sa rowne // System.out.println("Odcinki sie przecinaja- punkty leza po przeciwnych stronach"); return lineCrossPoint(A.x, A.y, B.x, B.y, C.x, C.y, D.x, D.y); } } } /** * @param p1 * @param p2 * @param v1 * @param v2 * @return * * @see {http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect/565282#565282} */ public static Point2d intersectLineSegments(Point2d p1, Point2d p2, Vector2d v1, Vector2d v2) { Point2d p = p1; Vector2d r = v1; Point2d q = p2; Vector2d s = v2; Vector2d qp = new Vector2d(q.x - p.x, q.y - p.y);
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector2dUtil.java // public class Vector2dUtil { // // private static double EPSILON = 0.00000001; // // public static Vector2d orthogonalLeft(Vector2d v) { // return new Vector2d(-v.y, v.x); // } // // public static Vector2d orthogonalRight(Vector2d v) { // return new Vector2d(v.y, -v.x); // } // // public static Vector2d bisector(Point2d p1, Point2d p2, Point2d p3) { // left // // XXX rename to bisectorLeft // return Vector2dUtil.bisector(Vector2dUtil.fromTo(p1, p2), Vector2dUtil.fromTo(p2, p3)); // } // // public static Vector2d bisector(Vector2d v1, Vector2d v2) { // // XXX rename to bisectorLeft // Vector2d norm1 = new Vector2d(v1); // norm1.normalize(); // // Vector2d norm2 = new Vector2d(v2); // norm2.normalize(); // // return bisectorNormalized(norm1, norm2); // } // // public static Vector2d bisectorNormalized(Vector2d norm1, Vector2d norm2) { // Vector2d e1v = orthogonalLeft(norm1); // Vector2d e2v = orthogonalLeft(norm2); // // // 90 - 180 || 180 - 270 // // if (norm1.dot(e2v) <= 0 && ) { //XXX >= !! // if (norm1.dot(norm2) > 0) { // // e1v.add(e2v); // return e1v; // // } // // // 0 - 180 // Vector2d ret = new Vector2d(norm1); // ret.negate(); // ret.add(norm2); // // if (e1v.dot(norm2) < 0) { // // 270 - 360 // ret.negate(); // } // return ret; // } // // private static boolean equalsEpsilon(double pNumber) { // if ((pNumber < 0 ? -pNumber : pNumber) > EPSILON) { // return false; // } // return false; // // } // // /** // * Cross product for 2d is same as doc // * // * @param u // * @param v // * @return // * @see {http://mathworld.wolfram.com/CrossProduct.html} // */ // public static double cross(Tuple2d u, Tuple2d v) { // return u.x * v.y - u.y * v.x; // } // // public static Vector2d fromTo(Point2d begin, Point2d end) { // return new Vector2d(end.x - begin.x, end.y - begin.y); // } // // public static Vector2d negate(Vector2d vector) { // return new Vector2d(-vector.x, -vector.y); // } // // } // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LineUtil.java import javax.vecmath.Point2d; import javax.vecmath.Tuple2d; import javax.vecmath.Vector2d; import kendzi.math.geometry.point.Vector2dUtil; } else if (matrixDet(C, D, A) * matrixDet(C, D, B) >= 0) { //System.out.println("Odcinki sie NIE przecinaja"); return null; } else { // znaki wyznacznikow sa rowne // System.out.println("Odcinki sie przecinaja- punkty leza po przeciwnych stronach"); return lineCrossPoint(A.x, A.y, B.x, B.y, C.x, C.y, D.x, D.y); } } } /** * @param p1 * @param p2 * @param v1 * @param v2 * @return * * @see {http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect/565282#565282} */ public static Point2d intersectLineSegments(Point2d p1, Point2d p2, Vector2d v1, Vector2d v2) { Point2d p = p1; Vector2d r = v1; Point2d q = p2; Vector2d s = v2; Vector2d qp = new Vector2d(q.x - p.x, q.y - p.y);
double rs = Vector2dUtil.cross(r, s);
kendzi/kendzi-math
kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/EdgeOutput.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/PolygonList2d.java // public class PolygonList2d { // // /** // * Points of polygon. // */ // private List<Point2d> points; // // /** // * Create polygon from list of points. // * // * @param pPoints list of points // */ // public PolygonList2d(List<Point2d> pPoints) { // this.points = pPoints; // } // // /** // * Create polygon from points. // * // * @param pPoints points // */ // public PolygonList2d(Point2d ... pPoints) { // List<Point2d> ret = new ArrayList<Point2d>(pPoints.length); // for(Point2d p : pPoints) { // ret.add(p); // } // // this.points = ret; // } // // /** // * Create empty polygon. // */ // public PolygonList2d() { // this(new ArrayList<Point2d>()); // } // // /** // * @return the points // */ // public List<Point2d> getPoints() { // return this.points; // } // // /** // * @param pPoints the points to set // */ // public void setPoints(List<Point2d> pPoints) { // this.points = pPoints; // } // // // // // public void union(PolygonList2d pPolygon) { // // TODO !!! // // suma // throw new RuntimeException("TODO"); // } // public void difference(PolygonList2d pPolygon) { // // TODO !!! // // roznica // throw new RuntimeException("TODO"); // } // // public boolean inside(Point2d pPoint) { // // TODO !!! // throw new RuntimeException("TODO"); // // } // // public boolean inside(Point2d pPoint, double epsilon) { // // TODO !!! // throw new RuntimeException("TODO"); // } // // /** // * Reverse point order in list // * // * @param polygon // * @return // */ // public static List<Point2d> reverse(List<Point2d> polygon) { // return PolygonUtil.reverse(polygon); // } // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // }
import kendzi.math.geometry.polygon.PolygonList2d; import kendzi.math.geometry.skeleton.circular.Edge;
package kendzi.math.geometry.skeleton; public class EdgeOutput { // int edgeNumber; // int polygonNumber private Edge edge;
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/PolygonList2d.java // public class PolygonList2d { // // /** // * Points of polygon. // */ // private List<Point2d> points; // // /** // * Create polygon from list of points. // * // * @param pPoints list of points // */ // public PolygonList2d(List<Point2d> pPoints) { // this.points = pPoints; // } // // /** // * Create polygon from points. // * // * @param pPoints points // */ // public PolygonList2d(Point2d ... pPoints) { // List<Point2d> ret = new ArrayList<Point2d>(pPoints.length); // for(Point2d p : pPoints) { // ret.add(p); // } // // this.points = ret; // } // // /** // * Create empty polygon. // */ // public PolygonList2d() { // this(new ArrayList<Point2d>()); // } // // /** // * @return the points // */ // public List<Point2d> getPoints() { // return this.points; // } // // /** // * @param pPoints the points to set // */ // public void setPoints(List<Point2d> pPoints) { // this.points = pPoints; // } // // // // // public void union(PolygonList2d pPolygon) { // // TODO !!! // // suma // throw new RuntimeException("TODO"); // } // public void difference(PolygonList2d pPolygon) { // // TODO !!! // // roznica // throw new RuntimeException("TODO"); // } // // public boolean inside(Point2d pPoint) { // // TODO !!! // throw new RuntimeException("TODO"); // // } // // public boolean inside(Point2d pPoint, double epsilon) { // // TODO !!! // throw new RuntimeException("TODO"); // } // // /** // * Reverse point order in list // * // * @param polygon // * @return // */ // public static List<Point2d> reverse(List<Point2d> polygon) { // return PolygonUtil.reverse(polygon); // } // } // // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/circular/Edge.java // public class Edge extends CircularNode { // // private Point2d begin; // private Point2d end; // // private Ray2d bisectorPrevious; // private Ray2d bisectorNext; // // private LineLinear2d lineLinear2d; // // private Vector2d norm; // // public Edge(Point2d begin, Point2d end) { // this.begin = begin; // this.end = end; // // this.lineLinear2d = new LineLinear2d(begin, end); // // this.norm = new Vector2d(end); // this.norm.sub(begin); // this.norm.normalize(); // // } // // @Override // public Edge next() { // return (Edge) super.next(); // } // // @Override // public Edge previous() { // return (Edge) super.previous(); // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(begin, norm); // } // // public LineLinear2d getLineLinear() { // return this.lineLinear2d; // } // // public Vector2d getNorm() { // return this.norm; // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "EdgeEntry [p1=" + this.begin + ", p2=" + this.end + "]"; // } // // public Point2d getBegin() { // return begin; // } // // public Point2d getEnd() { // return end; // } // // public Ray2d getBisectorPrevious() { // return bisectorPrevious; // } // // public Ray2d getBisectorNext() { // return bisectorNext; // } // // public LineLinear2d getLineLinear2d() { // return lineLinear2d; // } // // public void setBisectorPrevious(Ray2d bisectorPrevious) { // this.bisectorPrevious = bisectorPrevious; // } // // public void setBisectorNext(Ray2d bisectorNext) { // this.bisectorNext = bisectorNext; // } // } // Path: kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/EdgeOutput.java import kendzi.math.geometry.polygon.PolygonList2d; import kendzi.math.geometry.skeleton.circular.Edge; package kendzi.math.geometry.skeleton; public class EdgeOutput { // int edgeNumber; // int polygonNumber private Edge edge;
private PolygonList2d polygon;
kendzi/kendzi-math
kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilInternalTest.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Close { // public List<Node> chain; // public double beginDistance; // public double endDistance; // public boolean direction; // public boolean removed; // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "Close [beginDistance=" + beginDistance + ", endDistance=" + endDistance + ", direction=" + direction // + ", removed=" + removed + ", chain=" + chain + "]"; // } // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Node { // private final Point2d point; // private final double det; // // /** // * The node. // * // * @param point // * polygon point // * @param det // * determinant from splitting line // */ // public Node(Point2d point, double det) { // this.point = point; // this.det = det; // } // // /** // * Checks if point is lies on splitting line. // * // * @return is point on splitting line // */ // public boolean isOnSplittingLine() { // return det == ZERO; // } // // @Override // public String toString() { // return "Node [point=" + point + ", det=" + det + "]"; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Close; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Node; import org.junit.Test;
package kendzi.math.geometry.polygon.split; /** * Tests for internals of polygon split util. */ public class PlygonSplitUtilInternalTest { private static final double EPSILON = 0.00001d; @Test public void closePolygonsSingleSquare() { Point2d p1 = debugPoint(0, 1, -0); Point2d p2 = debugPoint(1, 1, -1); Point2d p3 = debugPoint(2, 1, 1); Point2d p4 = debugPoint(4, -1, -0);
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Close { // public List<Node> chain; // public double beginDistance; // public double endDistance; // public boolean direction; // public boolean removed; // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "Close [beginDistance=" + beginDistance + ", endDistance=" + endDistance + ", direction=" + direction // + ", removed=" + removed + ", chain=" + chain + "]"; // } // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Node { // private final Point2d point; // private final double det; // // /** // * The node. // * // * @param point // * polygon point // * @param det // * determinant from splitting line // */ // public Node(Point2d point, double det) { // this.point = point; // this.det = det; // } // // /** // * Checks if point is lies on splitting line. // * // * @return is point on splitting line // */ // public boolean isOnSplittingLine() { // return det == ZERO; // } // // @Override // public String toString() { // return "Node [point=" + point + ", det=" + det + "]"; // } // } // Path: kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilInternalTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Close; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Node; import org.junit.Test; package kendzi.math.geometry.polygon.split; /** * Tests for internals of polygon split util. */ public class PlygonSplitUtilInternalTest { private static final double EPSILON = 0.00001d; @Test public void closePolygonsSingleSquare() { Point2d p1 = debugPoint(0, 1, -0); Point2d p2 = debugPoint(1, 1, -1); Point2d p3 = debugPoint(2, 1, 1); Point2d p4 = debugPoint(4, -1, -0);
Node n0 = debugNode("n0", p1, 0);
kendzi/kendzi-math
kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilInternalTest.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Close { // public List<Node> chain; // public double beginDistance; // public double endDistance; // public boolean direction; // public boolean removed; // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "Close [beginDistance=" + beginDistance + ", endDistance=" + endDistance + ", direction=" + direction // + ", removed=" + removed + ", chain=" + chain + "]"; // } // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Node { // private final Point2d point; // private final double det; // // /** // * The node. // * // * @param point // * polygon point // * @param det // * determinant from splitting line // */ // public Node(Point2d point, double det) { // this.point = point; // this.det = det; // } // // /** // * Checks if point is lies on splitting line. // * // * @return is point on splitting line // */ // public boolean isOnSplittingLine() { // return det == ZERO; // } // // @Override // public String toString() { // return "Node [point=" + point + ", det=" + det + "]"; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Close; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Node; import org.junit.Test;
package kendzi.math.geometry.polygon.split; /** * Tests for internals of polygon split util. */ public class PlygonSplitUtilInternalTest { private static final double EPSILON = 0.00001d; @Test public void closePolygonsSingleSquare() { Point2d p1 = debugPoint(0, 1, -0); Point2d p2 = debugPoint(1, 1, -1); Point2d p3 = debugPoint(2, 1, 1); Point2d p4 = debugPoint(4, -1, -0); Node n0 = debugNode("n0", p1, 0); Node n1 = debugNode("n1", p2, 1); Node n2 = debugNode("n2", p3, 1); Node n3 = debugNode("n3", p4, 0);
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Close { // public List<Node> chain; // public double beginDistance; // public double endDistance; // public boolean direction; // public boolean removed; // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "Close [beginDistance=" + beginDistance + ", endDistance=" + endDistance + ", direction=" + direction // + ", removed=" + removed + ", chain=" + chain + "]"; // } // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Node { // private final Point2d point; // private final double det; // // /** // * The node. // * // * @param point // * polygon point // * @param det // * determinant from splitting line // */ // public Node(Point2d point, double det) { // this.point = point; // this.det = det; // } // // /** // * Checks if point is lies on splitting line. // * // * @return is point on splitting line // */ // public boolean isOnSplittingLine() { // return det == ZERO; // } // // @Override // public String toString() { // return "Node [point=" + point + ", det=" + det + "]"; // } // } // Path: kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilInternalTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Close; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Node; import org.junit.Test; package kendzi.math.geometry.polygon.split; /** * Tests for internals of polygon split util. */ public class PlygonSplitUtilInternalTest { private static final double EPSILON = 0.00001d; @Test public void closePolygonsSingleSquare() { Point2d p1 = debugPoint(0, 1, -0); Point2d p2 = debugPoint(1, 1, -1); Point2d p3 = debugPoint(2, 1, 1); Point2d p4 = debugPoint(4, -1, -0); Node n0 = debugNode("n0", p1, 0); Node n1 = debugNode("n1", p2, 1); Node n2 = debugNode("n2", p3, 1); Node n3 = debugNode("n3", p4, 0);
LinePoints2d line = new LinePoints2d(debugPoint("l1", 0, 0), debugPoint("l2", 1, 0));
kendzi/kendzi-math
kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilInternalTest.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Close { // public List<Node> chain; // public double beginDistance; // public double endDistance; // public boolean direction; // public boolean removed; // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "Close [beginDistance=" + beginDistance + ", endDistance=" + endDistance + ", direction=" + direction // + ", removed=" + removed + ", chain=" + chain + "]"; // } // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Node { // private final Point2d point; // private final double det; // // /** // * The node. // * // * @param point // * polygon point // * @param det // * determinant from splitting line // */ // public Node(Point2d point, double det) { // this.point = point; // this.det = det; // } // // /** // * Checks if point is lies on splitting line. // * // * @return is point on splitting line // */ // public boolean isOnSplittingLine() { // return det == ZERO; // } // // @Override // public String toString() { // return "Node [point=" + point + ", det=" + det + "]"; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Close; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Node; import org.junit.Test;
package kendzi.math.geometry.polygon.split; /** * Tests for internals of polygon split util. */ public class PlygonSplitUtilInternalTest { private static final double EPSILON = 0.00001d; @Test public void closePolygonsSingleSquare() { Point2d p1 = debugPoint(0, 1, -0); Point2d p2 = debugPoint(1, 1, -1); Point2d p3 = debugPoint(2, 1, 1); Point2d p4 = debugPoint(4, -1, -0); Node n0 = debugNode("n0", p1, 0); Node n1 = debugNode("n1", p2, 1); Node n2 = debugNode("n2", p3, 1); Node n3 = debugNode("n3", p4, 0); LinePoints2d line = new LinePoints2d(debugPoint("l1", 0, 0), debugPoint("l2", 1, 0)); @SuppressWarnings("unchecked")
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LinePoints2d.java // public class LinePoints2d { // /** // * Start point A. XXX rename to A ? // */ // Point2d p1; // /** // * End point B. XXX rename to B ? // */ // Point2d p2; // // public LinePoints2d(Point2d p1, Point2d p2) { // this.p1 = p1; // this.p2 = p2; // } // // public Point2d getP1() { // return this.p1; // } // // public void setP1(Point2d p1) { // this.p1 = p1; // } // // public Point2d getP2() { // return this.p2; // } // // public void setP2(Point2d p2) { // this.p2 = p2; // } // // /** // * Starting Point A from parametric description. // * // * @return starting point A. // */ // Point2d getPointA() { // return this.p1; // } // // /** // * Direction vector U from parametric description. // * // * @return direction vector U. // */ // Vector2d getVectorU() { // Vector2d u = new Vector2d(this.p2); // u.sub(this.p1); // return u; // } // // public LineParametric2d getLineParametric2d() { // return new LineParametric2d(getPointA(), getVectorU()); // } // // // /** Determinate if point is over line or on line. // * @param pPoint point // * @return point is over line or on line // * TODO RENAME TO POINT_IN_FRONT // */ // public boolean inFront(Tuple2d pPoint) { // return LineUtil.matrixDet(this.p1, this.p2, pPoint) >= 0; // } // // /** // * {@inheritDoc} // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "L (" + this.p1 + ") -> (" + this.p2 + ")"; // } // // // // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Close { // public List<Node> chain; // public double beginDistance; // public double endDistance; // public boolean direction; // public boolean removed; // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "Close [beginDistance=" + beginDistance + ", endDistance=" + endDistance + ", direction=" + direction // + ", removed=" + removed + ", chain=" + chain + "]"; // } // // } // // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/split/PlygonSplitUtil.java // protected static class Node { // private final Point2d point; // private final double det; // // /** // * The node. // * // * @param point // * polygon point // * @param det // * determinant from splitting line // */ // public Node(Point2d point, double det) { // this.point = point; // this.det = det; // } // // /** // * Checks if point is lies on splitting line. // * // * @return is point on splitting line // */ // public boolean isOnSplittingLine() { // return det == ZERO; // } // // @Override // public String toString() { // return "Node [point=" + point + ", det=" + det + "]"; // } // } // Path: kendzi-math-geometry/src/test/java/kendzi/math/geometry/polygon/split/PlygonSplitUtilInternalTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.line.LinePoints2d; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Close; import kendzi.math.geometry.polygon.split.PlygonSplitUtil.Node; import org.junit.Test; package kendzi.math.geometry.polygon.split; /** * Tests for internals of polygon split util. */ public class PlygonSplitUtilInternalTest { private static final double EPSILON = 0.00001d; @Test public void closePolygonsSingleSquare() { Point2d p1 = debugPoint(0, 1, -0); Point2d p2 = debugPoint(1, 1, -1); Point2d p3 = debugPoint(2, 1, 1); Point2d p4 = debugPoint(4, -1, -0); Node n0 = debugNode("n0", p1, 0); Node n1 = debugNode("n1", p2, 1); Node n2 = debugNode("n2", p3, 1); Node n3 = debugNode("n3", p4, 0); LinePoints2d line = new LinePoints2d(debugPoint("l1", 0, 0), debugPoint("l2", 1, 0)); @SuppressWarnings("unchecked")
List<Close> polygons = PlygonSplitUtil.closePolygons(Arrays.asList(Arrays.<Node> asList(n0, n1, n2, n3)), line);
kendzi/kendzi-math
kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LineParametric2d.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector2dUtil.java // public class Vector2dUtil { // // private static double EPSILON = 0.00000001; // // public static Vector2d orthogonalLeft(Vector2d v) { // return new Vector2d(-v.y, v.x); // } // // public static Vector2d orthogonalRight(Vector2d v) { // return new Vector2d(v.y, -v.x); // } // // public static Vector2d bisector(Point2d p1, Point2d p2, Point2d p3) { // left // // XXX rename to bisectorLeft // return Vector2dUtil.bisector(Vector2dUtil.fromTo(p1, p2), Vector2dUtil.fromTo(p2, p3)); // } // // public static Vector2d bisector(Vector2d v1, Vector2d v2) { // // XXX rename to bisectorLeft // Vector2d norm1 = new Vector2d(v1); // norm1.normalize(); // // Vector2d norm2 = new Vector2d(v2); // norm2.normalize(); // // return bisectorNormalized(norm1, norm2); // } // // public static Vector2d bisectorNormalized(Vector2d norm1, Vector2d norm2) { // Vector2d e1v = orthogonalLeft(norm1); // Vector2d e2v = orthogonalLeft(norm2); // // // 90 - 180 || 180 - 270 // // if (norm1.dot(e2v) <= 0 && ) { //XXX >= !! // if (norm1.dot(norm2) > 0) { // // e1v.add(e2v); // return e1v; // // } // // // 0 - 180 // Vector2d ret = new Vector2d(norm1); // ret.negate(); // ret.add(norm2); // // if (e1v.dot(norm2) < 0) { // // 270 - 360 // ret.negate(); // } // return ret; // } // // private static boolean equalsEpsilon(double pNumber) { // if ((pNumber < 0 ? -pNumber : pNumber) > EPSILON) { // return false; // } // return false; // // } // // /** // * Cross product for 2d is same as doc // * // * @param u // * @param v // * @return // * @see {http://mathworld.wolfram.com/CrossProduct.html} // */ // public static double cross(Tuple2d u, Tuple2d v) { // return u.x * v.y - u.y * v.x; // } // // public static Vector2d fromTo(Point2d begin, Point2d end) { // return new Vector2d(end.x - begin.x, end.y - begin.y); // } // // public static Vector2d negate(Vector2d vector) { // return new Vector2d(-vector.x, -vector.y); // } // // }
import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import kendzi.math.geometry.point.Vector2dUtil;
/* * This software is provided "AS IS" without a warranty of any kind. * You use it on your own risk and responsibility!!! * * This file is shared under BSD v3 license. * See readme.txt and BSD3 file for details. * */ package kendzi.math.geometry.line; /** * Geometry line in parametric form. * * x = x_A + t * u_x; * y = y_A + t * u_y; * where t in R * * TODO * * @see http://pl.wikipedia.org/wiki/Prosta#R.C3.B3wnanie_w_postaci_kierunkowej * @see http://en.wikipedia.org/wiki/Linear_equation * * @author kendzi * */ public class LineParametric2d { public Point2d A; public Vector2d U; public LineParametric2d(Point2d pA, Vector2d pU) { this.A = pA; this.U = pU; } public LineLinear2d getLinearForm() { double x = this.A.x; double y = this.A.y; double B = -this.U.x; double A = this.U.y; double C = - (A * x + B * y); return new LineLinear2d(A, B, C); } public boolean isOnLeftSite(Point2d point, double epsilon) { Vector2d direction = new Vector2d(point); direction.sub(A);
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector2dUtil.java // public class Vector2dUtil { // // private static double EPSILON = 0.00000001; // // public static Vector2d orthogonalLeft(Vector2d v) { // return new Vector2d(-v.y, v.x); // } // // public static Vector2d orthogonalRight(Vector2d v) { // return new Vector2d(v.y, -v.x); // } // // public static Vector2d bisector(Point2d p1, Point2d p2, Point2d p3) { // left // // XXX rename to bisectorLeft // return Vector2dUtil.bisector(Vector2dUtil.fromTo(p1, p2), Vector2dUtil.fromTo(p2, p3)); // } // // public static Vector2d bisector(Vector2d v1, Vector2d v2) { // // XXX rename to bisectorLeft // Vector2d norm1 = new Vector2d(v1); // norm1.normalize(); // // Vector2d norm2 = new Vector2d(v2); // norm2.normalize(); // // return bisectorNormalized(norm1, norm2); // } // // public static Vector2d bisectorNormalized(Vector2d norm1, Vector2d norm2) { // Vector2d e1v = orthogonalLeft(norm1); // Vector2d e2v = orthogonalLeft(norm2); // // // 90 - 180 || 180 - 270 // // if (norm1.dot(e2v) <= 0 && ) { //XXX >= !! // if (norm1.dot(norm2) > 0) { // // e1v.add(e2v); // return e1v; // // } // // // 0 - 180 // Vector2d ret = new Vector2d(norm1); // ret.negate(); // ret.add(norm2); // // if (e1v.dot(norm2) < 0) { // // 270 - 360 // ret.negate(); // } // return ret; // } // // private static boolean equalsEpsilon(double pNumber) { // if ((pNumber < 0 ? -pNumber : pNumber) > EPSILON) { // return false; // } // return false; // // } // // /** // * Cross product for 2d is same as doc // * // * @param u // * @param v // * @return // * @see {http://mathworld.wolfram.com/CrossProduct.html} // */ // public static double cross(Tuple2d u, Tuple2d v) { // return u.x * v.y - u.y * v.x; // } // // public static Vector2d fromTo(Point2d begin, Point2d end) { // return new Vector2d(end.x - begin.x, end.y - begin.y); // } // // public static Vector2d negate(Vector2d vector) { // return new Vector2d(-vector.x, -vector.y); // } // // } // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LineParametric2d.java import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import kendzi.math.geometry.point.Vector2dUtil; /* * This software is provided "AS IS" without a warranty of any kind. * You use it on your own risk and responsibility!!! * * This file is shared under BSD v3 license. * See readme.txt and BSD3 file for details. * */ package kendzi.math.geometry.line; /** * Geometry line in parametric form. * * x = x_A + t * u_x; * y = y_A + t * u_y; * where t in R * * TODO * * @see http://pl.wikipedia.org/wiki/Prosta#R.C3.B3wnanie_w_postaci_kierunkowej * @see http://en.wikipedia.org/wiki/Linear_equation * * @author kendzi * */ public class LineParametric2d { public Point2d A; public Vector2d U; public LineParametric2d(Point2d pA, Vector2d pU) { this.A = pA; this.U = pU; } public LineLinear2d getLinearForm() { double x = this.A.x; double y = this.A.y; double B = -this.U.x; double A = this.U.y; double C = - (A * x + B * y); return new LineLinear2d(A, B, C); } public boolean isOnLeftSite(Point2d point, double epsilon) { Vector2d direction = new Vector2d(point); direction.sub(A);
Vector2d ortagonalRight = Vector2dUtil.orthogonalRight(U);
kendzi/kendzi-math
kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/PolygonWithHolesList2dUtil.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/TransformationMatrix2d.java // public class TransformationMatrix2d { // // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotX(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {1, 0 }, // {0, cosX} // }); // } // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotXA(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {1, 0, 0}, // {0, cosX, 0}, // {0, 0, 1} // }); // } // // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotY(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {cosX, 0 }, // {0, 1 }, // }); // } // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotYA(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {cosX, 0, 0}, // {0, 1, 0}, // {0, 0, 1} // }); // } // // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotZ(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {cosX, -sinX }, // {sinX, cosX } // }); // } // /** // * XXX sign of alpha may change !!! // * @param alpha // * @return // */ // public static SimpleMatrix rotZA(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {cosX, -sinX, 0}, // {sinX, cosX, 0}, // {0, 0, 1} // }); // } // // // /** // * @param alpha // * @return // */ // public static SimpleMatrix tranA(double x, double y) { // // return new SimpleMatrix( // new double [][] { // {1, 0, x}, // {0, 1, y}, // {0, 0, 1} // }); // } // // /** // * // * @return // */ // public static SimpleMatrix scaleA(double scaleX, double scaleY) { // // // return new SimpleMatrix( // new double [][] { // {scaleX, 0, 0}, // {0, scaleY, 0}, // {0, 0, 1} // }); // } // // public static Point2d transform(Point2d pPoint, SimpleMatrix pSimpleMatrix) { // SimpleMatrix sm = new SimpleMatrix( // new double [][] { // {pPoint.x}, // {pPoint.y}, // {1} // }); // // SimpleMatrix mult = pSimpleMatrix.mult(sm); // // return new Point2d(mult.get(0), mult.get(1)); // } // // public static Vector2d transform(Vector2d pVector, SimpleMatrix pSimpleMatrix) { // SimpleMatrix sm = new SimpleMatrix( // new double [][] { // {pVector.x}, // {pVector.y}, // {0} // }); // // SimpleMatrix mult = pSimpleMatrix.mult(sm); // // return new Vector2d(mult.get(0), mult.get(1)); // } // // /** Transform list of points using transformation matrix. // * @param pList list of points // * @param transformLocal transformation matrix // * @return transformed list of points // */ // public static List<Point2d> transformList(List<Point2d> pList, SimpleMatrix transformLocal) { // // List<Point2d> list = new ArrayList<Point2d>(pList.size()); // for (Point2d p : pList) { // Point2d transformed = TransformationMatrix2d.transform(p, transformLocal); // list.add(transformed); // } // return list; // } // // /** Transform array of points using transformation matrix. // * @param pList array of points // * @param transformLocal transformation matrix // * @return transformed array of points // */ // public static Point2d[] transformArray(Point2d[] pList, SimpleMatrix transformLocal) { // // Point2d [] list = new Point2d[pList.length]; // int i = 0; // for (Point2d p : pList) { // Point2d transformed = TransformationMatrix2d.transform(p, transformLocal); // list[i] = transformed; // i++; // } // return list; // } // }
import java.util.ArrayList; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.point.TransformationMatrix2d; import org.ejml.simple.SimpleMatrix;
package kendzi.math.geometry.polygon; public class PolygonWithHolesList2dUtil { public static PolygonWithHolesList2d transform(PolygonWithHolesList2d polygon, SimpleMatrix transformMatrix) { PolygonList2d outer = polygon.getOuter();
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/TransformationMatrix2d.java // public class TransformationMatrix2d { // // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotX(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {1, 0 }, // {0, cosX} // }); // } // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotXA(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {1, 0, 0}, // {0, cosX, 0}, // {0, 0, 1} // }); // } // // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotY(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {cosX, 0 }, // {0, 1 }, // }); // } // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotYA(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {cosX, 0, 0}, // {0, 1, 0}, // {0, 0, 1} // }); // } // // /** // * @param alpha // * @return // */ // public static SimpleMatrix rotZ(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {cosX, -sinX }, // {sinX, cosX } // }); // } // /** // * XXX sign of alpha may change !!! // * @param alpha // * @return // */ // public static SimpleMatrix rotZA(double alpha) { // double sinX = Math.sin(alpha); // double cosX = Math.cos(alpha); // // return new SimpleMatrix( // new double [][] { // {cosX, -sinX, 0}, // {sinX, cosX, 0}, // {0, 0, 1} // }); // } // // // /** // * @param alpha // * @return // */ // public static SimpleMatrix tranA(double x, double y) { // // return new SimpleMatrix( // new double [][] { // {1, 0, x}, // {0, 1, y}, // {0, 0, 1} // }); // } // // /** // * // * @return // */ // public static SimpleMatrix scaleA(double scaleX, double scaleY) { // // // return new SimpleMatrix( // new double [][] { // {scaleX, 0, 0}, // {0, scaleY, 0}, // {0, 0, 1} // }); // } // // public static Point2d transform(Point2d pPoint, SimpleMatrix pSimpleMatrix) { // SimpleMatrix sm = new SimpleMatrix( // new double [][] { // {pPoint.x}, // {pPoint.y}, // {1} // }); // // SimpleMatrix mult = pSimpleMatrix.mult(sm); // // return new Point2d(mult.get(0), mult.get(1)); // } // // public static Vector2d transform(Vector2d pVector, SimpleMatrix pSimpleMatrix) { // SimpleMatrix sm = new SimpleMatrix( // new double [][] { // {pVector.x}, // {pVector.y}, // {0} // }); // // SimpleMatrix mult = pSimpleMatrix.mult(sm); // // return new Vector2d(mult.get(0), mult.get(1)); // } // // /** Transform list of points using transformation matrix. // * @param pList list of points // * @param transformLocal transformation matrix // * @return transformed list of points // */ // public static List<Point2d> transformList(List<Point2d> pList, SimpleMatrix transformLocal) { // // List<Point2d> list = new ArrayList<Point2d>(pList.size()); // for (Point2d p : pList) { // Point2d transformed = TransformationMatrix2d.transform(p, transformLocal); // list.add(transformed); // } // return list; // } // // /** Transform array of points using transformation matrix. // * @param pList array of points // * @param transformLocal transformation matrix // * @return transformed array of points // */ // public static Point2d[] transformArray(Point2d[] pList, SimpleMatrix transformLocal) { // // Point2d [] list = new Point2d[pList.length]; // int i = 0; // for (Point2d p : pList) { // Point2d transformed = TransformationMatrix2d.transform(p, transformLocal); // list[i] = transformed; // i++; // } // return list; // } // } // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/PolygonWithHolesList2dUtil.java import java.util.ArrayList; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.point.TransformationMatrix2d; import org.ejml.simple.SimpleMatrix; package kendzi.math.geometry.polygon; public class PolygonWithHolesList2dUtil { public static PolygonWithHolesList2d transform(PolygonWithHolesList2d polygon, SimpleMatrix transformMatrix) { PolygonList2d outer = polygon.getOuter();
List<Point2d> outerList = TransformationMatrix2d.transformList(outer.getPoints(), transformMatrix);
kendzi/kendzi-math
kendzi-straight-skeleton/src/test/java/kendzi/math/geometry/skeleton/SkeletonApplet.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/PolygonList2d.java // public class PolygonList2d { // // /** // * Points of polygon. // */ // private List<Point2d> points; // // /** // * Create polygon from list of points. // * // * @param pPoints list of points // */ // public PolygonList2d(List<Point2d> pPoints) { // this.points = pPoints; // } // // /** // * Create polygon from points. // * // * @param pPoints points // */ // public PolygonList2d(Point2d ... pPoints) { // List<Point2d> ret = new ArrayList<Point2d>(pPoints.length); // for(Point2d p : pPoints) { // ret.add(p); // } // // this.points = ret; // } // // /** // * Create empty polygon. // */ // public PolygonList2d() { // this(new ArrayList<Point2d>()); // } // // /** // * @return the points // */ // public List<Point2d> getPoints() { // return this.points; // } // // /** // * @param pPoints the points to set // */ // public void setPoints(List<Point2d> pPoints) { // this.points = pPoints; // } // // // // // public void union(PolygonList2d pPolygon) { // // TODO !!! // // suma // throw new RuntimeException("TODO"); // } // public void difference(PolygonList2d pPolygon) { // // TODO !!! // // roznica // throw new RuntimeException("TODO"); // } // // public boolean inside(Point2d pPoint) { // // TODO !!! // throw new RuntimeException("TODO"); // // } // // public boolean inside(Point2d pPoint, double epsilon) { // // TODO !!! // throw new RuntimeException("TODO"); // } // // /** // * Reverse point order in list // * // * @param polygon // * @return // */ // public static List<Point2d> reverse(List<Point2d> polygon) { // return PolygonUtil.reverse(polygon); // } // }
import java.applet.Applet; import java.awt.Button; import java.awt.Color; import java.awt.Dimension; import java.awt.Event; import java.awt.Graphics; import java.awt.Polygon; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.polygon.PolygonList2d;
if (this.points.contains(point)) { return; } this.points.add(point); if (this.points.size() >= 3) { SkeletonScanApp(); } } void clearAll() { this.points = new ArrayList<Point2d>(); this.drawableObjects.clear(); } boolean SkeletonScanApp() { SkeletonOutput ret = Skeleton.skeleton(this.points); setupResults(ret); return true; } public void setupResults(SkeletonOutput sk) { this.drawableObjects.clear(); for (EdgeOutput edgeOutput : sk.getEdgeOutputs()) {
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/polygon/PolygonList2d.java // public class PolygonList2d { // // /** // * Points of polygon. // */ // private List<Point2d> points; // // /** // * Create polygon from list of points. // * // * @param pPoints list of points // */ // public PolygonList2d(List<Point2d> pPoints) { // this.points = pPoints; // } // // /** // * Create polygon from points. // * // * @param pPoints points // */ // public PolygonList2d(Point2d ... pPoints) { // List<Point2d> ret = new ArrayList<Point2d>(pPoints.length); // for(Point2d p : pPoints) { // ret.add(p); // } // // this.points = ret; // } // // /** // * Create empty polygon. // */ // public PolygonList2d() { // this(new ArrayList<Point2d>()); // } // // /** // * @return the points // */ // public List<Point2d> getPoints() { // return this.points; // } // // /** // * @param pPoints the points to set // */ // public void setPoints(List<Point2d> pPoints) { // this.points = pPoints; // } // // // // // public void union(PolygonList2d pPolygon) { // // TODO !!! // // suma // throw new RuntimeException("TODO"); // } // public void difference(PolygonList2d pPolygon) { // // TODO !!! // // roznica // throw new RuntimeException("TODO"); // } // // public boolean inside(Point2d pPoint) { // // TODO !!! // throw new RuntimeException("TODO"); // // } // // public boolean inside(Point2d pPoint, double epsilon) { // // TODO !!! // throw new RuntimeException("TODO"); // } // // /** // * Reverse point order in list // * // * @param polygon // * @return // */ // public static List<Point2d> reverse(List<Point2d> polygon) { // return PolygonUtil.reverse(polygon); // } // } // Path: kendzi-straight-skeleton/src/test/java/kendzi/math/geometry/skeleton/SkeletonApplet.java import java.applet.Applet; import java.awt.Button; import java.awt.Color; import java.awt.Dimension; import java.awt.Event; import java.awt.Graphics; import java.awt.Polygon; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.vecmath.Point2d; import kendzi.math.geometry.polygon.PolygonList2d; if (this.points.contains(point)) { return; } this.points.add(point); if (this.points.size() >= 3) { SkeletonScanApp(); } } void clearAll() { this.points = new ArrayList<Point2d>(); this.drawableObjects.clear(); } boolean SkeletonScanApp() { SkeletonOutput ret = Skeleton.skeleton(this.points); setupResults(ret); return true; } public void setupResults(SkeletonOutput sk) { this.drawableObjects.clear(); for (EdgeOutput edgeOutput : sk.getEdgeOutputs()) {
PolygonList2d polygonList2d = edgeOutput.getPolygon();
kendzi/kendzi-math
kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LineSegmentUtil2d.java
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector2dUtil.java // public class Vector2dUtil { // // private static double EPSILON = 0.00000001; // // public static Vector2d orthogonalLeft(Vector2d v) { // return new Vector2d(-v.y, v.x); // } // // public static Vector2d orthogonalRight(Vector2d v) { // return new Vector2d(v.y, -v.x); // } // // public static Vector2d bisector(Point2d p1, Point2d p2, Point2d p3) { // left // // XXX rename to bisectorLeft // return Vector2dUtil.bisector(Vector2dUtil.fromTo(p1, p2), Vector2dUtil.fromTo(p2, p3)); // } // // public static Vector2d bisector(Vector2d v1, Vector2d v2) { // // XXX rename to bisectorLeft // Vector2d norm1 = new Vector2d(v1); // norm1.normalize(); // // Vector2d norm2 = new Vector2d(v2); // norm2.normalize(); // // return bisectorNormalized(norm1, norm2); // } // // public static Vector2d bisectorNormalized(Vector2d norm1, Vector2d norm2) { // Vector2d e1v = orthogonalLeft(norm1); // Vector2d e2v = orthogonalLeft(norm2); // // // 90 - 180 || 180 - 270 // // if (norm1.dot(e2v) <= 0 && ) { //XXX >= !! // if (norm1.dot(norm2) > 0) { // // e1v.add(e2v); // return e1v; // // } // // // 0 - 180 // Vector2d ret = new Vector2d(norm1); // ret.negate(); // ret.add(norm2); // // if (e1v.dot(norm2) < 0) { // // 270 - 360 // ret.negate(); // } // return ret; // } // // private static boolean equalsEpsilon(double pNumber) { // if ((pNumber < 0 ? -pNumber : pNumber) > EPSILON) { // return false; // } // return false; // // } // // /** // * Cross product for 2d is same as doc // * // * @param u // * @param v // * @return // * @see {http://mathworld.wolfram.com/CrossProduct.html} // */ // public static double cross(Tuple2d u, Tuple2d v) { // return u.x * v.y - u.y * v.x; // } // // public static Vector2d fromTo(Point2d begin, Point2d end) { // return new Vector2d(end.x - begin.x, end.y - begin.y); // } // // public static Vector2d negate(Vector2d vector) { // return new Vector2d(-vector.x, -vector.y); // } // // }
import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import kendzi.math.geometry.point.Vector2dUtil;
package kendzi.math.geometry.line; public class LineSegmentUtil2d { /** * Error epsilon. Anything that avoids division. */ static final double SMALL_NUM = 0.00000001; /** * Return value if there is no intersection. */ static final IntersectPoints EMPTY = new IntersectPoints(); /** * Calculate intersection points for two line segments. It can return more then one * intersection point when line segments overlaps. * * * @see http://geomalgorithms.com/a05-_intersect-1.html * @see http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm * * @param r1 * first line segment * @param r2 * second line segment * @return class with intersection points. It never return null. */ public static IntersectPoints intersectRays2d(LineSegment2d r1, LineSegment2d r2) { Point2d s1p0 = r1.getBegin(); Point2d s1p1 = r1.getEnd(); Point2d s2p0 = r2.getBegin(); Point2d s2p1 = r2.getEnd();
// Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/point/Vector2dUtil.java // public class Vector2dUtil { // // private static double EPSILON = 0.00000001; // // public static Vector2d orthogonalLeft(Vector2d v) { // return new Vector2d(-v.y, v.x); // } // // public static Vector2d orthogonalRight(Vector2d v) { // return new Vector2d(v.y, -v.x); // } // // public static Vector2d bisector(Point2d p1, Point2d p2, Point2d p3) { // left // // XXX rename to bisectorLeft // return Vector2dUtil.bisector(Vector2dUtil.fromTo(p1, p2), Vector2dUtil.fromTo(p2, p3)); // } // // public static Vector2d bisector(Vector2d v1, Vector2d v2) { // // XXX rename to bisectorLeft // Vector2d norm1 = new Vector2d(v1); // norm1.normalize(); // // Vector2d norm2 = new Vector2d(v2); // norm2.normalize(); // // return bisectorNormalized(norm1, norm2); // } // // public static Vector2d bisectorNormalized(Vector2d norm1, Vector2d norm2) { // Vector2d e1v = orthogonalLeft(norm1); // Vector2d e2v = orthogonalLeft(norm2); // // // 90 - 180 || 180 - 270 // // if (norm1.dot(e2v) <= 0 && ) { //XXX >= !! // if (norm1.dot(norm2) > 0) { // // e1v.add(e2v); // return e1v; // // } // // // 0 - 180 // Vector2d ret = new Vector2d(norm1); // ret.negate(); // ret.add(norm2); // // if (e1v.dot(norm2) < 0) { // // 270 - 360 // ret.negate(); // } // return ret; // } // // private static boolean equalsEpsilon(double pNumber) { // if ((pNumber < 0 ? -pNumber : pNumber) > EPSILON) { // return false; // } // return false; // // } // // /** // * Cross product for 2d is same as doc // * // * @param u // * @param v // * @return // * @see {http://mathworld.wolfram.com/CrossProduct.html} // */ // public static double cross(Tuple2d u, Tuple2d v) { // return u.x * v.y - u.y * v.x; // } // // public static Vector2d fromTo(Point2d begin, Point2d end) { // return new Vector2d(end.x - begin.x, end.y - begin.y); // } // // public static Vector2d negate(Vector2d vector) { // return new Vector2d(-vector.x, -vector.y); // } // // } // Path: kendzi-math-geometry/src/main/java/kendzi/math/geometry/line/LineSegmentUtil2d.java import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import kendzi.math.geometry.point.Vector2dUtil; package kendzi.math.geometry.line; public class LineSegmentUtil2d { /** * Error epsilon. Anything that avoids division. */ static final double SMALL_NUM = 0.00000001; /** * Return value if there is no intersection. */ static final IntersectPoints EMPTY = new IntersectPoints(); /** * Calculate intersection points for two line segments. It can return more then one * intersection point when line segments overlaps. * * * @see http://geomalgorithms.com/a05-_intersect-1.html * @see http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm * * @param r1 * first line segment * @param r2 * second line segment * @return class with intersection points. It never return null. */ public static IntersectPoints intersectRays2d(LineSegment2d r1, LineSegment2d r2) { Point2d s1p0 = r1.getBegin(); Point2d s1p1 = r1.getEnd(); Point2d s2p0 = r2.getBegin(); Point2d s2p1 = r2.getEnd();
Vector2d u = Vector2dUtil.fromTo(r1.getBegin(), r1.getEnd());
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/StashCommentReportTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // }
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.sonar.plugins.stash.StashPlugin.IssueType; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
report1.add(comment2); StashCommentReport report2 = new StashCommentReport(); report2.add(report1); assertEquals(2, report2.size()); } @Test public void testAddNotEmptyReportToEmptyReport() { StashCommentReport report1 = new StashCommentReport(); StashCommentReport report2 = new StashCommentReport(); report2.add(comment1); report1.add(report2); assertEquals(1, report1.size()); } @Test public void testAddEmptyReportToEmptyReport() { StashCommentReport report1 = new StashCommentReport(); StashCommentReport report2 = new StashCommentReport(); report1.add(report2); assertEquals(0, report1.size()); } @Test public void applyDiffReportWithCONTEXT() { StashDiff diff = mock(StashDiff.class);
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // } // Path: src/test/java/org/sonar/plugins/stash/issue/StashCommentReportTest.java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.sonar.plugins.stash.StashPlugin.IssueType; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; report1.add(comment2); StashCommentReport report2 = new StashCommentReport(); report2.add(report1); assertEquals(2, report2.size()); } @Test public void testAddNotEmptyReportToEmptyReport() { StashCommentReport report1 = new StashCommentReport(); StashCommentReport report2 = new StashCommentReport(); report2.add(comment1); report1.add(report2); assertEquals(1, report1.size()); } @Test public void testAddEmptyReportToEmptyReport() { StashCommentReport report1 = new StashCommentReport(); StashCommentReport report2 = new StashCommentReport(); report1.add(report2); assertEquals(0, report1.size()); } @Test public void applyDiffReportWithCONTEXT() { StashDiff diff = mock(StashDiff.class);
when(diff.getType()).thenReturn(IssueType.CONTEXT);
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/StashDiffReportTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // }
import com.google.common.collect.Range; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.plugins.stash.StashPlugin.IssueType; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.sonar.plugins.stash.issue; public class StashDiffReportTest { StashDiff diff1; StashDiff diff2; StashDiff diff3; StashDiff diff4; StashDiff diff5; StashDiff diff6; StashDiffReport report1 = new StashDiffReport(); StashDiffReport report2 = new StashDiffReport(); private static final String FILE_PATH = "path/to/diff"; @BeforeEach public void setUp() { StashComment comment1 = mock(StashComment.class); when(comment1.getId()).thenReturn((long)12345); StashComment comment2 = mock(StashComment.class); when(comment2.getId()).thenReturn((long)54321);
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // } // Path: src/test/java/org/sonar/plugins/stash/issue/StashDiffReportTest.java import com.google.common.collect.Range; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.plugins.stash.StashPlugin.IssueType; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.sonar.plugins.stash.issue; public class StashDiffReportTest { StashDiff diff1; StashDiff diff2; StashDiff diff3; StashDiff diff4; StashDiff diff5; StashDiff diff6; StashDiffReport report1 = new StashDiffReport(); StashDiffReport report2 = new StashDiffReport(); private static final String FILE_PATH = "path/to/diff"; @BeforeEach public void setUp() { StashComment comment1 = mock(StashComment.class); when(comment1.getId()).thenReturn((long)12345); StashComment comment2 = mock(StashComment.class); when(comment2.getId()).thenReturn((long)54321);
diff1 = new StashDiff(IssueType.CONTEXT, "path/to/diff1", (long)10, (long)20);
AmadeusITGroup/sonar-stash
src/main/java/org/sonar/plugins/stash/issue/StashCommentReport.java
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // }
import java.util.Objects; import java.util.ArrayList; import java.util.List; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.plugins.stash.StashPlugin.IssueType;
public void add(StashComment comment) { comments.add(comment); } public void add(StashCommentReport report) { for (StashComment comment : report.getComments()) { comments.add(comment); } } public boolean contains(String message, String path, long line) { boolean result = false; for (StashComment comment : comments) { if (Objects.equals(comment.getMessage(), message) && Objects.equals(comment.getPath(), path) && comment.getLine() == line) { result = true; break; } } return result; } public StashCommentReport applyDiffReport(StashDiffReport diffReport) { for (StashComment comment : comments) { StashDiff diff = diffReport.getDiffByComment(comment.getId());
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // } // Path: src/main/java/org/sonar/plugins/stash/issue/StashCommentReport.java import java.util.Objects; import java.util.ArrayList; import java.util.List; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.plugins.stash.StashPlugin.IssueType; public void add(StashComment comment) { comments.add(comment); } public void add(StashCommentReport report) { for (StashComment comment : report.getComments()) { comments.add(comment); } } public boolean contains(String message, String path, long line) { boolean result = false; for (StashComment comment : comments) { if (Objects.equals(comment.getMessage(), message) && Objects.equals(comment.getPath(), path) && comment.getLine() == line) { result = true; break; } } return result; } public StashCommentReport applyDiffReport(StashDiffReport diffReport) { for (StashComment comment : comments) { StashDiff diff = diffReport.getDiffByComment(comment.getId());
if ((diff != null) && diff.getType() == IssueType.CONTEXT) {
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/StashPluginUtilsTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static String formatPercentage(double d) { // // // Defining that our percentage is precise down to 0.1% // DecimalFormat df = new DecimalFormat("0.0"); // // // Protecting this method against non-US locales that would not use '.' as decimal separation // DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); // decimalFormatSymbols.setDecimalSeparator('.'); // df.setDecimalFormatSymbols(decimalFormatSymbols); // // // Making sure that we round the 0.1% properly out of the double value // df.setRoundingMode(RoundingMode.HALF_UP); // return df.format(d); // } // // Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static boolean roundedPercentageGreaterThan(double left, double right) { // return (left > right) && !formatPercentage(left).equals(formatPercentage(right)); // }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.sonar.plugins.stash.StashPluginUtils.formatPercentage; import static org.sonar.plugins.stash.StashPluginUtils.roundedPercentageGreaterThan;
package org.sonar.plugins.stash; public class StashPluginUtilsTest { @Test public void testFormatPercentage() {
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static String formatPercentage(double d) { // // // Defining that our percentage is precise down to 0.1% // DecimalFormat df = new DecimalFormat("0.0"); // // // Protecting this method against non-US locales that would not use '.' as decimal separation // DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); // decimalFormatSymbols.setDecimalSeparator('.'); // df.setDecimalFormatSymbols(decimalFormatSymbols); // // // Making sure that we round the 0.1% properly out of the double value // df.setRoundingMode(RoundingMode.HALF_UP); // return df.format(d); // } // // Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static boolean roundedPercentageGreaterThan(double left, double right) { // return (left > right) && !formatPercentage(left).equals(formatPercentage(right)); // } // Path: src/test/java/org/sonar/plugins/stash/StashPluginUtilsTest.java import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.sonar.plugins.stash.StashPluginUtils.formatPercentage; import static org.sonar.plugins.stash.StashPluginUtils.roundedPercentageGreaterThan; package org.sonar.plugins.stash; public class StashPluginUtilsTest { @Test public void testFormatPercentage() {
assertEquals("10.9", formatPercentage(10.90));
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/StashPluginUtilsTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static String formatPercentage(double d) { // // // Defining that our percentage is precise down to 0.1% // DecimalFormat df = new DecimalFormat("0.0"); // // // Protecting this method against non-US locales that would not use '.' as decimal separation // DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); // decimalFormatSymbols.setDecimalSeparator('.'); // df.setDecimalFormatSymbols(decimalFormatSymbols); // // // Making sure that we round the 0.1% properly out of the double value // df.setRoundingMode(RoundingMode.HALF_UP); // return df.format(d); // } // // Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static boolean roundedPercentageGreaterThan(double left, double right) { // return (left > right) && !formatPercentage(left).equals(formatPercentage(right)); // }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.sonar.plugins.stash.StashPluginUtils.formatPercentage; import static org.sonar.plugins.stash.StashPluginUtils.roundedPercentageGreaterThan;
package org.sonar.plugins.stash; public class StashPluginUtilsTest { @Test public void testFormatPercentage() { assertEquals("10.9", formatPercentage(10.90)); assertEquals("10.9", formatPercentage(10.94)); assertEquals("11.0", formatPercentage(10.96)); assertEquals("11.0", formatPercentage(11.0)); assertEquals("31.3", formatPercentage(31.25)); assertEquals("50.3", formatPercentage(50.29)); // This test can fail with 50.2 instead of 50.3 if run with an older version of the JDK 8 // (failed with v25 & worked with v131) } @Test public void testRoundedPercentageGreaterThan() {
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static String formatPercentage(double d) { // // // Defining that our percentage is precise down to 0.1% // DecimalFormat df = new DecimalFormat("0.0"); // // // Protecting this method against non-US locales that would not use '.' as decimal separation // DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); // decimalFormatSymbols.setDecimalSeparator('.'); // df.setDecimalFormatSymbols(decimalFormatSymbols); // // // Making sure that we round the 0.1% properly out of the double value // df.setRoundingMode(RoundingMode.HALF_UP); // return df.format(d); // } // // Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static boolean roundedPercentageGreaterThan(double left, double right) { // return (left > right) && !formatPercentage(left).equals(formatPercentage(right)); // } // Path: src/test/java/org/sonar/plugins/stash/StashPluginUtilsTest.java import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.sonar.plugins.stash.StashPluginUtils.formatPercentage; import static org.sonar.plugins.stash.StashPluginUtils.roundedPercentageGreaterThan; package org.sonar.plugins.stash; public class StashPluginUtilsTest { @Test public void testFormatPercentage() { assertEquals("10.9", formatPercentage(10.90)); assertEquals("10.9", formatPercentage(10.94)); assertEquals("11.0", formatPercentage(10.96)); assertEquals("11.0", formatPercentage(11.0)); assertEquals("31.3", formatPercentage(31.25)); assertEquals("50.3", formatPercentage(50.29)); // This test can fail with 50.2 instead of 50.3 if run with an older version of the JDK 8 // (failed with v25 & worked with v131) } @Test public void testRoundedPercentageGreaterThan() {
assertTrue(roundedPercentageGreaterThan(0.1, 0.0));
AmadeusITGroup/sonar-stash
src/main/java/org/sonar/plugins/stash/StashPlugin.java
// Path: src/main/java/org/sonar/plugins/stash/issue/StashDiffReport.java // public class StashDiffReport { // // public static final int VICINITY_RANGE_NONE = 0; // // private List<StashDiff> diffs; // // public StashDiffReport() { // this.diffs = new ArrayList<>(); // } // // public List<StashDiff> getDiffs() { // return Collections.unmodifiableList(diffs); // } // // public void add(StashDiff diff) { // diffs.add(diff); // } // // public void add(StashDiffReport report) { // diffs.addAll(report.getDiffs()); // } // // private static boolean inVicinityOfChangedDiff(StashDiff diff, long destination, int range) { // if (range <= 0) { // return false; // } // long lower = Math.min(diff.getSource(), diff.getDestination()); // long upper = Math.max(diff.getSource(), diff.getDestination()); // return Range.closed(lower - range, upper + range).contains(destination); // } // // private static boolean isChangedDiff(StashDiff diff, long destination) { // return diff.getDestination() == destination; // } // // private static boolean lineIsChangedDiff(StashDiff diff) { // return !diff.getType().equals(IssueType.CONTEXT); // } // // public IssueType getType(String path, long destination, int vicinityRange) { // boolean isInContextDiff = false; // for (StashDiff diff : diffs) { // if (Objects.equals(diff.getPath(), path)) { // // Line 0 never belongs to Stash Diff view. // // It is a global comment with a type set to CONTEXT. // if (destination == 0) { // return IssueType.CONTEXT; // } else if (!lineIsChangedDiff(diff)) { // // We only care about changed diff // continue; // } else if (isChangedDiff(diff, destination)) { // return diff.getType(); // } else if (inVicinityOfChangedDiff(diff, destination, vicinityRange)) { // isInContextDiff = true; // } // } // } // return isInContextDiff ? IssueType.CONTEXT : null; // } // // /** // * Depends on the type of the diff. // * If type == "CONTEXT", return the source line of the diff. // * If type == "ADDED", return the destination line of the diff. // */ // public long getLine(String path, long destination) { // for (StashDiff diff : diffs) { // if (Objects.equals(diff.getPath(), path) && (diff.getDestination() == destination)) { // // if (diff.getType() == IssueType.CONTEXT) { // return diff.getSource(); // } else { // return diff.getDestination(); // } // } // } // return 0; // } // // public StashDiff getDiffByComment(long commentId) { // for (StashDiff diff : diffs) { // if (diff.containsComment(commentId)) { // return diff; // } // } // return null; // } // // /** // * Get all comments from the Stash differential report. // */ // public List<StashComment> getComments() { // List<StashComment> result = new ArrayList<>(); // // for (StashDiff diff : this.diffs) { // List<StashComment> comments = diff.getComments(); // // for (StashComment comment : comments) { // if (!result.contains(comment)) { // result.add(comment); // } // } // } // return result; // } // }
import com.google.common.collect.Lists; import java.util.Arrays; import java.util.stream.Collectors; import org.sonar.api.Plugin; import org.sonar.api.Properties; import org.sonar.api.Property; import org.sonar.api.PropertyType; import org.sonar.api.batch.rule.Severity; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.resources.Qualifiers; import java.util.List; import org.sonar.plugins.stash.issue.StashDiffReport;
package org.sonar.plugins.stash; @Properties({ @Property(key = StashPlugin.STASH_NOTIFICATION, name = "Stash Notification", defaultValue = "false", description = "Analysis result will be issued in Stash pull request", global = false), @Property(key = StashPlugin.STASH_PROJECT, name = "Stash Project", description = "Stash project of current pull-request", global = false), @Property(key = StashPlugin.STASH_REPOSITORY, name = "Stash Repository", description = "Stash project of current pull-request", global = false), @Property(key = StashPlugin.STASH_PULL_REQUEST_ID, name = "Stash Pull-request Id", description = "Stash pull-request Id", global = false)}) public class StashPlugin implements Plugin { private static final String DEFAULT_STASH_TIMEOUT_VALUE = "10000"; private static final String DEFAULT_STASH_THRESHOLD_VALUE = "100"; private static final boolean DEFAULT_STASH_ANALYSIS_OVERVIEW = true; private static final boolean DEFAULT_STASH_INCLUDE_EXISTING_ISSUES = false; private static final int DEFAULT_STASH_FILES_IN_OVERVIEW = 0;
// Path: src/main/java/org/sonar/plugins/stash/issue/StashDiffReport.java // public class StashDiffReport { // // public static final int VICINITY_RANGE_NONE = 0; // // private List<StashDiff> diffs; // // public StashDiffReport() { // this.diffs = new ArrayList<>(); // } // // public List<StashDiff> getDiffs() { // return Collections.unmodifiableList(diffs); // } // // public void add(StashDiff diff) { // diffs.add(diff); // } // // public void add(StashDiffReport report) { // diffs.addAll(report.getDiffs()); // } // // private static boolean inVicinityOfChangedDiff(StashDiff diff, long destination, int range) { // if (range <= 0) { // return false; // } // long lower = Math.min(diff.getSource(), diff.getDestination()); // long upper = Math.max(diff.getSource(), diff.getDestination()); // return Range.closed(lower - range, upper + range).contains(destination); // } // // private static boolean isChangedDiff(StashDiff diff, long destination) { // return diff.getDestination() == destination; // } // // private static boolean lineIsChangedDiff(StashDiff diff) { // return !diff.getType().equals(IssueType.CONTEXT); // } // // public IssueType getType(String path, long destination, int vicinityRange) { // boolean isInContextDiff = false; // for (StashDiff diff : diffs) { // if (Objects.equals(diff.getPath(), path)) { // // Line 0 never belongs to Stash Diff view. // // It is a global comment with a type set to CONTEXT. // if (destination == 0) { // return IssueType.CONTEXT; // } else if (!lineIsChangedDiff(diff)) { // // We only care about changed diff // continue; // } else if (isChangedDiff(diff, destination)) { // return diff.getType(); // } else if (inVicinityOfChangedDiff(diff, destination, vicinityRange)) { // isInContextDiff = true; // } // } // } // return isInContextDiff ? IssueType.CONTEXT : null; // } // // /** // * Depends on the type of the diff. // * If type == "CONTEXT", return the source line of the diff. // * If type == "ADDED", return the destination line of the diff. // */ // public long getLine(String path, long destination) { // for (StashDiff diff : diffs) { // if (Objects.equals(diff.getPath(), path) && (diff.getDestination() == destination)) { // // if (diff.getType() == IssueType.CONTEXT) { // return diff.getSource(); // } else { // return diff.getDestination(); // } // } // } // return 0; // } // // public StashDiff getDiffByComment(long commentId) { // for (StashDiff diff : diffs) { // if (diff.containsComment(commentId)) { // return diff; // } // } // return null; // } // // /** // * Get all comments from the Stash differential report. // */ // public List<StashComment> getComments() { // List<StashComment> result = new ArrayList<>(); // // for (StashDiff diff : this.diffs) { // List<StashComment> comments = diff.getComments(); // // for (StashComment comment : comments) { // if (!result.contains(comment)) { // result.add(comment); // } // } // } // return result; // } // } // Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java import com.google.common.collect.Lists; import java.util.Arrays; import java.util.stream.Collectors; import org.sonar.api.Plugin; import org.sonar.api.Properties; import org.sonar.api.Property; import org.sonar.api.PropertyType; import org.sonar.api.batch.rule.Severity; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.resources.Qualifiers; import java.util.List; import org.sonar.plugins.stash.issue.StashDiffReport; package org.sonar.plugins.stash; @Properties({ @Property(key = StashPlugin.STASH_NOTIFICATION, name = "Stash Notification", defaultValue = "false", description = "Analysis result will be issued in Stash pull request", global = false), @Property(key = StashPlugin.STASH_PROJECT, name = "Stash Project", description = "Stash project of current pull-request", global = false), @Property(key = StashPlugin.STASH_REPOSITORY, name = "Stash Repository", description = "Stash project of current pull-request", global = false), @Property(key = StashPlugin.STASH_PULL_REQUEST_ID, name = "Stash Pull-request Id", description = "Stash pull-request Id", global = false)}) public class StashPlugin implements Plugin { private static final String DEFAULT_STASH_TIMEOUT_VALUE = "10000"; private static final String DEFAULT_STASH_THRESHOLD_VALUE = "100"; private static final boolean DEFAULT_STASH_ANALYSIS_OVERVIEW = true; private static final boolean DEFAULT_STASH_INCLUDE_EXISTING_ISSUES = false; private static final int DEFAULT_STASH_FILES_IN_OVERVIEW = 0;
private static final int DEFAULT_STASH_INCLUDE_VICINITY_RANGE = StashDiffReport.VICINITY_RANGE_NONE;
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/StashDiffTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // }
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.plugins.stash.StashPlugin.IssueType; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.sonar.plugins.stash.issue; public class StashDiffTest { StashDiff diff1; StashDiff diff2; StashDiff diff3; @BeforeEach public void setUp() { StashComment comment1 = mock(StashComment.class); when(comment1.getId()).thenReturn((long)12345); StashComment comment2 = mock(StashComment.class); when(comment2.getId()).thenReturn((long)54321);
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // } // Path: src/test/java/org/sonar/plugins/stash/issue/StashDiffTest.java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.plugins.stash.StashPlugin.IssueType; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.sonar.plugins.stash.issue; public class StashDiffTest { StashDiff diff1; StashDiff diff2; StashDiff diff3; @BeforeEach public void setUp() { StashComment comment1 = mock(StashComment.class); when(comment1.getId()).thenReturn((long)12345); StashComment comment2 = mock(StashComment.class); when(comment2.getId()).thenReturn((long)54321);
diff1 = new StashDiff(IssueType.CONTEXT, "path/to/diff1", (long)10, (long)20);
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/MarkdownPrinterTest.java
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // }
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver;
package org.sonar.plugins.stash.issue; public class MarkdownPrinterTest { PostJobIssue issue; List<PostJobIssue> report = new ArrayList<>(); private static final String SONAR_URL = "sonarqube/URL"; private MarkdownPrinter printer; private int issueThreshold; @BeforeEach public void setUp() {
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // } // Path: src/test/java/org/sonar/plugins/stash/issue/MarkdownPrinterTest.java import static org.junit.jupiter.api.Assertions.assertEquals; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver; package org.sonar.plugins.stash.issue; public class MarkdownPrinterTest { PostJobIssue issue; List<PostJobIssue> report = new ArrayList<>(); private static final String SONAR_URL = "sonarqube/URL"; private MarkdownPrinter printer; private int issueThreshold; @BeforeEach public void setUp() {
PostJobIssue issueBlocker = new DefaultIssue().setKey("key1")
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/MarkdownPrinterTest.java
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // }
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver;
package org.sonar.plugins.stash.issue; public class MarkdownPrinterTest { PostJobIssue issue; List<PostJobIssue> report = new ArrayList<>(); private static final String SONAR_URL = "sonarqube/URL"; private MarkdownPrinter printer; private int issueThreshold; @BeforeEach public void setUp() { PostJobIssue issueBlocker = new DefaultIssue().setKey("key1") .setSeverity(Severity.BLOCKER) .setMessage("messageBlocker") .setRuleKey(RuleKey.of("RepoBlocker", "RuleBlocker"))
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // } // Path: src/test/java/org/sonar/plugins/stash/issue/MarkdownPrinterTest.java import static org.junit.jupiter.api.Assertions.assertEquals; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver; package org.sonar.plugins.stash.issue; public class MarkdownPrinterTest { PostJobIssue issue; List<PostJobIssue> report = new ArrayList<>(); private static final String SONAR_URL = "sonarqube/URL"; private MarkdownPrinter printer; private int issueThreshold; @BeforeEach public void setUp() { PostJobIssue issueBlocker = new DefaultIssue().setKey("key1") .setSeverity(Severity.BLOCKER) .setMessage("messageBlocker") .setRuleKey(RuleKey.of("RepoBlocker", "RuleBlocker"))
.setInputComponent(inputFile("foo1", "scripts/file1.example"))
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/MarkdownPrinterTest.java
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // }
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver;
.setLine(1); PostJobIssue issueMajor = new DefaultIssue().setKey("key3") .setSeverity(Severity.MAJOR) .setMessage("messageMajor") .setRuleKey(RuleKey.of("RepoMajor", "RuleMajor")) .setInputComponent(inputFile("foo3", "scripts/file3.example")) .setLine(1); PostJobIssue issueSameFile = new DefaultIssue().setKey("key3") .setSeverity(Severity.MAJOR) .setMessage("messageMajor") .setRuleKey(RuleKey.of("RepoMajor", "RuleMajor")) .setInputComponent(inputFile("foo3", "scripts/tests/file3.example")) .setLine(5); PostJobIssue issueSameFileHidden = new DefaultIssue().setKey("key3") .setSeverity(Severity.MAJOR) .setMessage("messageMajor") .setRuleKey(RuleKey.of("RepoMajor", "RuleMajor")) .setInputComponent(inputFile("foo3", "scripts/file3.example")) .setLine(15); report.add(issueBlocker); report.add(issueCritical); report.add(issueMajor); report.add(issueSameFile); report.add(issueSameFileHidden); issue = issueBlocker; issueThreshold = 100;
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // } // Path: src/test/java/org/sonar/plugins/stash/issue/MarkdownPrinterTest.java import static org.junit.jupiter.api.Assertions.assertEquals; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver; .setLine(1); PostJobIssue issueMajor = new DefaultIssue().setKey("key3") .setSeverity(Severity.MAJOR) .setMessage("messageMajor") .setRuleKey(RuleKey.of("RepoMajor", "RuleMajor")) .setInputComponent(inputFile("foo3", "scripts/file3.example")) .setLine(1); PostJobIssue issueSameFile = new DefaultIssue().setKey("key3") .setSeverity(Severity.MAJOR) .setMessage("messageMajor") .setRuleKey(RuleKey.of("RepoMajor", "RuleMajor")) .setInputComponent(inputFile("foo3", "scripts/tests/file3.example")) .setLine(5); PostJobIssue issueSameFileHidden = new DefaultIssue().setKey("key3") .setSeverity(Severity.MAJOR) .setMessage("messageMajor") .setRuleKey(RuleKey.of("RepoMajor", "RuleMajor")) .setInputComponent(inputFile("foo3", "scripts/file3.example")) .setLine(15); report.add(issueBlocker); report.add(issueCritical); report.add(issueMajor); report.add(issueSameFile); report.add(issueSameFileHidden); issue = issueBlocker; issueThreshold = 100;
printer = new MarkdownPrinter(issueThreshold, SONAR_URL, 2, new DummyIssuePathResolver());
AmadeusITGroup/sonar-stash
src/main/java/org/sonar/plugins/stash/issue/StashDiffReport.java
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // }
import com.google.common.collect.Range; import java.util.Collections; import java.util.Objects; import java.util.ArrayList; import java.util.List; import org.sonar.plugins.stash.StashPlugin.IssueType;
package org.sonar.plugins.stash.issue; /** * This class is a representation of the Stash Diff view. * <p> * Purpose is to check if a SonarQube issue belongs to the Stash diff view before posting. * Indeed, Stash Diff view displays only comments which belong to this view. */ public class StashDiffReport { public static final int VICINITY_RANGE_NONE = 0; private List<StashDiff> diffs; public StashDiffReport() { this.diffs = new ArrayList<>(); } public List<StashDiff> getDiffs() { return Collections.unmodifiableList(diffs); } public void add(StashDiff diff) { diffs.add(diff); } public void add(StashDiffReport report) { diffs.addAll(report.getDiffs()); } private static boolean inVicinityOfChangedDiff(StashDiff diff, long destination, int range) { if (range <= 0) { return false; } long lower = Math.min(diff.getSource(), diff.getDestination()); long upper = Math.max(diff.getSource(), diff.getDestination()); return Range.closed(lower - range, upper + range).contains(destination); } private static boolean isChangedDiff(StashDiff diff, long destination) { return diff.getDestination() == destination; } private static boolean lineIsChangedDiff(StashDiff diff) {
// Path: src/main/java/org/sonar/plugins/stash/StashPlugin.java // public enum IssueType { // CONTEXT, // REMOVED, // ADDED, // } // Path: src/main/java/org/sonar/plugins/stash/issue/StashDiffReport.java import com.google.common.collect.Range; import java.util.Collections; import java.util.Objects; import java.util.ArrayList; import java.util.List; import org.sonar.plugins.stash.StashPlugin.IssueType; package org.sonar.plugins.stash.issue; /** * This class is a representation of the Stash Diff view. * <p> * Purpose is to check if a SonarQube issue belongs to the Stash diff view before posting. * Indeed, Stash Diff view displays only comments which belong to this view. */ public class StashDiffReport { public static final int VICINITY_RANGE_NONE = 0; private List<StashDiff> diffs; public StashDiffReport() { this.diffs = new ArrayList<>(); } public List<StashDiff> getDiffs() { return Collections.unmodifiableList(diffs); } public void add(StashDiff diff) { diffs.add(diff); } public void add(StashDiffReport report) { diffs.addAll(report.getDiffs()); } private static boolean inVicinityOfChangedDiff(StashDiff diff, long destination, int range) { if (range <= 0) { return false; } long lower = Math.min(diff.getSource(), diff.getDestination()); long upper = Math.max(diff.getSource(), diff.getDestination()); return Range.closed(lower - range, upper + range).contains(destination); } private static boolean isChangedDiff(StashDiff diff, long destination) { return diff.getDestination() == destination; } private static boolean lineIsChangedDiff(StashDiff diff) {
return !diff.getType().equals(IssueType.CONTEXT);
AmadeusITGroup/sonar-stash
src/main/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollector.java
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static boolean isProjectWide(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (!(ic instanceof InputModule)) { // return false; // } // InputModule im = (InputModule) ic; // if (im.key() == null) { // return false; // } // return CharMatcher.is(':').countIn(im.key()) == 0; // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // }
import java.util.Set; import static org.sonar.plugins.stash.StashPluginUtils.isProjectWide; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.plugins.stash.IssuePathResolver;
package org.sonar.plugins.stash.issue.collector; public final class SonarQubeCollector { private static final Logger LOGGER = Loggers.get(SonarQubeCollector.class); private SonarQubeCollector() { // Hiding implicit public constructor with an explicit private one (squid:S1118) } /** * Create issue report according to issue list generated during SonarQube * analysis. */ public static List<PostJobIssue> extractIssueReport(
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static boolean isProjectWide(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (!(ic instanceof InputModule)) { // return false; // } // InputModule im = (InputModule) ic; // if (im.key() == null) { // return false; // } // return CharMatcher.is(':').countIn(im.key()) == 0; // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // Path: src/main/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollector.java import java.util.Set; import static org.sonar.plugins.stash.StashPluginUtils.isProjectWide; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.plugins.stash.IssuePathResolver; package org.sonar.plugins.stash.issue.collector; public final class SonarQubeCollector { private static final Logger LOGGER = Loggers.get(SonarQubeCollector.class); private SonarQubeCollector() { // Hiding implicit public constructor with an explicit private one (squid:S1118) } /** * Create issue report according to issue list generated during SonarQube * analysis. */ public static List<PostJobIssue> extractIssueReport(
Iterable<PostJobIssue> issues, IssuePathResolver issuePathResolver,
AmadeusITGroup/sonar-stash
src/main/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollector.java
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static boolean isProjectWide(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (!(ic instanceof InputModule)) { // return false; // } // InputModule im = (InputModule) ic; // if (im.key() == null) { // return false; // } // return CharMatcher.is(':').countIn(im.key()) == 0; // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // }
import java.util.Set; import static org.sonar.plugins.stash.StashPluginUtils.isProjectWide; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.plugins.stash.IssuePathResolver;
Iterable<PostJobIssue> issues, IssuePathResolver issuePathResolver, boolean includeExistingIssues, Set<RuleKey> excludedRules) { return StreamSupport.stream( issues.spliterator(), false) .filter(issue -> shouldIncludeIssue( issue, issuePathResolver, includeExistingIssues, excludedRules )) .collect(Collectors.toList()); } static boolean shouldIncludeIssue( PostJobIssue issue, IssuePathResolver issuePathResolver, boolean includeExistingIssues, Set<RuleKey> excludedRules ) { if (!includeExistingIssues && !issue.isNew()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Issue {} is not a new issue and so, not added to the report", issue.key()); } return false; } if (excludedRules.contains(issue.ruleKey())) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Issue {} is ignored, not added to the report", issue.key()); } return false; } String path = issuePathResolver.getIssuePath(issue);
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static boolean isProjectWide(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (!(ic instanceof InputModule)) { // return false; // } // InputModule im = (InputModule) ic; // if (im.key() == null) { // return false; // } // return CharMatcher.is(':').countIn(im.key()) == 0; // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // Path: src/main/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollector.java import java.util.Set; import static org.sonar.plugins.stash.StashPluginUtils.isProjectWide; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.plugins.stash.IssuePathResolver; Iterable<PostJobIssue> issues, IssuePathResolver issuePathResolver, boolean includeExistingIssues, Set<RuleKey> excludedRules) { return StreamSupport.stream( issues.spliterator(), false) .filter(issue -> shouldIncludeIssue( issue, issuePathResolver, includeExistingIssues, excludedRules )) .collect(Collectors.toList()); } static boolean shouldIncludeIssue( PostJobIssue issue, IssuePathResolver issuePathResolver, boolean includeExistingIssues, Set<RuleKey> excludedRules ) { if (!includeExistingIssues && !issue.isNew()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Issue {} is not a new issue and so, not added to the report", issue.key()); } return false; } if (excludedRules.contains(issue.ruleKey())) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Issue {} is ignored, not added to the report", issue.key()); } return false; } String path = issuePathResolver.getIssuePath(issue);
if (!isProjectWide(issue) && path == null) {
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/fixtures/SonarQube.java
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public class TestUtils { // private TestUtils() {} // // public static <T> T notNull(T t) { // assertNotNull(t); // return t; // } // // public static void assertContains(String s, String expected) { // assertNotNull(s); // assertNotNull(expected); // assertTrue(s.contains(expected)); // } // // // The first request to wiremock may be slow. // // We could increase the timeout on our StashClient but then all the timeout test take longer. // // So instead we perform a dummy request on each test invocation with a high timeout. // // We now have many more request than before, but are faster anyways. // public static void primeWireMock(WireMockServer wireMock) throws Exception { // StubMapping primingMapping = WireMock.get(WireMock.urlPathEqualTo("/")).build(); // wireMock.addStubMapping(primingMapping); // HttpURLConnection conn = (HttpURLConnection)new URL("http://127.0.0.1:" + wireMock.port()).openConnection(); // conn.setConnectTimeout(1000); // conn.setConnectTimeout(1000); // conn.connect(); // conn.getResponseCode(); // wireMock.removeStub(primingMapping); // wireMock.resetRequests(); // } // // public static WrappedProcessBuilder createProcess(String prefix, String... command) { // ProcessBuilder pb = new ProcessBuilder(command); // return new WrappedProcessBuilder(prefix, pb); // } // // public static class WrappedProcessBuilder { // private final String prefix; // private final ProcessBuilder wrapped; // // private WrappedProcessBuilder(String prefix, ProcessBuilder wrapped) { // this.prefix = prefix; // this.wrapped = wrapped; // } // // public WrappedProcessBuilder directory(File directory) { // wrapped.directory(directory); // return this; // } // // public Process start() throws IOException { // return new WrappedProcess(prefix, wrapped.start()); // } // // public List<String> command() { // return wrapped.command(); // } // // public Map<String, String> environment() { // return wrapped.environment(); // } // } // // public static class WrappedProcess extends Process { // private final Process wrapped; // private final ForwarderThread outputLogger; // private final ForwarderThread errorLogger; // // private WrappedProcess(String prefix, Process wrapped) { // this.wrapped = wrapped; // errorLogger = new ForwarderThread(prefix, wrapped.getErrorStream()); // errorLogger.start(); // outputLogger = new ForwarderThread(prefix, wrapped.getInputStream()); // outputLogger.start(); // } // // @Override // public OutputStream getOutputStream() { // return wrapped.getOutputStream(); // } // // @Override // public InputStream getInputStream() { // return wrapped.getInputStream(); // } // // @Override // public InputStream getErrorStream() { // return wrapped.getErrorStream(); // } // // @Override // public int waitFor() throws InterruptedException { // int exitCode = wrapped.waitFor(); // stopLoggers(); // return exitCode; // } // // @Override // public int exitValue() { // return wrapped.exitValue(); // } // // @Override // public void destroy() { // wrapped.destroy(); // } // // private void stopLoggers() throws InterruptedException { // outputLogger.interrupt(); // errorLogger.interrupt(); // outputLogger.join(); // errorLogger.join(); // } // } // // private static class ForwarderThread extends Thread implements AutoCloseable { // // private final String prefix; // private final InputStream input; // // private ForwarderThread(String prefix, InputStream input) { // this.prefix = "[" + prefix + "] "; // this.input = input; // setDaemon(true); // } // // @Override // public void run() { // try (BufferedReader lineReader = new BufferedReader(new InputStreamReader(input))) { // while (!Thread.interrupted()) { // String line = lineReader.readLine(); // if (line != null) { // System.out.println(prefix + line); // //logger.info(line); // } // } // } catch (IOException e) { // /* ignored */ // } // } // // @Override // public void close() throws InterruptedException { // interrupt(); // join(); // } // } // // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // public static InputFile inputFile(String moduleKey, Path moduleBaseDir, String path) { // return TestInputFileBuilder.create(moduleKey, path).setModuleBaseDir(moduleBaseDir).build(); // } // }
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.CoreProperties; import org.sonar.plugins.stash.TestUtils;
} File exec = installDir.resolve("bin").resolve(os + "-" + arch).resolve(binary).toFile(); if (!exec.exists()) { throw new IllegalArgumentException(); } if (!exec.canExecute()) { throw new IllegalArgumentException(); } return exec; } public void setUp() { // noop } public Properties getConfig() { return config; } protected void writeConfig() throws Exception { File configFile = installDir.resolve("conf").resolve("sonar.properties").toFile(); configFile.delete(); try (OutputStream configStream = new FileOutputStream(configFile)) { config.store(configStream, null); } } public void startAsync() throws Exception { writeConfig();
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public class TestUtils { // private TestUtils() {} // // public static <T> T notNull(T t) { // assertNotNull(t); // return t; // } // // public static void assertContains(String s, String expected) { // assertNotNull(s); // assertNotNull(expected); // assertTrue(s.contains(expected)); // } // // // The first request to wiremock may be slow. // // We could increase the timeout on our StashClient but then all the timeout test take longer. // // So instead we perform a dummy request on each test invocation with a high timeout. // // We now have many more request than before, but are faster anyways. // public static void primeWireMock(WireMockServer wireMock) throws Exception { // StubMapping primingMapping = WireMock.get(WireMock.urlPathEqualTo("/")).build(); // wireMock.addStubMapping(primingMapping); // HttpURLConnection conn = (HttpURLConnection)new URL("http://127.0.0.1:" + wireMock.port()).openConnection(); // conn.setConnectTimeout(1000); // conn.setConnectTimeout(1000); // conn.connect(); // conn.getResponseCode(); // wireMock.removeStub(primingMapping); // wireMock.resetRequests(); // } // // public static WrappedProcessBuilder createProcess(String prefix, String... command) { // ProcessBuilder pb = new ProcessBuilder(command); // return new WrappedProcessBuilder(prefix, pb); // } // // public static class WrappedProcessBuilder { // private final String prefix; // private final ProcessBuilder wrapped; // // private WrappedProcessBuilder(String prefix, ProcessBuilder wrapped) { // this.prefix = prefix; // this.wrapped = wrapped; // } // // public WrappedProcessBuilder directory(File directory) { // wrapped.directory(directory); // return this; // } // // public Process start() throws IOException { // return new WrappedProcess(prefix, wrapped.start()); // } // // public List<String> command() { // return wrapped.command(); // } // // public Map<String, String> environment() { // return wrapped.environment(); // } // } // // public static class WrappedProcess extends Process { // private final Process wrapped; // private final ForwarderThread outputLogger; // private final ForwarderThread errorLogger; // // private WrappedProcess(String prefix, Process wrapped) { // this.wrapped = wrapped; // errorLogger = new ForwarderThread(prefix, wrapped.getErrorStream()); // errorLogger.start(); // outputLogger = new ForwarderThread(prefix, wrapped.getInputStream()); // outputLogger.start(); // } // // @Override // public OutputStream getOutputStream() { // return wrapped.getOutputStream(); // } // // @Override // public InputStream getInputStream() { // return wrapped.getInputStream(); // } // // @Override // public InputStream getErrorStream() { // return wrapped.getErrorStream(); // } // // @Override // public int waitFor() throws InterruptedException { // int exitCode = wrapped.waitFor(); // stopLoggers(); // return exitCode; // } // // @Override // public int exitValue() { // return wrapped.exitValue(); // } // // @Override // public void destroy() { // wrapped.destroy(); // } // // private void stopLoggers() throws InterruptedException { // outputLogger.interrupt(); // errorLogger.interrupt(); // outputLogger.join(); // errorLogger.join(); // } // } // // private static class ForwarderThread extends Thread implements AutoCloseable { // // private final String prefix; // private final InputStream input; // // private ForwarderThread(String prefix, InputStream input) { // this.prefix = "[" + prefix + "] "; // this.input = input; // setDaemon(true); // } // // @Override // public void run() { // try (BufferedReader lineReader = new BufferedReader(new InputStreamReader(input))) { // while (!Thread.interrupted()) { // String line = lineReader.readLine(); // if (line != null) { // System.out.println(prefix + line); // //logger.info(line); // } // } // } catch (IOException e) { // /* ignored */ // } // } // // @Override // public void close() throws InterruptedException { // interrupt(); // join(); // } // } // // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // public static InputFile inputFile(String moduleKey, Path moduleBaseDir, String path) { // return TestInputFileBuilder.create(moduleKey, path).setModuleBaseDir(moduleBaseDir).build(); // } // } // Path: src/test/java/org/sonar/plugins/stash/fixtures/SonarQube.java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.CoreProperties; import org.sonar.plugins.stash.TestUtils; } File exec = installDir.resolve("bin").resolve(os + "-" + arch).resolve(binary).toFile(); if (!exec.exists()) { throw new IllegalArgumentException(); } if (!exec.canExecute()) { throw new IllegalArgumentException(); } return exec; } public void setUp() { // noop } public Properties getConfig() { return config; } protected void writeConfig() throws Exception { File configFile = installDir.resolve("conf").resolve("sonar.properties").toFile(); configFile.delete(); try (OutputStream configStream = new FileOutputStream(configFile)) { config.store(configStream, null); } } public void startAsync() throws Exception { writeConfig();
process = TestUtils.createProcess("sonarqube", this.getExecutable().toString(), "start")
AmadeusITGroup/sonar-stash
src/main/java/org/sonar/plugins/stash/issue/MarkdownPrinter.java
// Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // }
import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimaps; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Arrays; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.collect.ArrayListMultimap; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.IssuePathResolver; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity;
package org.sonar.plugins.stash.issue; public final class MarkdownPrinter { private static final String NEW_LINE = "\n"; private static final String CODING_RULES_RULE_KEY = "coding_rules#rule_key="; private int issueThreshold; private String sonarQubeURL; private int includeFilesInOverview;
// Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // Path: src/main/java/org/sonar/plugins/stash/issue/MarkdownPrinter.java import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimaps; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Arrays; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.collect.ArrayListMultimap; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.IssuePathResolver; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; package org.sonar.plugins.stash.issue; public final class MarkdownPrinter { private static final String NEW_LINE = "\n"; private static final String CODING_RULES_RULE_KEY = "coding_rules#rule_key="; private int issueThreshold; private String sonarQubeURL; private int includeFilesInOverview;
private IssuePathResolver issuePathResolver;
AmadeusITGroup/sonar-stash
src/main/java/org/sonar/plugins/stash/issue/MarkdownPrinter.java
// Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // }
import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimaps; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Arrays; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.collect.ArrayListMultimap; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.IssuePathResolver; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity;
package org.sonar.plugins.stash.issue; public final class MarkdownPrinter { private static final String NEW_LINE = "\n"; private static final String CODING_RULES_RULE_KEY = "coding_rules#rule_key="; private int issueThreshold; private String sonarQubeURL; private int includeFilesInOverview; private IssuePathResolver issuePathResolver; private Severity[] orderedSeverities; public MarkdownPrinter( int issueThreshold, String sonarQubeURL, int includeFilesInOverview, IssuePathResolver issuePathResolver ) { this.issueThreshold = issueThreshold; this.sonarQubeURL = sonarQubeURL; this.includeFilesInOverview = includeFilesInOverview; this.issuePathResolver = issuePathResolver; orderedSeverities = Severity.values(); Arrays.sort(orderedSeverities, Comparator.reverseOrder()); } public static String printSeverityMarkdown(org.sonar.api.batch.rule.Severity severity) { StringBuilder sb = new StringBuilder(); sb.append("*").append(severity.name().toUpperCase()).append("*").append(" - "); return sb.toString(); } public static String printIssueNumberBySeverityMarkdown(Collection<PostJobIssue> report, Severity severity) { StringBuilder sb = new StringBuilder();
// Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // Path: src/main/java/org/sonar/plugins/stash/issue/MarkdownPrinter.java import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimaps; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Arrays; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.collect.ArrayListMultimap; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.IssuePathResolver; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; package org.sonar.plugins.stash.issue; public final class MarkdownPrinter { private static final String NEW_LINE = "\n"; private static final String CODING_RULES_RULE_KEY = "coding_rules#rule_key="; private int issueThreshold; private String sonarQubeURL; private int includeFilesInOverview; private IssuePathResolver issuePathResolver; private Severity[] orderedSeverities; public MarkdownPrinter( int issueThreshold, String sonarQubeURL, int includeFilesInOverview, IssuePathResolver issuePathResolver ) { this.issueThreshold = issueThreshold; this.sonarQubeURL = sonarQubeURL; this.includeFilesInOverview = includeFilesInOverview; this.issuePathResolver = issuePathResolver; orderedSeverities = Severity.values(); Arrays.sort(orderedSeverities, Comparator.reverseOrder()); } public static String printSeverityMarkdown(org.sonar.api.batch.rule.Severity severity) { StringBuilder sb = new StringBuilder(); sb.append("*").append(severity.name().toUpperCase()).append("*").append(" - "); return sb.toString(); } public static String printIssueNumberBySeverityMarkdown(Collection<PostJobIssue> report, Severity severity) { StringBuilder sb = new StringBuilder();
long issueNumber = countIssuesBySeverity(report, severity);
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // }
import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver;
package org.sonar.plugins.stash.issue.collector; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class SonarQubeCollectorTest { @Mock
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // } // Path: src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver; package org.sonar.plugins.stash.issue.collector; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class SonarQubeCollectorTest { @Mock
DefaultIssue issue1;
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // }
import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver;
package org.sonar.plugins.stash.issue.collector; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class SonarQubeCollectorTest { @Mock DefaultIssue issue1; @Mock DefaultIssue issue2; @Mock InputFile inputFile1; @Mock InputFile inputFile2; Set<RuleKey> excludedRules;
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // } // Path: src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver; package org.sonar.plugins.stash.issue.collector; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class SonarQubeCollectorTest { @Mock DefaultIssue issue1; @Mock DefaultIssue issue2; @Mock InputFile inputFile1; @Mock InputFile inputFile2; Set<RuleKey> excludedRules;
IssuePathResolver ipr = new DummyIssuePathResolver();
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // }
import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver;
package org.sonar.plugins.stash.issue.collector; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class SonarQubeCollectorTest { @Mock DefaultIssue issue1; @Mock DefaultIssue issue2; @Mock InputFile inputFile1; @Mock InputFile inputFile2; Set<RuleKey> excludedRules;
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // } // Path: src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver; package org.sonar.plugins.stash.issue.collector; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class SonarQubeCollectorTest { @Mock DefaultIssue issue1; @Mock DefaultIssue issue2; @Mock InputFile inputFile1; @Mock InputFile inputFile2; Set<RuleKey> excludedRules;
IssuePathResolver ipr = new DummyIssuePathResolver();
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // }
import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver;
package org.sonar.plugins.stash.issue.collector; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class SonarQubeCollectorTest { @Mock DefaultIssue issue1; @Mock DefaultIssue issue2; @Mock InputFile inputFile1; @Mock InputFile inputFile2; Set<RuleKey> excludedRules; IssuePathResolver ipr = new DummyIssuePathResolver(); @BeforeEach public void setUp() throws Exception { ///////// SonarQube issues ///////// when(issue1.line()).thenReturn(1); when(issue1.message()).thenReturn("message1"); when(issue1.key()).thenReturn("key1"); when(issue1.severity()).thenReturn(Severity.BLOCKER); when(issue1.componentKey()).thenReturn("module1:component1"); when(issue1.isNew()).thenReturn(true);
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // } // Path: src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver; package org.sonar.plugins.stash.issue.collector; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class SonarQubeCollectorTest { @Mock DefaultIssue issue1; @Mock DefaultIssue issue2; @Mock InputFile inputFile1; @Mock InputFile inputFile2; Set<RuleKey> excludedRules; IssuePathResolver ipr = new DummyIssuePathResolver(); @BeforeEach public void setUp() throws Exception { ///////// SonarQube issues ///////// when(issue1.line()).thenReturn(1); when(issue1.message()).thenReturn("message1"); when(issue1.key()).thenReturn("key1"); when(issue1.severity()).thenReturn(Severity.BLOCKER); when(issue1.componentKey()).thenReturn("module1:component1"); when(issue1.isNew()).thenReturn(true);
when(issue1.inputComponent()).thenReturn(inputFile("module1", "file1"));
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // }
import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver;
when(issue2.inputComponent()).thenReturn(inputFile("module2", "file2")); RuleKey rule2 = mock(RuleKey.class); when(rule2.toString()).thenReturn("rule2"); when(issue2.ruleKey()).thenReturn(rule2); inputFile1 = inputFile("module1", "project/path1"); inputFile2 = inputFile("module2", "project/path2"); when(issue1.inputComponent()).thenReturn(inputFile1); when(issue2.inputComponent()).thenReturn(inputFile2); excludedRules = new HashSet<>(); } @Test public void testExtractEmptyIssueReport() { ArrayList<PostJobIssue> issues = new ArrayList<>(); List<PostJobIssue> report = SonarQubeCollector.extractIssueReport(issues, ipr, false, excludedRules); assertEquals(0, report.size()); } @Test public void testExtractIssueReport() { ArrayList<PostJobIssue> issues = new ArrayList<>(); issues.add(issue1); issues.add(issue2); List<PostJobIssue> report = SonarQubeCollector.extractIssueReport(issues, ipr, false, excludedRules); assertEquals(2, report.size());
// Path: src/main/java/org/sonar/plugins/stash/StashPluginUtils.java // public static long countIssuesBySeverity(Collection<PostJobIssue> issues, final Severity severity) { // return issues.stream().filter(i -> severity.equals(i.severity())).count(); // } // // Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // // Path: src/test/java/org/sonar/plugins/stash/DefaultIssue.java // public class DefaultIssue implements PostJobIssue { // private String key, componentKey, message; // private InputComponent inputComponent; // private boolean isNew; // private Severity severity; // private Integer line; // private RuleKey ruleKey; // // public String key() { // return key; // } // // public DefaultIssue setKey(String key) { // this.key = key; // return this; // } // // public String componentKey() { // return componentKey; // } // // public DefaultIssue setComponentKey(String componentKey) { // this.componentKey = componentKey; // return this; // } // // public String message() { // return message; // } // // public DefaultIssue setMessage(String message) { // this.message = message; // return this; // } // // public InputComponent inputComponent() { // return inputComponent; // } // // public DefaultIssue setInputComponent(InputComponent inputComponent) { // this.inputComponent = inputComponent; // return this; // } // // @Override // public boolean isNew() { // return isNew; // } // // public DefaultIssue setNew(boolean aNew) { // isNew = aNew; // return this; // } // // public Severity severity() { // return severity; // } // // public DefaultIssue setSeverity(Severity severity) { // this.severity = severity; // return this; // } // // public RuleKey ruleKey() { // return ruleKey; // } // // public DefaultIssue setRuleKey(RuleKey ruleKey) { // this.ruleKey = ruleKey; // return this; // } // // public DefaultIssue setLine(Integer line) { // this.line = line; // return this; // } // // @Override // public Integer line() { // return line; // } // } // // Path: src/main/java/org/sonar/plugins/stash/IssuePathResolver.java // @FunctionalInterface // public interface IssuePathResolver { // String getIssuePath(PostJobIssue issue); // } // // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyIssuePathResolver.java // public class DummyIssuePathResolver implements IssuePathResolver { // @Override // public String getIssuePath(PostJobIssue issue) { // InputComponent ic = issue.inputComponent(); // if (ic == null) { // return null; // } // return ((InputFile) ic).relativePath(); // } // } // Path: src/test/java/org/sonar/plugins/stash/issue/collector/SonarQubeCollectorTest.java import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.plugins.stash.StashPluginUtils.countIssuesBySeverity; import static org.sonar.plugins.stash.TestUtils.inputFile; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; import org.sonar.plugins.stash.DefaultIssue; import org.sonar.plugins.stash.IssuePathResolver; import org.sonar.plugins.stash.fixtures.DummyIssuePathResolver; when(issue2.inputComponent()).thenReturn(inputFile("module2", "file2")); RuleKey rule2 = mock(RuleKey.class); when(rule2.toString()).thenReturn("rule2"); when(issue2.ruleKey()).thenReturn(rule2); inputFile1 = inputFile("module1", "project/path1"); inputFile2 = inputFile("module2", "project/path2"); when(issue1.inputComponent()).thenReturn(inputFile1); when(issue2.inputComponent()).thenReturn(inputFile2); excludedRules = new HashSet<>(); } @Test public void testExtractEmptyIssueReport() { ArrayList<PostJobIssue> issues = new ArrayList<>(); List<PostJobIssue> report = SonarQubeCollector.extractIssueReport(issues, ipr, false, excludedRules); assertEquals(0, report.size()); } @Test public void testExtractIssueReport() { ArrayList<PostJobIssue> issues = new ArrayList<>(); issues.add(issue1); issues.add(issue2); List<PostJobIssue> report = SonarQubeCollector.extractIssueReport(issues, ipr, false, excludedRules); assertEquals(2, report.size());
assertEquals(1, countIssuesBySeverity(report, Severity.BLOCKER));
AmadeusITGroup/sonar-stash
src/test/java/org/sonar/plugins/stash/fixtures/DummyPostJobIssue.java
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // }
import static org.sonar.plugins.stash.TestUtils.inputFile; import java.nio.file.Path; import javax.annotation.CheckForNull; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey;
package org.sonar.plugins.stash.fixtures; public class DummyPostJobIssue implements PostJobIssue { private final String key; private final RuleKey ruleKey; private final String componentKey; private final Integer line; private final String message; private final Severity severity; private final InputComponent component; public DummyPostJobIssue(Path moduleBaseDir, String key, RuleKey ruleKey, String module, String relativePath, Integer line, String message, Severity severity) { this.key = key; this.ruleKey = ruleKey; this.componentKey = module + ":" + relativePath; this.line = line; this.message = message; this.severity = severity;
// Path: src/test/java/org/sonar/plugins/stash/TestUtils.java // public static InputFile inputFile(String moduleKey, String path) { // return TestInputFileBuilder.create(moduleKey, path).build(); // } // Path: src/test/java/org/sonar/plugins/stash/fixtures/DummyPostJobIssue.java import static org.sonar.plugins.stash.TestUtils.inputFile; import java.nio.file.Path; import javax.annotation.CheckForNull; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.postjob.issue.PostJobIssue; import org.sonar.api.batch.rule.Severity; import org.sonar.api.rule.RuleKey; package org.sonar.plugins.stash.fixtures; public class DummyPostJobIssue implements PostJobIssue { private final String key; private final RuleKey ruleKey; private final String componentKey; private final Integer line; private final String message; private final Severity severity; private final InputComponent component; public DummyPostJobIssue(Path moduleBaseDir, String key, RuleKey ruleKey, String module, String relativePath, Integer line, String message, Severity severity) { this.key = key; this.ruleKey = ruleKey; this.componentKey = module + ":" + relativePath; this.line = line; this.message = message; this.severity = severity;
component = inputFile(componentKey, moduleBaseDir, relativePath);
StripesFramework/stripes-stuff
src/test/java/org/stripesstuff/tests/session/action/Child2PersonActionBean.java
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // }
import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution;
package org.stripesstuff.tests.session.action; public class Child2PersonActionBean extends AbstractPersonActionBean { public Resolution reset() {
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // } // Path: src/test/java/org/stripesstuff/tests/session/action/Child2PersonActionBean.java import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; package org.stripesstuff.tests.session.action; public class Child2PersonActionBean extends AbstractPersonActionBean { public Resolution reset() {
Person person = new Person();
StripesFramework/stripes-stuff
src/test/java/org/stripesstuff/tests/session/action/Child1PersonActionBean.java
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // }
import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution;
package org.stripesstuff.tests.session.action; public class Child1PersonActionBean extends AbstractPersonActionBean { public Resolution reset() {
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // } // Path: src/test/java/org/stripesstuff/tests/session/action/Child1PersonActionBean.java import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; package org.stripesstuff.tests.session.action; public class Child1PersonActionBean extends AbstractPersonActionBean { public Resolution reset() {
Person person = new Person();
StripesFramework/stripes-stuff
src/test/java/org/stripesstuff/tests/session/action/PersonActionBean.java
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // }
import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.HandlesEvent; import net.sourceforge.stripes.action.Resolution;
package org.stripesstuff.tests.session.action; public class PersonActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * Person. */ @Session
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // } // Path: src/test/java/org/stripesstuff/tests/session/action/PersonActionBean.java import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.HandlesEvent; import net.sourceforge.stripes.action.Resolution; package org.stripesstuff.tests.session.action; public class PersonActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * Person. */ @Session
private Person person;
StripesFramework/stripes-stuff
src/test/java/org/stripesstuff/tests/session/action/FirstKeyActionBean.java
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // }
import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.HandlesEvent; import net.sourceforge.stripes.action.Resolution;
package org.stripesstuff.tests.session.action; /** * Test key attribute of {@link Session} * * @author Christian Poitras */ public class FirstKeyActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * A person. */ @Session(key="FirstKeyActionBean#person")
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // } // Path: src/test/java/org/stripesstuff/tests/session/action/FirstKeyActionBean.java import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.HandlesEvent; import net.sourceforge.stripes.action.Resolution; package org.stripesstuff.tests.session.action; /** * Test key attribute of {@link Session} * * @author Christian Poitras */ public class FirstKeyActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * A person. */ @Session(key="FirstKeyActionBean#person")
private Person person;
StripesFramework/stripes-stuff
src/test/java/org/stripesstuff/tests/session/action/AbstractPersonActionBean.java
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // }
import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution;
package org.stripesstuff.tests.session.action; public abstract class AbstractPersonActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * Person. */ @Session
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // } // Path: src/test/java/org/stripesstuff/tests/session/action/AbstractPersonActionBean.java import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; package org.stripesstuff.tests.session.action; public abstract class AbstractPersonActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * Person. */ @Session
private Person person;
StripesFramework/stripes-stuff
src/test/java/org/stripesstuff/tests/session/action/ListActionBean.java
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // }
import java.util.List; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person;
package org.stripesstuff.tests.session.action; /** * Used to test list of objects. * * @author Christian Poitras */ public class ListActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * Number list. */ @Session private List<Integer> numbers; /** * Person list. */ @Session
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // } // Path: src/test/java/org/stripesstuff/tests/session/action/ListActionBean.java import java.util.List; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person; package org.stripesstuff.tests.session.action; /** * Used to test list of objects. * * @author Christian Poitras */ public class ListActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * Number list. */ @Session private List<Integer> numbers; /** * Person list. */ @Session
private List<Person> persons;
StripesFramework/stripes-stuff
src/test/java/org/stripesstuff/tests/session/action/SecondKeyActionBean.java
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // }
import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution;
package org.stripesstuff.tests.session.action; /** * Test key attribute of {@link Session} * * @author Christian Poitras */ public class SecondKeyActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * A person. */ @Session(key="FirstKeyActionBean#person")
// Path: src/test/java/org/stripesstuff/tests/session/bean/Person.java // public class Person { // // /** // * First name. // */ // private String firstName; // /** // * Last name. // */ // private String lastName; // // // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // } // Path: src/test/java/org/stripesstuff/tests/session/action/SecondKeyActionBean.java import org.stripesstuff.plugin.session.Session; import org.stripesstuff.tests.session.bean.Person; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; package org.stripesstuff.tests.session.action; /** * Test key attribute of {@link Session} * * @author Christian Poitras */ public class SecondKeyActionBean implements ActionBean { private ActionBeanContext context; public ActionBeanContext getContext() {return context;} public void setContext(ActionBeanContext context) {this.context = context;} /** * A person. */ @Session(key="FirstKeyActionBean#person")
private Person person;
requery/sqlite-android
sqlite-android/src/main/java/io/requery/android/database/sqlite/SQLiteDatabase.java
// Path: sqlite-android/src/main/java/io/requery/android/database/DatabaseErrorHandler.java // public interface DatabaseErrorHandler { // // /** // * The method invoked when database corruption is detected. // * @param dbObj the {@link SQLiteDatabase} object representing the database on which corruption // * is detected. // */ // void onCorruption(SQLiteDatabase dbObj); // } // // Path: sqlite-android/src/main/java/io/requery/android/database/DefaultDatabaseErrorHandler.java // public final class DefaultDatabaseErrorHandler implements DatabaseErrorHandler { // // private static final String TAG = "DefaultDatabaseError"; // // @Override // public void onCorruption(SQLiteDatabase dbObj) { // Log.e(TAG, "Corruption reported by sqlite on database: " + dbObj.getPath()); // // // is the corruption detected even before database could be 'opened'? // if (!dbObj.isOpen()) { // // database files are not even openable. delete this database file. // // NOTE if the database has attached databases, then any of them could be corrupt. // // and not deleting all of them could cause corrupted database file to remain and // // make the application crash on database open operation. To avoid this problem, // // the application should provide its own {@link DatabaseErrorHandler} impl class // // to delete ALL files of the database (including the attached databases). // deleteDatabaseFile(dbObj.getPath()); // return; // } // // List<Pair<String, String>> attachedDbs = null; // try { // // Close the database, which will cause subsequent operations to fail. // // before that, get the attached database list first. // try { // attachedDbs = dbObj.getAttachedDbs(); // } catch (SQLiteException e) { // /* ignore */ // } // try { // dbObj.close(); // } catch (SQLiteException e) { // /* ignore */ // } // } finally { // // Delete all files of this corrupt database and/or attached databases // if (attachedDbs != null) { // for (Pair<String, String> p : attachedDbs) { // deleteDatabaseFile(p.second); // } // } else { // // attachedDbs = null is possible when the database is so corrupt that even // // "PRAGMA database_list;" also fails. delete the main database file // deleteDatabaseFile(dbObj.getPath()); // } // } // } // // private void deleteDatabaseFile(String fileName) { // if (fileName.equalsIgnoreCase(":memory:") || fileName.trim().length() == 0) { // return; // } // Log.e(TAG, "deleting the database file: " + fileName); // try { // SQLiteDatabase.deleteDatabase(new File(fileName)); // } catch (Exception e) { // /* print warning and ignore exception */ // Log.w(TAG, "delete failed: " + e.getMessage()); // } // } // }
import android.annotation.SuppressLint; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabaseCorruptException; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteTransactionListener; import android.os.Build; import android.os.Looper; import android.os.ParcelFileDescriptor; import android.text.TextUtils; import android.util.EventLog; import android.util.Log; import android.util.Pair; import android.util.Printer; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.os.CancellationSignal; import androidx.core.os.OperationCanceledException; import androidx.sqlite.db.SupportSQLiteDatabase; import androidx.sqlite.db.SupportSQLiteQuery; import io.requery.android.database.DatabaseErrorHandler; import io.requery.android.database.DefaultDatabaseErrorHandler; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.WeakHashMap;
/** Integer flag definition for the database open options */ @SuppressLint("UniqueConstants") // duplicate values provided for compatibility @IntDef(flag = true, value = { OPEN_READONLY, OPEN_READWRITE, OPEN_CREATE, OPEN_URI, OPEN_NOMUTEX, OPEN_FULLMUTEX, OPEN_SHAREDCACHE, OPEN_PRIVATECACHE, CREATE_IF_NECESSARY, ENABLE_WRITE_AHEAD_LOGGING}) @Retention(RetentionPolicy.SOURCE) public @interface OpenFlags { } /** * Absolute max value that can be set by {@link #setMaxSqlCacheSize(int)}. * * Each prepared-statement is between 1K - 6K, depending on the complexity of the * SQL statement & schema. A large SQL cache may use a significant amount of memory. */ public static final int MAX_SQL_CACHE_SIZE = 100; private SQLiteDatabase(SQLiteDatabaseConfiguration configuration, CursorFactory cursorFactory, DatabaseErrorHandler errorHandler) { mCursorFactory = cursorFactory;
// Path: sqlite-android/src/main/java/io/requery/android/database/DatabaseErrorHandler.java // public interface DatabaseErrorHandler { // // /** // * The method invoked when database corruption is detected. // * @param dbObj the {@link SQLiteDatabase} object representing the database on which corruption // * is detected. // */ // void onCorruption(SQLiteDatabase dbObj); // } // // Path: sqlite-android/src/main/java/io/requery/android/database/DefaultDatabaseErrorHandler.java // public final class DefaultDatabaseErrorHandler implements DatabaseErrorHandler { // // private static final String TAG = "DefaultDatabaseError"; // // @Override // public void onCorruption(SQLiteDatabase dbObj) { // Log.e(TAG, "Corruption reported by sqlite on database: " + dbObj.getPath()); // // // is the corruption detected even before database could be 'opened'? // if (!dbObj.isOpen()) { // // database files are not even openable. delete this database file. // // NOTE if the database has attached databases, then any of them could be corrupt. // // and not deleting all of them could cause corrupted database file to remain and // // make the application crash on database open operation. To avoid this problem, // // the application should provide its own {@link DatabaseErrorHandler} impl class // // to delete ALL files of the database (including the attached databases). // deleteDatabaseFile(dbObj.getPath()); // return; // } // // List<Pair<String, String>> attachedDbs = null; // try { // // Close the database, which will cause subsequent operations to fail. // // before that, get the attached database list first. // try { // attachedDbs = dbObj.getAttachedDbs(); // } catch (SQLiteException e) { // /* ignore */ // } // try { // dbObj.close(); // } catch (SQLiteException e) { // /* ignore */ // } // } finally { // // Delete all files of this corrupt database and/or attached databases // if (attachedDbs != null) { // for (Pair<String, String> p : attachedDbs) { // deleteDatabaseFile(p.second); // } // } else { // // attachedDbs = null is possible when the database is so corrupt that even // // "PRAGMA database_list;" also fails. delete the main database file // deleteDatabaseFile(dbObj.getPath()); // } // } // } // // private void deleteDatabaseFile(String fileName) { // if (fileName.equalsIgnoreCase(":memory:") || fileName.trim().length() == 0) { // return; // } // Log.e(TAG, "deleting the database file: " + fileName); // try { // SQLiteDatabase.deleteDatabase(new File(fileName)); // } catch (Exception e) { // /* print warning and ignore exception */ // Log.w(TAG, "delete failed: " + e.getMessage()); // } // } // } // Path: sqlite-android/src/main/java/io/requery/android/database/sqlite/SQLiteDatabase.java import android.annotation.SuppressLint; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabaseCorruptException; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteTransactionListener; import android.os.Build; import android.os.Looper; import android.os.ParcelFileDescriptor; import android.text.TextUtils; import android.util.EventLog; import android.util.Log; import android.util.Pair; import android.util.Printer; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.os.CancellationSignal; import androidx.core.os.OperationCanceledException; import androidx.sqlite.db.SupportSQLiteDatabase; import androidx.sqlite.db.SupportSQLiteQuery; import io.requery.android.database.DatabaseErrorHandler; import io.requery.android.database.DefaultDatabaseErrorHandler; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.WeakHashMap; /** Integer flag definition for the database open options */ @SuppressLint("UniqueConstants") // duplicate values provided for compatibility @IntDef(flag = true, value = { OPEN_READONLY, OPEN_READWRITE, OPEN_CREATE, OPEN_URI, OPEN_NOMUTEX, OPEN_FULLMUTEX, OPEN_SHAREDCACHE, OPEN_PRIVATECACHE, CREATE_IF_NECESSARY, ENABLE_WRITE_AHEAD_LOGGING}) @Retention(RetentionPolicy.SOURCE) public @interface OpenFlags { } /** * Absolute max value that can be set by {@link #setMaxSqlCacheSize(int)}. * * Each prepared-statement is between 1K - 6K, depending on the complexity of the * SQL statement & schema. A large SQL cache may use a significant amount of memory. */ public static final int MAX_SQL_CACHE_SIZE = 100; private SQLiteDatabase(SQLiteDatabaseConfiguration configuration, CursorFactory cursorFactory, DatabaseErrorHandler errorHandler) { mCursorFactory = cursorFactory;
mErrorHandler = errorHandler != null ? errorHandler : new DefaultDatabaseErrorHandler();
requery/sqlite-android
sqlite-android/src/main/java/io/requery/android/database/sqlite/SQLiteOpenHelper.java
// Path: sqlite-android/src/main/java/io/requery/android/database/DatabaseErrorHandler.java // public interface DatabaseErrorHandler { // // /** // * The method invoked when database corruption is detected. // * @param dbObj the {@link SQLiteDatabase} object representing the database on which corruption // * is detected. // */ // void onCorruption(SQLiteDatabase dbObj); // }
import android.content.Context; import android.database.sqlite.SQLiteException; import android.util.Log; import androidx.sqlite.db.SupportSQLiteOpenHelper; import io.requery.android.database.DatabaseErrorHandler;
/* * Copyright (C) 2007 The Android Open Source Project * * 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. */ // modified from original source see README at the top level of this project package io.requery.android.database.sqlite; /** * A helper class to manage database creation and version management. * * <p>You create a subclass implementing {@link #onCreate}, {@link #onUpgrade} and * optionally {@link #onOpen}, and this class takes care of opening the database * if it exists, creating it if it does not, and upgrading it as necessary. * Transactions are used to make sure the database is always in a sensible state. * * <p>This class makes it easy for {@link android.content.ContentProvider} * implementations to defer opening and upgrading the database until first use, * to avoid blocking application startup with long-running database upgrades. * * <p>For an example, see the NotePadProvider class in the NotePad sample application, * in the <em>samples/</em> directory of the SDK.</p> * * <p class="note"><strong>Note:</strong> this class assumes * monotonically increasing version numbers for upgrades.</p> */ @SuppressWarnings("unused") public abstract class SQLiteOpenHelper implements SupportSQLiteOpenHelper { private static final String TAG = SQLiteOpenHelper.class.getSimpleName(); // When true, getReadableDatabase returns a read-only database if it is just being opened. // The database handle is reopened in read/write mode when getWritableDatabase is called. // We leave this behavior disabled in production because it is inefficient and breaks // many applications. For debugging purposes it can be useful to turn on strict // read-only semantics to catch applications that call getReadableDatabase when they really // wanted getWritableDatabase. private static final boolean DEBUG_STRICT_READONLY = false; private final Context mContext; private final String mName; private final SQLiteDatabase.CursorFactory mFactory; private final int mNewVersion; private SQLiteDatabase mDatabase; private boolean mIsInitializing; private boolean mEnableWriteAheadLogging;
// Path: sqlite-android/src/main/java/io/requery/android/database/DatabaseErrorHandler.java // public interface DatabaseErrorHandler { // // /** // * The method invoked when database corruption is detected. // * @param dbObj the {@link SQLiteDatabase} object representing the database on which corruption // * is detected. // */ // void onCorruption(SQLiteDatabase dbObj); // } // Path: sqlite-android/src/main/java/io/requery/android/database/sqlite/SQLiteOpenHelper.java import android.content.Context; import android.database.sqlite.SQLiteException; import android.util.Log; import androidx.sqlite.db.SupportSQLiteOpenHelper; import io.requery.android.database.DatabaseErrorHandler; /* * Copyright (C) 2007 The Android Open Source Project * * 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. */ // modified from original source see README at the top level of this project package io.requery.android.database.sqlite; /** * A helper class to manage database creation and version management. * * <p>You create a subclass implementing {@link #onCreate}, {@link #onUpgrade} and * optionally {@link #onOpen}, and this class takes care of opening the database * if it exists, creating it if it does not, and upgrading it as necessary. * Transactions are used to make sure the database is always in a sensible state. * * <p>This class makes it easy for {@link android.content.ContentProvider} * implementations to defer opening and upgrading the database until first use, * to avoid blocking application startup with long-running database upgrades. * * <p>For an example, see the NotePadProvider class in the NotePad sample application, * in the <em>samples/</em> directory of the SDK.</p> * * <p class="note"><strong>Note:</strong> this class assumes * monotonically increasing version numbers for upgrades.</p> */ @SuppressWarnings("unused") public abstract class SQLiteOpenHelper implements SupportSQLiteOpenHelper { private static final String TAG = SQLiteOpenHelper.class.getSimpleName(); // When true, getReadableDatabase returns a read-only database if it is just being opened. // The database handle is reopened in read/write mode when getWritableDatabase is called. // We leave this behavior disabled in production because it is inefficient and breaks // many applications. For debugging purposes it can be useful to turn on strict // read-only semantics to catch applications that call getReadableDatabase when they really // wanted getWritableDatabase. private static final boolean DEBUG_STRICT_READONLY = false; private final Context mContext; private final String mName; private final SQLiteDatabase.CursorFactory mFactory; private final int mNewVersion; private SQLiteDatabase mDatabase; private boolean mIsInitializing; private boolean mEnableWriteAheadLogging;
private final DatabaseErrorHandler mErrorHandler;
requery/sqlite-android
sqlite-android/src/main/java/io/requery/android/database/sqlite/RequerySQLiteOpenHelperFactory.java
// Path: sqlite-android/src/main/java/io/requery/android/database/DatabaseErrorHandler.java // public interface DatabaseErrorHandler { // // /** // * The method invoked when database corruption is detected. // * @param dbObj the {@link SQLiteDatabase} object representing the database on which corruption // * is detected. // */ // void onCorruption(SQLiteDatabase dbObj); // }
import android.content.Context; import androidx.sqlite.db.SupportSQLiteOpenHelper; import io.requery.android.database.DatabaseErrorHandler; import java.util.Collections;
public void onCreate(SQLiteDatabase db) { callback.onCreate(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { callback.onUpgrade(db, oldVersion, newVersion); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { callback.onDowngrade(db, oldVersion, newVersion); } @Override public void onOpen(SQLiteDatabase db) { callback.onOpen(db); } @Override protected SQLiteDatabaseConfiguration createConfiguration(String path, int openFlags) { SQLiteDatabaseConfiguration config = super.createConfiguration(path, openFlags); for (ConfigurationOptions option : configurationOptions) { config = option.apply(config); } return config; } }
// Path: sqlite-android/src/main/java/io/requery/android/database/DatabaseErrorHandler.java // public interface DatabaseErrorHandler { // // /** // * The method invoked when database corruption is detected. // * @param dbObj the {@link SQLiteDatabase} object representing the database on which corruption // * is detected. // */ // void onCorruption(SQLiteDatabase dbObj); // } // Path: sqlite-android/src/main/java/io/requery/android/database/sqlite/RequerySQLiteOpenHelperFactory.java import android.content.Context; import androidx.sqlite.db.SupportSQLiteOpenHelper; import io.requery.android.database.DatabaseErrorHandler; import java.util.Collections; public void onCreate(SQLiteDatabase db) { callback.onCreate(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { callback.onUpgrade(db, oldVersion, newVersion); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { callback.onDowngrade(db, oldVersion, newVersion); } @Override public void onOpen(SQLiteDatabase db) { callback.onOpen(db); } @Override protected SQLiteDatabaseConfiguration createConfiguration(String path, int openFlags) { SQLiteDatabaseConfiguration config = super.createConfiguration(path, openFlags); for (ConfigurationOptions option : configurationOptions) { config = option.apply(config); } return config; } }
private static final class CallbackDatabaseErrorHandler implements DatabaseErrorHandler {
lbovet/jminix
src/test/java/org/jminix/resource/ValueParserTest.java
// Path: src/main/java/org/jminix/console/resource/ValueParser.java // public class ValueParser { // private static String stringArraySeparator = ";"; // // public static void setStringArraySeparator(String separator) { // Validate.notNull(separator); // stringArraySeparator = separator; // } // // public static boolean isNullOrEmpty(String value) { // return null == value || "".equals(value); // } // // public Object parse(String value, String type) { // Object result = null; // // if (type.equals("java.lang.String")) { // return value; // } else if (type.equals("java.lang.Byte") || type.equals("byte")) { // if (isNullOrEmpty(value)) { // return "byte".equals(type) ? (byte) 0 : null; // } // // result = new Byte(value); // } else if (type.equals("java.lang.Short") || type.equals("short")) { // if (isNullOrEmpty(value)) { // return "short".equals(type) ? (short) 0 : null; // } // // result = new Short(value); // } else if (type.equals("java.lang.Integer") || type.equals("int")) { // if (isNullOrEmpty(value)) { // return "int".equals(type) ? (int) 0 : null; // } // // result = new Integer(value); // } else if (type.equals("java.lang.Long") || type.equals("long")) { // if (isNullOrEmpty(value)) { // return "long".equals(type) ? (long) 0 : null; // } // // result = new Long(value); // } else if (type.equals("java.lang.Double") || type.equals("double")) { // if (isNullOrEmpty(value)) { // return "double".equals(type) ? (double) 0 : null; // } // // result = new Double(value); // } else if (type.equals("java.lang.Float") || type.equals("float")) { // if (isNullOrEmpty(value)) { // return "float".equals(type) ? (float) 0 : null; // } // // result = new Float(value); // } else if (type.equals("java.lang.Boolean") || type.equals("boolean")) { // if (isNullOrEmpty(value)) { // return "boolean".equals(type) ? false : null; // } // // result = new Boolean(value); // } else if (type.equals("[Ljava.lang.String;")) { // result = StringUtils.splitPreserveAllTokens(value, stringArraySeparator); // } // // if (result == null) { // throw new RuntimeException("Type " + type + " is not supported"); // } // // return result; // } // }
import static org.junit.Assert.assertEquals; import org.jminix.console.resource.ValueParser; import org.junit.Before; import org.junit.Test; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.runner.RunWith;
package org.jminix.resource; @RunWith(JUnit4ClassRunner.class) public class ValueParserTest {
// Path: src/main/java/org/jminix/console/resource/ValueParser.java // public class ValueParser { // private static String stringArraySeparator = ";"; // // public static void setStringArraySeparator(String separator) { // Validate.notNull(separator); // stringArraySeparator = separator; // } // // public static boolean isNullOrEmpty(String value) { // return null == value || "".equals(value); // } // // public Object parse(String value, String type) { // Object result = null; // // if (type.equals("java.lang.String")) { // return value; // } else if (type.equals("java.lang.Byte") || type.equals("byte")) { // if (isNullOrEmpty(value)) { // return "byte".equals(type) ? (byte) 0 : null; // } // // result = new Byte(value); // } else if (type.equals("java.lang.Short") || type.equals("short")) { // if (isNullOrEmpty(value)) { // return "short".equals(type) ? (short) 0 : null; // } // // result = new Short(value); // } else if (type.equals("java.lang.Integer") || type.equals("int")) { // if (isNullOrEmpty(value)) { // return "int".equals(type) ? (int) 0 : null; // } // // result = new Integer(value); // } else if (type.equals("java.lang.Long") || type.equals("long")) { // if (isNullOrEmpty(value)) { // return "long".equals(type) ? (long) 0 : null; // } // // result = new Long(value); // } else if (type.equals("java.lang.Double") || type.equals("double")) { // if (isNullOrEmpty(value)) { // return "double".equals(type) ? (double) 0 : null; // } // // result = new Double(value); // } else if (type.equals("java.lang.Float") || type.equals("float")) { // if (isNullOrEmpty(value)) { // return "float".equals(type) ? (float) 0 : null; // } // // result = new Float(value); // } else if (type.equals("java.lang.Boolean") || type.equals("boolean")) { // if (isNullOrEmpty(value)) { // return "boolean".equals(type) ? false : null; // } // // result = new Boolean(value); // } else if (type.equals("[Ljava.lang.String;")) { // result = StringUtils.splitPreserveAllTokens(value, stringArraySeparator); // } // // if (result == null) { // throw new RuntimeException("Type " + type + " is not supported"); // } // // return result; // } // } // Path: src/test/java/org/jminix/resource/ValueParserTest.java import static org.junit.Assert.assertEquals; import org.jminix.console.resource.ValueParser; import org.junit.Before; import org.junit.Test; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.runner.RunWith; package org.jminix.resource; @RunWith(JUnit4ClassRunner.class) public class ValueParserTest {
ValueParser sut;
lbovet/jminix
src/main/java/org/jminix/console/resource/OperationResource.java
// Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // }
import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.MBeanException; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.ReflectionException; import net.sf.json.JSONSerializer; import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.Post; import org.restlet.resource.ResourceException;
String mbean = unescape(getDecodedAttribute("mbean")); String declaration = getDecodedAttribute("operation"); String operation = declaration.split("\\(")[0]; String[] signature = declaration.split("\\(").length > 1 ? ( declaration.split("\\(")[1].split("\\)").length >0 ? declaration.split("\\(")[1].split("\\)")[0].split(",") : new String[]{} ) : new String[]{}; MBeanServerConnection server = getServer(); try { Object[] params=new Object[signature.length]; ValueParser parser = new ValueParser(); for(int i=0; i<stringParams.length; i++) { params[i] = parser.parse(stringParams[i], signature[i]); } Object result = server.invoke(new ObjectName(domain+":"+mbean), operation, params, signature); if(result != null) { Variant variant = getPreferredVariant(getVariants()); if (MediaType.APPLICATION_JSON == variant.getMediaType()) { return new StringRepresentation( JSONSerializer.toJSON(result).toString(), MediaType.APPLICATION_JSON, Language.ALL, CharacterSet.UTF_8); } else {
// Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // } // Path: src/main/java/org/jminix/console/resource/OperationResource.java import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.MBeanException; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.ReflectionException; import net.sf.json.JSONSerializer; import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.representation.InputRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.Post; import org.restlet.resource.ResourceException; String mbean = unescape(getDecodedAttribute("mbean")); String declaration = getDecodedAttribute("operation"); String operation = declaration.split("\\(")[0]; String[] signature = declaration.split("\\(").length > 1 ? ( declaration.split("\\(")[1].split("\\)").length >0 ? declaration.split("\\(")[1].split("\\)")[0].split(",") : new String[]{} ) : new String[]{}; MBeanServerConnection server = getServer(); try { Object[] params=new Object[signature.length]; ValueParser parser = new ValueParser(); for(int i=0; i<stringParams.length; i++) { params[i] = parser.parse(stringParams[i], signature[i]); } Object result = server.invoke(new ObjectName(domain+":"+mbean), operation, params, signature); if(result != null) { Variant variant = getPreferredVariant(getVariants()); if (MediaType.APPLICATION_JSON == variant.getMediaType()) { return new StringRepresentation( JSONSerializer.toJSON(result).toString(), MediaType.APPLICATION_JSON, Language.ALL, CharacterSet.UTF_8); } else {
if (result instanceof InputStreamContent) {
lbovet/jminix
src/test/java/org/jminix/console/Main.java
// Path: src/main/java/org/jminix/console/tool/StandaloneMiniConsole.java // public class StandaloneMiniConsole // { // private Component component=null; // // /** // * @param port the listening HTTP port // */ // public StandaloneMiniConsole(int port) { // this(port, new MiniConsoleApplication()); // } // // /** // * @param port the listening HTTP port // * @param the application object, if you want to create it by yourself. // */ // public StandaloneMiniConsole(int port, MiniConsoleApplication application) { // // Create a new Component. // component = new Component(); // component.getClients().add(Protocol.CLAP); // // Add a new HTTP server // component.getServers().add(Protocol.HTTP, port); // // // Attach the sample application. // component.getDefaultHost().attach(application); // // // Start the component. // try // { // component.start(); // } // catch (Exception e) // { // throw new RuntimeException(e); // } // } // // /** // * Stops the Mini Console and frees the resources. // */ // public void shutdown() { // try { // component.stop(); // } catch(Exception e) { // throw new RuntimeException(e); // } // } // // /** // * Runs as main, mostly for test purposes... // * // * @param args if present, first args is the port. Defaults to 8181. // */ // public static void main(String[] args) // { // int port=8181; // if(args.length>0) { // port=new Integer(args[0]); // } // new StandaloneMiniConsole(port); // } // // public MiniConsoleApplication getApplication() { // return (MiniConsoleApplication)component.getApplication(); // } // }
import java.lang.management.ManagementFactory; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import org.jminix.console.tool.StandaloneMiniConsole;
/* * Copyright 2009 Laurent Bovet, Swiss Post IT <lbovet@jminix.org> * * 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 org.jminix.console; public class Main { public final static void main(String[] args) throws MalformedObjectNameException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("org.jminix.console:type=JMiniXStuff"); mbs.registerMBean(new JMiniXStuff(), name);
// Path: src/main/java/org/jminix/console/tool/StandaloneMiniConsole.java // public class StandaloneMiniConsole // { // private Component component=null; // // /** // * @param port the listening HTTP port // */ // public StandaloneMiniConsole(int port) { // this(port, new MiniConsoleApplication()); // } // // /** // * @param port the listening HTTP port // * @param the application object, if you want to create it by yourself. // */ // public StandaloneMiniConsole(int port, MiniConsoleApplication application) { // // Create a new Component. // component = new Component(); // component.getClients().add(Protocol.CLAP); // // Add a new HTTP server // component.getServers().add(Protocol.HTTP, port); // // // Attach the sample application. // component.getDefaultHost().attach(application); // // // Start the component. // try // { // component.start(); // } // catch (Exception e) // { // throw new RuntimeException(e); // } // } // // /** // * Stops the Mini Console and frees the resources. // */ // public void shutdown() { // try { // component.stop(); // } catch(Exception e) { // throw new RuntimeException(e); // } // } // // /** // * Runs as main, mostly for test purposes... // * // * @param args if present, first args is the port. Defaults to 8181. // */ // public static void main(String[] args) // { // int port=8181; // if(args.length>0) { // port=new Integer(args[0]); // } // new StandaloneMiniConsole(port); // } // // public MiniConsoleApplication getApplication() { // return (MiniConsoleApplication)component.getApplication(); // } // } // Path: src/test/java/org/jminix/console/Main.java import java.lang.management.ManagementFactory; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import org.jminix.console.tool.StandaloneMiniConsole; /* * Copyright 2009 Laurent Bovet, Swiss Post IT <lbovet@jminix.org> * * 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 org.jminix.console; public class Main { public final static void main(String[] args) throws MalformedObjectNameException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("org.jminix.console:type=JMiniXStuff"); mbs.registerMBean(new JMiniXStuff(), name);
new StandaloneMiniConsole(8088);
lbovet/jminix
src/main/java/org/jminix/server/cluster/RmiClusterManager.java
// Path: src/main/java/org/jminix/server/RmiServerConnectionProvider.java // public class RmiServerConnectionProvider extends AbstractMapServerConnectionProvider { // // private String serviceUrl; // // private String username; // // private String password; // // private Map<String, JMXConnector> jmxcs = new HashMap<String, JMXConnector>(); // // /** // * Not explicitly documented. // * @see org.jminix.server.ServerConnectionProvider#getConnectionKeys() // */ // public List<String> getConnectionKeys() { // String[] parts = serviceUrl.split("/"); // return Arrays.asList(new String[] { parts[parts.length-1] }); // } // // /** // * Not explicitly documented. // * @see org.jminix.server.ServerConnectionProvider#getConnection(java.lang.String) // */ // public MBeanServerConnection getConnection(String name) { // // JMXServiceURL url; // try { // url = new JMXServiceURL(serviceUrl); // // JMXConnector jmxc = jmxcs.get(serviceUrl); // // if(jmxc == null) { // if (username != null && password != null) { // String[] creds = {username, password}; // Map<String, Object> env = new HashMap<String, Object>(); // env.put(JMXConnector.CREDENTIALS, creds); // jmxc = JMXConnectorFactory.connect(url, env); // } else { // jmxc = JMXConnectorFactory.connect(url, null); // } // jmxcs.put(serviceUrl, jmxc); // } else { // jmxc.connect(); // } // return jmxc.getMBeanServerConnection(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Sets the attribute serviceUrl. // * @param serviceUrl The serviceUrl to set. // */ // public void setServiceUrl(String serviceUrl) { // this.serviceUrl = serviceUrl; // } // // /** // * Sets the attribute username. // * @param username The username to set. // */ // public void setUsername(String username) { // this.username = username; // } // // /** // * Sets the attribute password. // * @param password The password to set. // */ // public void setPassword(String password) { // this.password = password; // } // // } // // Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // }
import org.jminix.server.CredentialsHolder; import org.jminix.server.RmiServerConnectionProvider; import org.jminix.server.ServerConnectionProvider;
/* * ------------------------------------------------------------------------------------------------ * Copyright 2011 by Swiss Post, Information Technology Services * ------------------------------------------------------------------------------------------------ * $Id$ * ------------------------------------------------------------------------------------------------ * */ package org.jminix.server.cluster; /** * A cluster manager managing {{@link RmiServerConnectionProvider} instances. Default registry port is 1099. * * @author bovetl * @version $Revision$ * @see <script>links('$HeadURL$');</script> */ public class RmiClusterManager extends ClusterManager { private CredentialsHolder credentials; public RmiClusterManager() { setUrlPattern("service:jmx:rmi://{0}/jndi/rmi://{0}:{1,number,#}/rmi"); setPort(1099); } /** * Not explicitly documented. * @see org.jminix.server.cluster.ClusterManager#createNodeProvider(org.jminix.server.cluster.ClusterManager.Node) */ @Override
// Path: src/main/java/org/jminix/server/RmiServerConnectionProvider.java // public class RmiServerConnectionProvider extends AbstractMapServerConnectionProvider { // // private String serviceUrl; // // private String username; // // private String password; // // private Map<String, JMXConnector> jmxcs = new HashMap<String, JMXConnector>(); // // /** // * Not explicitly documented. // * @see org.jminix.server.ServerConnectionProvider#getConnectionKeys() // */ // public List<String> getConnectionKeys() { // String[] parts = serviceUrl.split("/"); // return Arrays.asList(new String[] { parts[parts.length-1] }); // } // // /** // * Not explicitly documented. // * @see org.jminix.server.ServerConnectionProvider#getConnection(java.lang.String) // */ // public MBeanServerConnection getConnection(String name) { // // JMXServiceURL url; // try { // url = new JMXServiceURL(serviceUrl); // // JMXConnector jmxc = jmxcs.get(serviceUrl); // // if(jmxc == null) { // if (username != null && password != null) { // String[] creds = {username, password}; // Map<String, Object> env = new HashMap<String, Object>(); // env.put(JMXConnector.CREDENTIALS, creds); // jmxc = JMXConnectorFactory.connect(url, env); // } else { // jmxc = JMXConnectorFactory.connect(url, null); // } // jmxcs.put(serviceUrl, jmxc); // } else { // jmxc.connect(); // } // return jmxc.getMBeanServerConnection(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Sets the attribute serviceUrl. // * @param serviceUrl The serviceUrl to set. // */ // public void setServiceUrl(String serviceUrl) { // this.serviceUrl = serviceUrl; // } // // /** // * Sets the attribute username. // * @param username The username to set. // */ // public void setUsername(String username) { // this.username = username; // } // // /** // * Sets the attribute password. // * @param password The password to set. // */ // public void setPassword(String password) { // this.password = password; // } // // } // // Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // Path: src/main/java/org/jminix/server/cluster/RmiClusterManager.java import org.jminix.server.CredentialsHolder; import org.jminix.server.RmiServerConnectionProvider; import org.jminix.server.ServerConnectionProvider; /* * ------------------------------------------------------------------------------------------------ * Copyright 2011 by Swiss Post, Information Technology Services * ------------------------------------------------------------------------------------------------ * $Id$ * ------------------------------------------------------------------------------------------------ * */ package org.jminix.server.cluster; /** * A cluster manager managing {{@link RmiServerConnectionProvider} instances. Default registry port is 1099. * * @author bovetl * @version $Revision$ * @see <script>links('$HeadURL$');</script> */ public class RmiClusterManager extends ClusterManager { private CredentialsHolder credentials; public RmiClusterManager() { setUrlPattern("service:jmx:rmi://{0}/jndi/rmi://{0}:{1,number,#}/rmi"); setPort(1099); } /** * Not explicitly documented. * @see org.jminix.server.cluster.ClusterManager#createNodeProvider(org.jminix.server.cluster.ClusterManager.Node) */ @Override
protected ServerConnectionProvider createNodeProvider(Node node) {
lbovet/jminix
src/main/java/org/jminix/server/cluster/RmiClusterManager.java
// Path: src/main/java/org/jminix/server/RmiServerConnectionProvider.java // public class RmiServerConnectionProvider extends AbstractMapServerConnectionProvider { // // private String serviceUrl; // // private String username; // // private String password; // // private Map<String, JMXConnector> jmxcs = new HashMap<String, JMXConnector>(); // // /** // * Not explicitly documented. // * @see org.jminix.server.ServerConnectionProvider#getConnectionKeys() // */ // public List<String> getConnectionKeys() { // String[] parts = serviceUrl.split("/"); // return Arrays.asList(new String[] { parts[parts.length-1] }); // } // // /** // * Not explicitly documented. // * @see org.jminix.server.ServerConnectionProvider#getConnection(java.lang.String) // */ // public MBeanServerConnection getConnection(String name) { // // JMXServiceURL url; // try { // url = new JMXServiceURL(serviceUrl); // // JMXConnector jmxc = jmxcs.get(serviceUrl); // // if(jmxc == null) { // if (username != null && password != null) { // String[] creds = {username, password}; // Map<String, Object> env = new HashMap<String, Object>(); // env.put(JMXConnector.CREDENTIALS, creds); // jmxc = JMXConnectorFactory.connect(url, env); // } else { // jmxc = JMXConnectorFactory.connect(url, null); // } // jmxcs.put(serviceUrl, jmxc); // } else { // jmxc.connect(); // } // return jmxc.getMBeanServerConnection(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Sets the attribute serviceUrl. // * @param serviceUrl The serviceUrl to set. // */ // public void setServiceUrl(String serviceUrl) { // this.serviceUrl = serviceUrl; // } // // /** // * Sets the attribute username. // * @param username The username to set. // */ // public void setUsername(String username) { // this.username = username; // } // // /** // * Sets the attribute password. // * @param password The password to set. // */ // public void setPassword(String password) { // this.password = password; // } // // } // // Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // }
import org.jminix.server.CredentialsHolder; import org.jminix.server.RmiServerConnectionProvider; import org.jminix.server.ServerConnectionProvider;
/* * ------------------------------------------------------------------------------------------------ * Copyright 2011 by Swiss Post, Information Technology Services * ------------------------------------------------------------------------------------------------ * $Id$ * ------------------------------------------------------------------------------------------------ * */ package org.jminix.server.cluster; /** * A cluster manager managing {{@link RmiServerConnectionProvider} instances. Default registry port is 1099. * * @author bovetl * @version $Revision$ * @see <script>links('$HeadURL$');</script> */ public class RmiClusterManager extends ClusterManager { private CredentialsHolder credentials; public RmiClusterManager() { setUrlPattern("service:jmx:rmi://{0}/jndi/rmi://{0}:{1,number,#}/rmi"); setPort(1099); } /** * Not explicitly documented. * @see org.jminix.server.cluster.ClusterManager#createNodeProvider(org.jminix.server.cluster.ClusterManager.Node) */ @Override protected ServerConnectionProvider createNodeProvider(Node node) {
// Path: src/main/java/org/jminix/server/RmiServerConnectionProvider.java // public class RmiServerConnectionProvider extends AbstractMapServerConnectionProvider { // // private String serviceUrl; // // private String username; // // private String password; // // private Map<String, JMXConnector> jmxcs = new HashMap<String, JMXConnector>(); // // /** // * Not explicitly documented. // * @see org.jminix.server.ServerConnectionProvider#getConnectionKeys() // */ // public List<String> getConnectionKeys() { // String[] parts = serviceUrl.split("/"); // return Arrays.asList(new String[] { parts[parts.length-1] }); // } // // /** // * Not explicitly documented. // * @see org.jminix.server.ServerConnectionProvider#getConnection(java.lang.String) // */ // public MBeanServerConnection getConnection(String name) { // // JMXServiceURL url; // try { // url = new JMXServiceURL(serviceUrl); // // JMXConnector jmxc = jmxcs.get(serviceUrl); // // if(jmxc == null) { // if (username != null && password != null) { // String[] creds = {username, password}; // Map<String, Object> env = new HashMap<String, Object>(); // env.put(JMXConnector.CREDENTIALS, creds); // jmxc = JMXConnectorFactory.connect(url, env); // } else { // jmxc = JMXConnectorFactory.connect(url, null); // } // jmxcs.put(serviceUrl, jmxc); // } else { // jmxc.connect(); // } // return jmxc.getMBeanServerConnection(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Sets the attribute serviceUrl. // * @param serviceUrl The serviceUrl to set. // */ // public void setServiceUrl(String serviceUrl) { // this.serviceUrl = serviceUrl; // } // // /** // * Sets the attribute username. // * @param username The username to set. // */ // public void setUsername(String username) { // this.username = username; // } // // /** // * Sets the attribute password. // * @param password The password to set. // */ // public void setPassword(String password) { // this.password = password; // } // // } // // Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // Path: src/main/java/org/jminix/server/cluster/RmiClusterManager.java import org.jminix.server.CredentialsHolder; import org.jminix.server.RmiServerConnectionProvider; import org.jminix.server.ServerConnectionProvider; /* * ------------------------------------------------------------------------------------------------ * Copyright 2011 by Swiss Post, Information Technology Services * ------------------------------------------------------------------------------------------------ * $Id$ * ------------------------------------------------------------------------------------------------ * */ package org.jminix.server.cluster; /** * A cluster manager managing {{@link RmiServerConnectionProvider} instances. Default registry port is 1099. * * @author bovetl * @version $Revision$ * @see <script>links('$HeadURL$');</script> */ public class RmiClusterManager extends ClusterManager { private CredentialsHolder credentials; public RmiClusterManager() { setUrlPattern("service:jmx:rmi://{0}/jndi/rmi://{0}:{1,number,#}/rmi"); setPort(1099); } /** * Not explicitly documented. * @see org.jminix.server.cluster.ClusterManager#createNodeProvider(org.jminix.server.cluster.ClusterManager.Node) */ @Override protected ServerConnectionProvider createNodeProvider(Node node) {
RmiServerConnectionProvider nodeProvider = new RmiServerConnectionProvider();
lbovet/jminix
src/main/java/org/jminix/console/resource/AttributeResource.java
// Path: src/main/java/org/jminix/type/AttributeFilter.java // public interface AttributeFilter { // // /** // * @param object the attribute to transform. // * @return the transformed object. // */ // Object filter(Object object); // }
import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jminix.type.AttributeFilter; import org.restlet.data.Form; import org.restlet.representation.Representation; import org.restlet.resource.Post; import org.restlet.resource.ResourceException; import javax.management.*; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; import java.io.IOException; import java.util.HashMap;
/* * Copyright 2009 Laurent Bovet, Swiss Post IT <lbovet@jminix.org> * * 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 org.jminix.console.resource; public class AttributeResource extends AbstractTemplateResource { private static Log log = LogFactory.getLog(AttributeResource.class);
// Path: src/main/java/org/jminix/type/AttributeFilter.java // public interface AttributeFilter { // // /** // * @param object the attribute to transform. // * @return the transformed object. // */ // Object filter(Object object); // } // Path: src/main/java/org/jminix/console/resource/AttributeResource.java import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jminix.type.AttributeFilter; import org.restlet.data.Form; import org.restlet.representation.Representation; import org.restlet.resource.Post; import org.restlet.resource.ResourceException; import javax.management.*; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; import java.io.IOException; import java.util.HashMap; /* * Copyright 2009 Laurent Bovet, Swiss Post IT <lbovet@jminix.org> * * 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 org.jminix.console.resource; public class AttributeResource extends AbstractTemplateResource { private static Log log = LogFactory.getLog(AttributeResource.class);
private AttributeFilter attributeFilter;
lbovet/jminix
src/test/java/org/jminix/console/JMiniXStuffMBean.java
// Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // }
import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent;
package org.jminix.console; /** * Our Test MBean. */ public interface JMiniXStuffMBean { /** * Attribute that returns a simple String. */ public String getSimpleString(); /** * Operation that Returns a simple String. */ public abstract String invokeStringOperation(); /** * Attribute that returns a HTML String. */ public abstract HtmlContent getHtmlString(); /** * Operation that returns a HTML String. */ public abstract HtmlContent invokeHtmlStringOperation(); /** * Attribute that returns an {@link InputStreamContent}. */
// Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // } // Path: src/test/java/org/jminix/console/JMiniXStuffMBean.java import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent; package org.jminix.console; /** * Our Test MBean. */ public interface JMiniXStuffMBean { /** * Attribute that returns a simple String. */ public String getSimpleString(); /** * Operation that Returns a simple String. */ public abstract String invokeStringOperation(); /** * Attribute that returns a HTML String. */ public abstract HtmlContent getHtmlString(); /** * Operation that returns a HTML String. */ public abstract HtmlContent invokeHtmlStringOperation(); /** * Attribute that returns an {@link InputStreamContent}. */
public abstract InputStreamContent getInputStream();
lbovet/jminix
src/test/java/org/jminix/console/JMiniXStuff.java
// Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // }
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent;
private static final long serialVersionUID = -1997969459356542938L; public String toString() { return "JMiniX can be found <a href=\"https://code.google.com/p/jminix/\">here</a>"; } }; } /** * {@inheritDoc} */ @Override public HtmlContent invokeHtmlStringOperation() { return new HtmlContent() { private static final long serialVersionUID = -1997969459356542938L; public String toString() { StringBuilder sb = new StringBuilder(); sb.append("My bookmarks (from 'invokeHtmlStringOperation')<hr>"); sb.append("<a href=\"https://code.google.com/p/jminix/\">JMiniX Homepage</a><br>"); sb.append("<a href=\"https://github.com/lbovet/jminix/\">JMiniX on GitHub</a>"); return sb.toString(); } }; } /** * {@inheritDoc} */ @Override
// Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // } // Path: src/test/java/org/jminix/console/JMiniXStuff.java import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent; private static final long serialVersionUID = -1997969459356542938L; public String toString() { return "JMiniX can be found <a href=\"https://code.google.com/p/jminix/\">here</a>"; } }; } /** * {@inheritDoc} */ @Override public HtmlContent invokeHtmlStringOperation() { return new HtmlContent() { private static final long serialVersionUID = -1997969459356542938L; public String toString() { StringBuilder sb = new StringBuilder(); sb.append("My bookmarks (from 'invokeHtmlStringOperation')<hr>"); sb.append("<a href=\"https://code.google.com/p/jminix/\">JMiniX Homepage</a><br>"); sb.append("<a href=\"https://github.com/lbovet/jminix/\">JMiniX on GitHub</a>"); return sb.toString(); } }; } /** * {@inheritDoc} */ @Override
public InputStreamContent getInputStream() {
lbovet/jminix
src/main/java/org/jminix/console/resource/AbstractTemplateResource.java
// Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // // Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // }
import net.sf.json.JSONSerializer; import org.apache.velocity.Template; import org.apache.velocity.app.VelocityEngine; import org.jminix.server.ServerConnectionProvider; import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent; import org.restlet.data.CacheDirective; import org.restlet.data.CharacterSet; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.ext.velocity.TemplateRepresentation; import org.restlet.representation.*; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import javax.management.MBeanAttributeInfo; import javax.management.MBeanServerConnection; import javax.management.openmbean.CompositeData; import java.util.*;
} protected abstract String getTemplateName(); @Get("html|txt|json") public abstract Map<String, Object> getModel(); @Override public Representation toRepresentation(Object source, Variant variant) { if (source instanceof Representation) { return (Representation) source; } if (source == null) { return new EmptyRepresentation(); } Map<String, Object> model = (Map<String, Object>) source; getResponseCacheDirectives().add(CacheDirective.noCache()); getResponseCacheDirectives().add(CacheDirective.mustRevalidate()); getResponseCacheDirectives().add(CacheDirective.noStore()); Representation representation; if (MediaType.TEXT_HTML.equals(variant.getMediaType())) { Map<String, Object> enrichedModel = new HashMap<String, Object>(model); String templateName = getTemplateName(); Object resultObject = enrichedModel.get("value");
// Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // // Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // } // Path: src/main/java/org/jminix/console/resource/AbstractTemplateResource.java import net.sf.json.JSONSerializer; import org.apache.velocity.Template; import org.apache.velocity.app.VelocityEngine; import org.jminix.server.ServerConnectionProvider; import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent; import org.restlet.data.CacheDirective; import org.restlet.data.CharacterSet; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.ext.velocity.TemplateRepresentation; import org.restlet.representation.*; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import javax.management.MBeanAttributeInfo; import javax.management.MBeanServerConnection; import javax.management.openmbean.CompositeData; import java.util.*; } protected abstract String getTemplateName(); @Get("html|txt|json") public abstract Map<String, Object> getModel(); @Override public Representation toRepresentation(Object source, Variant variant) { if (source instanceof Representation) { return (Representation) source; } if (source == null) { return new EmptyRepresentation(); } Map<String, Object> model = (Map<String, Object>) source; getResponseCacheDirectives().add(CacheDirective.noCache()); getResponseCacheDirectives().add(CacheDirective.mustRevalidate()); getResponseCacheDirectives().add(CacheDirective.noStore()); Representation representation; if (MediaType.TEXT_HTML.equals(variant.getMediaType())) { Map<String, Object> enrichedModel = new HashMap<String, Object>(model); String templateName = getTemplateName(); Object resultObject = enrichedModel.get("value");
if (resultObject instanceof InputStreamContent) {
lbovet/jminix
src/main/java/org/jminix/console/resource/AbstractTemplateResource.java
// Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // // Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // }
import net.sf.json.JSONSerializer; import org.apache.velocity.Template; import org.apache.velocity.app.VelocityEngine; import org.jminix.server.ServerConnectionProvider; import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent; import org.restlet.data.CacheDirective; import org.restlet.data.CharacterSet; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.ext.velocity.TemplateRepresentation; import org.restlet.representation.*; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import javax.management.MBeanAttributeInfo; import javax.management.MBeanServerConnection; import javax.management.openmbean.CompositeData; import java.util.*;
value = items.toString(); } result.put("value", value); } else if (model.containsKey("attributes") && model.get("attributes") instanceof CompositeData) { CompositeData items = (CompositeData) model.get("attributes"); result.put("value", items.values()); } } // Hack because root must be a list for dojo tree... if ("servers".equals(getRequest().getOriginalRef().getLastSegment(true))) { representation = new StringRepresentation(JSONSerializer.toJSON(new Object[]{result}) .toString(), MediaType.APPLICATION_JSON, Language.ALL, CharacterSet.UTF_8); } else { representation = new StringRepresentation(JSONSerializer.toJSON(result).toString(), MediaType.APPLICATION_JSON, Language.ALL, CharacterSet.UTF_8 ); } } else { return null; } representation.setExpirationDate(new Date(0l)); return representation; }
// Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // // Path: src/main/java/org/jminix/type/InputStreamContent.java // public abstract class InputStreamContent extends InputStream { // // } // Path: src/main/java/org/jminix/console/resource/AbstractTemplateResource.java import net.sf.json.JSONSerializer; import org.apache.velocity.Template; import org.apache.velocity.app.VelocityEngine; import org.jminix.server.ServerConnectionProvider; import org.jminix.type.HtmlContent; import org.jminix.type.InputStreamContent; import org.restlet.data.CacheDirective; import org.restlet.data.CharacterSet; import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.ext.velocity.TemplateRepresentation; import org.restlet.representation.*; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import javax.management.MBeanAttributeInfo; import javax.management.MBeanServerConnection; import javax.management.openmbean.CompositeData; import java.util.*; value = items.toString(); } result.put("value", value); } else if (model.containsKey("attributes") && model.get("attributes") instanceof CompositeData) { CompositeData items = (CompositeData) model.get("attributes"); result.put("value", items.values()); } } // Hack because root must be a list for dojo tree... if ("servers".equals(getRequest().getOriginalRef().getLastSegment(true))) { representation = new StringRepresentation(JSONSerializer.toJSON(new Object[]{result}) .toString(), MediaType.APPLICATION_JSON, Language.ALL, CharacterSet.UTF_8); } else { representation = new StringRepresentation(JSONSerializer.toJSON(result).toString(), MediaType.APPLICATION_JSON, Language.ALL, CharacterSet.UTF_8 ); } } else { return null; } representation.setExpirationDate(new Date(0l)); return representation; }
protected ServerConnectionProvider getServerProvider()
lbovet/jminix
src/main/java/org/jminix/console/application/MiniConsoleApplication.java
// Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // // Path: src/main/java/org/jminix/type/AttributeFilter.java // public interface AttributeFilter { // // /** // * @param object the attribute to transform. // * @return the transformed object. // */ // Object filter(Object object); // }
import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.jminix.console.resource.*; import org.jminix.server.DefaultLocalServerConnectionProvider; import org.jminix.server.ServerConnectionProvider; import org.jminix.type.AttributeFilter; import org.restlet.*; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.representation.OutputRepresentation; import org.restlet.resource.Directory; import org.restlet.routing.Router; import org.restlet.routing.Template; import java.io.IOException;
/* * Copyright 2009 Laurent Bovet, Swiss Post IT <lbovet@jminix.org> * * 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 org.jminix.console.application; public class MiniConsoleApplication extends Application { { configureLog(null); }
// Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // // Path: src/main/java/org/jminix/type/AttributeFilter.java // public interface AttributeFilter { // // /** // * @param object the attribute to transform. // * @return the transformed object. // */ // Object filter(Object object); // } // Path: src/main/java/org/jminix/console/application/MiniConsoleApplication.java import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.jminix.console.resource.*; import org.jminix.server.DefaultLocalServerConnectionProvider; import org.jminix.server.ServerConnectionProvider; import org.jminix.type.AttributeFilter; import org.restlet.*; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.representation.OutputRepresentation; import org.restlet.resource.Directory; import org.restlet.routing.Router; import org.restlet.routing.Template; import java.io.IOException; /* * Copyright 2009 Laurent Bovet, Swiss Post IT <lbovet@jminix.org> * * 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 org.jminix.console.application; public class MiniConsoleApplication extends Application { { configureLog(null); }
private ServerConnectionProvider serverConnectionProvider;
lbovet/jminix
src/main/java/org/jminix/console/application/MiniConsoleApplication.java
// Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // // Path: src/main/java/org/jminix/type/AttributeFilter.java // public interface AttributeFilter { // // /** // * @param object the attribute to transform. // * @return the transformed object. // */ // Object filter(Object object); // }
import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.jminix.console.resource.*; import org.jminix.server.DefaultLocalServerConnectionProvider; import org.jminix.server.ServerConnectionProvider; import org.jminix.type.AttributeFilter; import org.restlet.*; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.representation.OutputRepresentation; import org.restlet.resource.Directory; import org.restlet.routing.Router; import org.restlet.routing.Template; import java.io.IOException;
/* * Copyright 2009 Laurent Bovet, Swiss Post IT <lbovet@jminix.org> * * 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 org.jminix.console.application; public class MiniConsoleApplication extends Application { { configureLog(null); } private ServerConnectionProvider serverConnectionProvider;
// Path: src/main/java/org/jminix/server/ServerConnectionProvider.java // public interface ServerConnectionProvider // { // /** // * List of connections. The clients are not intended to cache them, but query them before each use. // * The ordering is guaranteed to be unchanged over time (e.g. after reboot). // * // * @return the list of connections. // */ // public List<MBeanServerConnection> getConnections(); // // /** // * @return the names of connections. They can be simple numeric identifiers. They are guarantee not to change over // * time (e.g. after reboot), though. // */ // public List<String> getConnectionKeys(); // // /** // * Return a connection by name. // * // * @param name key as returned by {@link #getConnectionKeys()}. // * @return the connection or null if not found. // */ // public MBeanServerConnection getConnection(String name); // } // // Path: src/main/java/org/jminix/type/AttributeFilter.java // public interface AttributeFilter { // // /** // * @param object the attribute to transform. // * @return the transformed object. // */ // Object filter(Object object); // } // Path: src/main/java/org/jminix/console/application/MiniConsoleApplication.java import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.jminix.console.resource.*; import org.jminix.server.DefaultLocalServerConnectionProvider; import org.jminix.server.ServerConnectionProvider; import org.jminix.type.AttributeFilter; import org.restlet.*; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.representation.OutputRepresentation; import org.restlet.resource.Directory; import org.restlet.routing.Router; import org.restlet.routing.Template; import java.io.IOException; /* * Copyright 2009 Laurent Bovet, Swiss Post IT <lbovet@jminix.org> * * 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 org.jminix.console.application; public class MiniConsoleApplication extends Application { { configureLog(null); } private ServerConnectionProvider serverConnectionProvider;
private AttributeFilter attributeFilter;
tricreo/schema-generator
src/main/java/jp/tricreo/schemagenerator/infrastructure/utils/CloseableUtil.java
// Path: src/main/java/jp/tricreo/schemagenerator/exception/IORuntimeException.java // @SuppressWarnings("serial") // public class IORuntimeException extends RuntimeException { // // /** // * インスタンスを生成する。 // * // */ // public IORuntimeException() { // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // */ // public IORuntimeException(String message) { // super(message); // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // * @param cause 原因 // */ // public IORuntimeException(String message, Throwable cause) { // super(message, cause); // } // // /** // * インスタンスを生成する。 // * // * @param cause 原因 // */ // public IORuntimeException(Throwable cause) { // super(cause); // } // // }
import java.io.Closeable; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import jp.tricreo.schemagenerator.exception.IORuntimeException;
/* * Copyright 2010 TRICREO, Inc. (http://tricreo.jp/) * * 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 jp.tricreo.schemagenerator.infrastructure.utils; /** * {@code Closeable}のためのユーティリティ。 * * @author junichi */ public final class CloseableUtil { /** * {@link Closeable}をクローズする。 * * @param closeable {@link Closeable} */ public static void close(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof SQLException) {
// Path: src/main/java/jp/tricreo/schemagenerator/exception/IORuntimeException.java // @SuppressWarnings("serial") // public class IORuntimeException extends RuntimeException { // // /** // * インスタンスを生成する。 // * // */ // public IORuntimeException() { // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // */ // public IORuntimeException(String message) { // super(message); // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // * @param cause 原因 // */ // public IORuntimeException(String message, Throwable cause) { // super(message, cause); // } // // /** // * インスタンスを生成する。 // * // * @param cause 原因 // */ // public IORuntimeException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/jp/tricreo/schemagenerator/infrastructure/utils/CloseableUtil.java import java.io.Closeable; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import jp.tricreo.schemagenerator.exception.IORuntimeException; /* * Copyright 2010 TRICREO, Inc. (http://tricreo.jp/) * * 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 jp.tricreo.schemagenerator.infrastructure.utils; /** * {@code Closeable}のためのユーティリティ。 * * @author junichi */ public final class CloseableUtil { /** * {@link Closeable}をクローズする。 * * @param closeable {@link Closeable} */ public static void close(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof SQLException) {
throw new IORuntimeException(cause);
tricreo/schema-generator
src/main/java/jp/tricreo/schemagenerator/domain/model/DataSource.java
// Path: src/main/java/jp/tricreo/schemagenerator/exception/CloneNotSupportedRuntimeException.java // @SuppressWarnings("serial") // public class CloneNotSupportedRuntimeException extends RuntimeException { // // /** // * インスタンスを生成する。 // * // */ // public CloneNotSupportedRuntimeException() { // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // */ // public CloneNotSupportedRuntimeException(String message) { // super(message); // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(String message, Throwable cause) { // super(message, cause); // } // // /** // * インスタンスを生成する。 // * // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(Throwable cause) { // super(cause); // } // // }
import jp.tricreo.schemagenerator.exception.CloneNotSupportedRuntimeException; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
package jp.tricreo.schemagenerator.domain.model; /** * データソースを表すクラス。 * * <p> * データソースとは、JDBCで接続できるデータベースの接続情報を意味する。 * 可変なエンティティ。 * </p> * * @author junichi */ public class DataSource implements Entity<DataSource, String> { // IDは必ずfinal private final String identity; private String driverClassName; private String url; private String userName; private String password; /** * インスタンスを生成する。 * * @param identity 識別子 */ public DataSource(String identity) { this(identity, null, null, null, null); } /** * インスタンスを生成する。 * * @param identity 識別子 * @param driverClassName ドライバークラス名 * @param url URL * @param userName ユーザ名 * @param password パスワード */ public DataSource(String identity, String driverClassName, String url, String userName, String password) { Validate.notNull(identity); this.identity = identity; this.driverClassName = driverClassName; this.url = url; this.userName = userName; this.password = password; } @Override public final DataSource clone() { try { DataSource clone = (DataSource) super.clone(); return clone; } catch (CloneNotSupportedException e) {
// Path: src/main/java/jp/tricreo/schemagenerator/exception/CloneNotSupportedRuntimeException.java // @SuppressWarnings("serial") // public class CloneNotSupportedRuntimeException extends RuntimeException { // // /** // * インスタンスを生成する。 // * // */ // public CloneNotSupportedRuntimeException() { // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // */ // public CloneNotSupportedRuntimeException(String message) { // super(message); // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(String message, Throwable cause) { // super(message, cause); // } // // /** // * インスタンスを生成する。 // * // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/DataSource.java import jp.tricreo.schemagenerator.exception.CloneNotSupportedRuntimeException; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; package jp.tricreo.schemagenerator.domain.model; /** * データソースを表すクラス。 * * <p> * データソースとは、JDBCで接続できるデータベースの接続情報を意味する。 * 可変なエンティティ。 * </p> * * @author junichi */ public class DataSource implements Entity<DataSource, String> { // IDは必ずfinal private final String identity; private String driverClassName; private String url; private String userName; private String password; /** * インスタンスを生成する。 * * @param identity 識別子 */ public DataSource(String identity) { this(identity, null, null, null, null); } /** * インスタンスを生成する。 * * @param identity 識別子 * @param driverClassName ドライバークラス名 * @param url URL * @param userName ユーザ名 * @param password パスワード */ public DataSource(String identity, String driverClassName, String url, String userName, String password) { Validate.notNull(identity); this.identity = identity; this.driverClassName = driverClassName; this.url = url; this.userName = userName; this.password = password; } @Override public final DataSource clone() { try { DataSource clone = (DataSource) super.clone(); return clone; } catch (CloneNotSupportedException e) {
throw new CloneNotSupportedRuntimeException(e);
tricreo/schema-generator
src/test/java/jp/tricreo/schemagenerator/infrastructure/utils/CloneUtilTest.java
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/Entity.java // public interface Entity<T extends Entity<T, ID>, ID> extends Cloneable { // // /** // * クローンを生成する。 // * // * @return クローン // */ // T clone(); // // /** // * 識別子を取得する。 // * // * @return 識別子 // */ // ID getIdentity(); // // /** // * 指定されたエンティティとこのエンティティが同じ識別子かどうかを判定する。 // * // * <p>{@link Object#equals}のタイプセーフ版</p> // * // * @param other エンティティ // * @return 同じ識別子ならtrue // */ // boolean sameIdentityAs(T other); // // } // // Path: src/main/java/jp/tricreo/schemagenerator/exception/CloneNotSupportedRuntimeException.java // @SuppressWarnings("serial") // public class CloneNotSupportedRuntimeException extends RuntimeException { // // /** // * インスタンスを生成する。 // * // */ // public CloneNotSupportedRuntimeException() { // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // */ // public CloneNotSupportedRuntimeException(String message) { // super(message); // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(String message, Throwable cause) { // super(message, cause); // } // // /** // * インスタンスを生成する。 // * // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(Throwable cause) { // super(cause); // } // // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import jp.tricreo.schemagenerator.domain.model.Entity; import jp.tricreo.schemagenerator.exception.CloneNotSupportedRuntimeException; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.junit.Test;
package jp.tricreo.schemagenerator.infrastructure.utils; /** * {@link CloneUtil}のためのテスト。 * * @version $Id$ * @author daisuke * @author j5ik2o */ public class CloneUtilTest { public static class SampleMainEntity implements
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/Entity.java // public interface Entity<T extends Entity<T, ID>, ID> extends Cloneable { // // /** // * クローンを生成する。 // * // * @return クローン // */ // T clone(); // // /** // * 識別子を取得する。 // * // * @return 識別子 // */ // ID getIdentity(); // // /** // * 指定されたエンティティとこのエンティティが同じ識別子かどうかを判定する。 // * // * <p>{@link Object#equals}のタイプセーフ版</p> // * // * @param other エンティティ // * @return 同じ識別子ならtrue // */ // boolean sameIdentityAs(T other); // // } // // Path: src/main/java/jp/tricreo/schemagenerator/exception/CloneNotSupportedRuntimeException.java // @SuppressWarnings("serial") // public class CloneNotSupportedRuntimeException extends RuntimeException { // // /** // * インスタンスを生成する。 // * // */ // public CloneNotSupportedRuntimeException() { // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // */ // public CloneNotSupportedRuntimeException(String message) { // super(message); // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(String message, Throwable cause) { // super(message, cause); // } // // /** // * インスタンスを生成する。 // * // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(Throwable cause) { // super(cause); // } // // } // Path: src/test/java/jp/tricreo/schemagenerator/infrastructure/utils/CloneUtilTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import jp.tricreo.schemagenerator.domain.model.Entity; import jp.tricreo.schemagenerator.exception.CloneNotSupportedRuntimeException; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.junit.Test; package jp.tricreo.schemagenerator.infrastructure.utils; /** * {@link CloneUtil}のためのテスト。 * * @version $Id$ * @author daisuke * @author j5ik2o */ public class CloneUtilTest { public static class SampleMainEntity implements
Entity<SampleMainEntity, UUID> {
tricreo/schema-generator
src/test/java/jp/tricreo/schemagenerator/infrastructure/utils/CloneUtilTest.java
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/Entity.java // public interface Entity<T extends Entity<T, ID>, ID> extends Cloneable { // // /** // * クローンを生成する。 // * // * @return クローン // */ // T clone(); // // /** // * 識別子を取得する。 // * // * @return 識別子 // */ // ID getIdentity(); // // /** // * 指定されたエンティティとこのエンティティが同じ識別子かどうかを判定する。 // * // * <p>{@link Object#equals}のタイプセーフ版</p> // * // * @param other エンティティ // * @return 同じ識別子ならtrue // */ // boolean sameIdentityAs(T other); // // } // // Path: src/main/java/jp/tricreo/schemagenerator/exception/CloneNotSupportedRuntimeException.java // @SuppressWarnings("serial") // public class CloneNotSupportedRuntimeException extends RuntimeException { // // /** // * インスタンスを生成する。 // * // */ // public CloneNotSupportedRuntimeException() { // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // */ // public CloneNotSupportedRuntimeException(String message) { // super(message); // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(String message, Throwable cause) { // super(message, cause); // } // // /** // * インスタンスを生成する。 // * // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(Throwable cause) { // super(cause); // } // // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import jp.tricreo.schemagenerator.domain.model.Entity; import jp.tricreo.schemagenerator.exception.CloneNotSupportedRuntimeException; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.junit.Test;
package jp.tricreo.schemagenerator.infrastructure.utils; /** * {@link CloneUtil}のためのテスト。 * * @version $Id$ * @author daisuke * @author j5ik2o */ public class CloneUtilTest { public static class SampleMainEntity implements Entity<SampleMainEntity, UUID> { private UUID identity; public SampleMainEntity(UUID id) { identity = id; } @Override public SampleMainEntity clone() { try { return (SampleMainEntity) super.clone(); } catch (CloneNotSupportedException e) {
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/Entity.java // public interface Entity<T extends Entity<T, ID>, ID> extends Cloneable { // // /** // * クローンを生成する。 // * // * @return クローン // */ // T clone(); // // /** // * 識別子を取得する。 // * // * @return 識別子 // */ // ID getIdentity(); // // /** // * 指定されたエンティティとこのエンティティが同じ識別子かどうかを判定する。 // * // * <p>{@link Object#equals}のタイプセーフ版</p> // * // * @param other エンティティ // * @return 同じ識別子ならtrue // */ // boolean sameIdentityAs(T other); // // } // // Path: src/main/java/jp/tricreo/schemagenerator/exception/CloneNotSupportedRuntimeException.java // @SuppressWarnings("serial") // public class CloneNotSupportedRuntimeException extends RuntimeException { // // /** // * インスタンスを生成する。 // * // */ // public CloneNotSupportedRuntimeException() { // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // */ // public CloneNotSupportedRuntimeException(String message) { // super(message); // } // // /** // * インスタンスを生成する。 // * // * @param message メッセージ // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(String message, Throwable cause) { // super(message, cause); // } // // /** // * インスタンスを生成する。 // * // * @param cause 原因 // */ // public CloneNotSupportedRuntimeException(Throwable cause) { // super(cause); // } // // } // Path: src/test/java/jp/tricreo/schemagenerator/infrastructure/utils/CloneUtilTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import jp.tricreo.schemagenerator.domain.model.Entity; import jp.tricreo.schemagenerator.exception.CloneNotSupportedRuntimeException; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.junit.Test; package jp.tricreo.schemagenerator.infrastructure.utils; /** * {@link CloneUtil}のためのテスト。 * * @version $Id$ * @author daisuke * @author j5ik2o */ public class CloneUtilTest { public static class SampleMainEntity implements Entity<SampleMainEntity, UUID> { private UUID identity; public SampleMainEntity(UUID id) { identity = id; } @Override public SampleMainEntity clone() { try { return (SampleMainEntity) super.clone(); } catch (CloneNotSupportedException e) {
throw new CloneNotSupportedRuntimeException(e);
tricreo/schema-generator
src/main/java/jp/tricreo/schemagenerator/domain/model/impl/EchoActionImpl.java
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/Action.java // public interface Action<T extends Action<T>> extends ValueObject<T> { // // /** // * アクションを実行する。 // * // * @param actionContext {@link ActionContext} // */ // void execute(ActionContext actionContext); // // } // // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/ActionContext.java // public final class ActionContext implements ValueObject<ActionContext> { // // private final Connection connection; // // private final Logger logger; // // // /** // * インスタンスを生成する。 // * // * @param logger {@link Logger} // * @param connection {@link Connection} // */ // public ActionContext(Logger logger, Connection connection) { // Validate.notNull(logger); // Validate.notNull(connection); // this.logger = logger; // this.connection = connection; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // ActionContext other = (ActionContext) obj; // return sameValueAs(other); // } // // /** // * {@link Connection}を取得する。 // * // * <p>便宜上、内部の参照をそのまま返す。</p> // * // * @return {@link Connection} // */ // public Connection getConnection() { // return connection; // } // // /** // * {@link Logger}を取得する。 // * // * <p>便宜上、内部の参照をそのまま返す。</p> // * // * @return {@link Logger} // */ // public Logger getLogger() { // return logger; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(connection).append(logger) // .toHashCode(); // } // // @Override // public boolean sameValueAs(ActionContext other) { // return new EqualsBuilder().append(connection, other.connection) // .append(logger, other.logger).isEquals(); // } // // }
import jp.tricreo.schemagenerator.domain.model.Action; import jp.tricreo.schemagenerator.domain.model.ActionContext; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
/* * Copyright 2010 TRICREO, Inc. (http://tricreo.jp/) * * 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 jp.tricreo.schemagenerator.domain.model.impl; /** * メッセージを出力するためのアクションクラス。 * * <p>当該クラスはImmutableであること。</p> * * @author junichi */ public final class EchoActionImpl implements Action<EchoActionImpl> { private final String text; /** * インスタンスを生成する。 * * @param text 出力したい文字列 */ public EchoActionImpl(String text) { Validate.notNull(text); this.text = text; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } EchoActionImpl other = (EchoActionImpl) obj; return sameValueAs(other); } @Override
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/Action.java // public interface Action<T extends Action<T>> extends ValueObject<T> { // // /** // * アクションを実行する。 // * // * @param actionContext {@link ActionContext} // */ // void execute(ActionContext actionContext); // // } // // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/ActionContext.java // public final class ActionContext implements ValueObject<ActionContext> { // // private final Connection connection; // // private final Logger logger; // // // /** // * インスタンスを生成する。 // * // * @param logger {@link Logger} // * @param connection {@link Connection} // */ // public ActionContext(Logger logger, Connection connection) { // Validate.notNull(logger); // Validate.notNull(connection); // this.logger = logger; // this.connection = connection; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // ActionContext other = (ActionContext) obj; // return sameValueAs(other); // } // // /** // * {@link Connection}を取得する。 // * // * <p>便宜上、内部の参照をそのまま返す。</p> // * // * @return {@link Connection} // */ // public Connection getConnection() { // return connection; // } // // /** // * {@link Logger}を取得する。 // * // * <p>便宜上、内部の参照をそのまま返す。</p> // * // * @return {@link Logger} // */ // public Logger getLogger() { // return logger; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(connection).append(logger) // .toHashCode(); // } // // @Override // public boolean sameValueAs(ActionContext other) { // return new EqualsBuilder().append(connection, other.connection) // .append(logger, other.logger).isEquals(); // } // // } // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/impl/EchoActionImpl.java import jp.tricreo.schemagenerator.domain.model.Action; import jp.tricreo.schemagenerator.domain.model.ActionContext; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /* * Copyright 2010 TRICREO, Inc. (http://tricreo.jp/) * * 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 jp.tricreo.schemagenerator.domain.model.impl; /** * メッセージを出力するためのアクションクラス。 * * <p>当該クラスはImmutableであること。</p> * * @author junichi */ public final class EchoActionImpl implements Action<EchoActionImpl> { private final String text; /** * インスタンスを生成する。 * * @param text 出力したい文字列 */ public EchoActionImpl(String text) { Validate.notNull(text); this.text = text; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } EchoActionImpl other = (EchoActionImpl) obj; return sameValueAs(other); } @Override
public void execute(ActionContext actionContext) {
tricreo/schema-generator
src/test/java/jp/tricreo/schemagenerator/domain/model/impl/EchoActionImplTest.java
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/ActionContext.java // public final class ActionContext implements ValueObject<ActionContext> { // // private final Connection connection; // // private final Logger logger; // // // /** // * インスタンスを生成する。 // * // * @param logger {@link Logger} // * @param connection {@link Connection} // */ // public ActionContext(Logger logger, Connection connection) { // Validate.notNull(logger); // Validate.notNull(connection); // this.logger = logger; // this.connection = connection; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // ActionContext other = (ActionContext) obj; // return sameValueAs(other); // } // // /** // * {@link Connection}を取得する。 // * // * <p>便宜上、内部の参照をそのまま返す。</p> // * // * @return {@link Connection} // */ // public Connection getConnection() { // return connection; // } // // /** // * {@link Logger}を取得する。 // * // * <p>便宜上、内部の参照をそのまま返す。</p> // * // * @return {@link Logger} // */ // public Logger getLogger() { // return logger; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(connection).append(logger) // .toHashCode(); // } // // @Override // public boolean sameValueAs(ActionContext other) { // return new EqualsBuilder().append(connection, other.connection) // .append(logger, other.logger).isEquals(); // } // // } // // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/impl/EchoActionImpl.java // public final class EchoActionImpl implements Action<EchoActionImpl> { // // private final String text; // // // /** // * インスタンスを生成する。 // * // * @param text 出力したい文字列 // */ // public EchoActionImpl(String text) { // Validate.notNull(text); // this.text = text; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // EchoActionImpl other = (EchoActionImpl) obj; // return sameValueAs(other); // } // // @Override // public void execute(ActionContext actionContext) { // Validate.notNull(actionContext); // actionContext.getLogger().info(text); // } // // /** // * 出力したい文字列を取得する。 // * // * @return 出力したい文字列 // */ // public String getText() { // return text; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(text).toHashCode(); // } // // @Override // public boolean sameValueAs(EchoActionImpl other) { // return new EqualsBuilder().append(text, other.text).isEquals(); // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.MULTI_LINE_STYLE); // } // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.sql.Connection; import jp.tricreo.schemagenerator.domain.model.ActionContext; import jp.tricreo.schemagenerator.domain.model.impl.EchoActionImpl; import org.junit.Test; import org.slf4j.Logger;
package jp.tricreo.schemagenerator.domain.model.impl; /** * {@link EchoActionImpl}のためのテスト。 * * @version $Id$ * @author junichi */ public class EchoActionImplTest { private String text = "DEPTを作成します"; /** * 値として等価であること */ @Test public void test01_値として等価であること() {
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/ActionContext.java // public final class ActionContext implements ValueObject<ActionContext> { // // private final Connection connection; // // private final Logger logger; // // // /** // * インスタンスを生成する。 // * // * @param logger {@link Logger} // * @param connection {@link Connection} // */ // public ActionContext(Logger logger, Connection connection) { // Validate.notNull(logger); // Validate.notNull(connection); // this.logger = logger; // this.connection = connection; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // ActionContext other = (ActionContext) obj; // return sameValueAs(other); // } // // /** // * {@link Connection}を取得する。 // * // * <p>便宜上、内部の参照をそのまま返す。</p> // * // * @return {@link Connection} // */ // public Connection getConnection() { // return connection; // } // // /** // * {@link Logger}を取得する。 // * // * <p>便宜上、内部の参照をそのまま返す。</p> // * // * @return {@link Logger} // */ // public Logger getLogger() { // return logger; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(connection).append(logger) // .toHashCode(); // } // // @Override // public boolean sameValueAs(ActionContext other) { // return new EqualsBuilder().append(connection, other.connection) // .append(logger, other.logger).isEquals(); // } // // } // // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/impl/EchoActionImpl.java // public final class EchoActionImpl implements Action<EchoActionImpl> { // // private final String text; // // // /** // * インスタンスを生成する。 // * // * @param text 出力したい文字列 // */ // public EchoActionImpl(String text) { // Validate.notNull(text); // this.text = text; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // EchoActionImpl other = (EchoActionImpl) obj; // return sameValueAs(other); // } // // @Override // public void execute(ActionContext actionContext) { // Validate.notNull(actionContext); // actionContext.getLogger().info(text); // } // // /** // * 出力したい文字列を取得する。 // * // * @return 出力したい文字列 // */ // public String getText() { // return text; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(text).toHashCode(); // } // // @Override // public boolean sameValueAs(EchoActionImpl other) { // return new EqualsBuilder().append(text, other.text).isEquals(); // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.MULTI_LINE_STYLE); // } // } // Path: src/test/java/jp/tricreo/schemagenerator/domain/model/impl/EchoActionImplTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.sql.Connection; import jp.tricreo.schemagenerator.domain.model.ActionContext; import jp.tricreo.schemagenerator.domain.model.impl.EchoActionImpl; import org.junit.Test; import org.slf4j.Logger; package jp.tricreo.schemagenerator.domain.model.impl; /** * {@link EchoActionImpl}のためのテスト。 * * @version $Id$ * @author junichi */ public class EchoActionImplTest { private String text = "DEPTを作成します"; /** * 値として等価であること */ @Test public void test01_値として等価であること() {
assertThat(new EchoActionImpl(text),
tricreo/schema-generator
src/test/java/jp/tricreo/schemagenerator/domain/lifecycle/factory/impl/ActionFactoryImplTest.java
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/Action.java // public interface Action<T extends Action<T>> extends ValueObject<T> { // // /** // * アクションを実行する。 // * // * @param actionContext {@link ActionContext} // */ // void execute(ActionContext actionContext); // // } // // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/impl/EchoActionImpl.java // public final class EchoActionImpl implements Action<EchoActionImpl> { // // private final String text; // // // /** // * インスタンスを生成する。 // * // * @param text 出力したい文字列 // */ // public EchoActionImpl(String text) { // Validate.notNull(text); // this.text = text; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // EchoActionImpl other = (EchoActionImpl) obj; // return sameValueAs(other); // } // // @Override // public void execute(ActionContext actionContext) { // Validate.notNull(actionContext); // actionContext.getLogger().info(text); // } // // /** // * 出力したい文字列を取得する。 // * // * @return 出力したい文字列 // */ // public String getText() { // return text; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(text).toHashCode(); // } // // @Override // public boolean sameValueAs(EchoActionImpl other) { // return new EqualsBuilder().append(text, other.text).isEquals(); // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.MULTI_LINE_STYLE); // } // } // // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/impl/SqlActionImpl.java // public final class SqlActionImpl implements Action<SqlActionImpl> { // // private final String sql; // // // /** // * インスタンスを生成する。 // * // * @param sql 実行するSQL // */ // public SqlActionImpl(String sql) { // Validate.notNull(sql); // this.sql = sql; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // SqlActionImpl other = (SqlActionImpl) obj; // return sameValueAs(other); // } // // @Override // public void execute(ActionContext actionContext) { // Validate.notNull(actionContext); // Statement statement = null; // try { // statement = actionContext.getConnection().createStatement(); // if (statement.executeUpdate(sql) > 0) { // actionContext.getLogger().debug("sql = " + sql); // } // } catch (SQLException e) { // throw new SQLRuntimeException(e); // } finally { // CloseableUtil.close(statement); // } // } // // /** // * SQLを取得する。 // * // * @return SQL // */ // public String getSql() { // return sql; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(sql).toHashCode(); // } // // @Override // public boolean sameValueAs(SqlActionImpl other) { // return new EqualsBuilder().append(sql, other.sql).isEquals(); // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.MULTI_LINE_STYLE); // } // // }
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import jp.tricreo.schemagenerator.domain.model.Action; import jp.tricreo.schemagenerator.domain.model.impl.EchoActionImpl; import jp.tricreo.schemagenerator.domain.model.impl.SqlActionImpl; import org.junit.Test;
package jp.tricreo.schemagenerator.domain.lifecycle.factory.impl; /** * {@link ActionFactoryImpl}のためのテスト。 * * @version $Id$ * @author junichi */ public class ActionFactoryImplTest { /** * Actionを生成できること。 */ @Test public void test01_Actionを生成できること() { ActionFactoryImpl actionFactoryImpl = new ActionFactoryImpl();
// Path: src/main/java/jp/tricreo/schemagenerator/domain/model/Action.java // public interface Action<T extends Action<T>> extends ValueObject<T> { // // /** // * アクションを実行する。 // * // * @param actionContext {@link ActionContext} // */ // void execute(ActionContext actionContext); // // } // // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/impl/EchoActionImpl.java // public final class EchoActionImpl implements Action<EchoActionImpl> { // // private final String text; // // // /** // * インスタンスを生成する。 // * // * @param text 出力したい文字列 // */ // public EchoActionImpl(String text) { // Validate.notNull(text); // this.text = text; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // EchoActionImpl other = (EchoActionImpl) obj; // return sameValueAs(other); // } // // @Override // public void execute(ActionContext actionContext) { // Validate.notNull(actionContext); // actionContext.getLogger().info(text); // } // // /** // * 出力したい文字列を取得する。 // * // * @return 出力したい文字列 // */ // public String getText() { // return text; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(text).toHashCode(); // } // // @Override // public boolean sameValueAs(EchoActionImpl other) { // return new EqualsBuilder().append(text, other.text).isEquals(); // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.MULTI_LINE_STYLE); // } // } // // Path: src/main/java/jp/tricreo/schemagenerator/domain/model/impl/SqlActionImpl.java // public final class SqlActionImpl implements Action<SqlActionImpl> { // // private final String sql; // // // /** // * インスタンスを生成する。 // * // * @param sql 実行するSQL // */ // public SqlActionImpl(String sql) { // Validate.notNull(sql); // this.sql = sql; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // SqlActionImpl other = (SqlActionImpl) obj; // return sameValueAs(other); // } // // @Override // public void execute(ActionContext actionContext) { // Validate.notNull(actionContext); // Statement statement = null; // try { // statement = actionContext.getConnection().createStatement(); // if (statement.executeUpdate(sql) > 0) { // actionContext.getLogger().debug("sql = " + sql); // } // } catch (SQLException e) { // throw new SQLRuntimeException(e); // } finally { // CloseableUtil.close(statement); // } // } // // /** // * SQLを取得する。 // * // * @return SQL // */ // public String getSql() { // return sql; // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(sql).toHashCode(); // } // // @Override // public boolean sameValueAs(SqlActionImpl other) { // return new EqualsBuilder().append(sql, other.sql).isEquals(); // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.MULTI_LINE_STYLE); // } // // } // Path: src/test/java/jp/tricreo/schemagenerator/domain/lifecycle/factory/impl/ActionFactoryImplTest.java import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import jp.tricreo.schemagenerator.domain.model.Action; import jp.tricreo.schemagenerator.domain.model.impl.EchoActionImpl; import jp.tricreo.schemagenerator.domain.model.impl.SqlActionImpl; import org.junit.Test; package jp.tricreo.schemagenerator.domain.lifecycle.factory.impl; /** * {@link ActionFactoryImpl}のためのテスト。 * * @version $Id$ * @author junichi */ public class ActionFactoryImplTest { /** * Actionを生成できること。 */ @Test public void test01_Actionを生成できること() { ActionFactoryImpl actionFactoryImpl = new ActionFactoryImpl();
Action<?> newAction =
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/unit/SauceConfigurationTest.java
// Path: common/src/main/java/com/saucelabs/common/SauceConfiguration.java // public class SauceConfiguration { // private String userNameEnvironmentVariableKey; // private String apiKeyEnvironmentVariableName; // public String accessKey; // // public SauceConfiguration() { // userNameEnvironmentVariableKey = "SAUCE_USERNAME"; // apiKeyEnvironmentVariableName = "SAUCE_ACCESS_KEY"; // } // // public String getUserName() throws SauceEnvironmentVariableNotSetException { // String userName = System.getenv(userNameEnvironmentVariableKey); // return checkIfEmpty(userName); // } // public String getAccessKey() throws SauceEnvironmentVariableNotSetException { // String apiKey = System.getenv(apiKeyEnvironmentVariableName); // return checkIfEmpty(apiKey); // } // // private String checkIfEmpty(String userName) throws SauceEnvironmentVariableNotSetException { // if (userName == null) // throw new SauceEnvironmentVariableNotSetException(); // return userName; // } // // public void setAccessKeyEnvironmentVariable(String key) { // apiKeyEnvironmentVariableName = key; // } // // public void setUserNameEnvironmentVariable(String key) { // userNameEnvironmentVariableKey = key; // } // public String getUserNameEnvironmentVariableKey() { // return userNameEnvironmentVariableKey; // } // // public String getEnvironmentVariableApiKeyName() { // return apiKeyEnvironmentVariableName; // } // // } // // Path: common/src/main/java/com/saucelabs/common/SauceEnvironmentVariableNotSetException.java // public class SauceEnvironmentVariableNotSetException extends Throwable { // }
import com.saucelabs.common.SauceConfiguration; import com.saucelabs.common.SauceEnvironmentVariableNotSetException; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
package com.saucelabs.common.unit; public class SauceConfigurationTest { private SauceConfiguration mockSauceEnv; @Before public void runBeforeTests() { mockSauceEnv = new SauceConfiguration(); } @Test public void shouldReturnDefaultUserNameEnvironmentKey() { Assert.assertEquals("SAUCE_USERNAME", mockSauceEnv.getUserNameEnvironmentVariableKey()); } @Test public void shouldReturnDefaultAccessKeyEnvironmentKey() { Assert.assertEquals("SAUCE_ACCESS_KEY", mockSauceEnv.getEnvironmentVariableApiKeyName()); }
// Path: common/src/main/java/com/saucelabs/common/SauceConfiguration.java // public class SauceConfiguration { // private String userNameEnvironmentVariableKey; // private String apiKeyEnvironmentVariableName; // public String accessKey; // // public SauceConfiguration() { // userNameEnvironmentVariableKey = "SAUCE_USERNAME"; // apiKeyEnvironmentVariableName = "SAUCE_ACCESS_KEY"; // } // // public String getUserName() throws SauceEnvironmentVariableNotSetException { // String userName = System.getenv(userNameEnvironmentVariableKey); // return checkIfEmpty(userName); // } // public String getAccessKey() throws SauceEnvironmentVariableNotSetException { // String apiKey = System.getenv(apiKeyEnvironmentVariableName); // return checkIfEmpty(apiKey); // } // // private String checkIfEmpty(String userName) throws SauceEnvironmentVariableNotSetException { // if (userName == null) // throw new SauceEnvironmentVariableNotSetException(); // return userName; // } // // public void setAccessKeyEnvironmentVariable(String key) { // apiKeyEnvironmentVariableName = key; // } // // public void setUserNameEnvironmentVariable(String key) { // userNameEnvironmentVariableKey = key; // } // public String getUserNameEnvironmentVariableKey() { // return userNameEnvironmentVariableKey; // } // // public String getEnvironmentVariableApiKeyName() { // return apiKeyEnvironmentVariableName; // } // // } // // Path: common/src/main/java/com/saucelabs/common/SauceEnvironmentVariableNotSetException.java // public class SauceEnvironmentVariableNotSetException extends Throwable { // } // Path: common/src/test/java/com/saucelabs/common/unit/SauceConfigurationTest.java import com.saucelabs.common.SauceConfiguration; import com.saucelabs.common.SauceEnvironmentVariableNotSetException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; package com.saucelabs.common.unit; public class SauceConfigurationTest { private SauceConfiguration mockSauceEnv; @Before public void runBeforeTests() { mockSauceEnv = new SauceConfiguration(); } @Test public void shouldReturnDefaultUserNameEnvironmentKey() { Assert.assertEquals("SAUCE_USERNAME", mockSauceEnv.getUserNameEnvironmentVariableKey()); } @Test public void shouldReturnDefaultAccessKeyEnvironmentKey() { Assert.assertEquals("SAUCE_ACCESS_KEY", mockSauceEnv.getEnvironmentVariableApiKeyName()); }
@Test(expected = SauceEnvironmentVariableNotSetException.class)
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/acceptance/SauceApiAcceptanceTest.java
// Path: common/src/main/java/com/saucelabs/common/InvalidTestStatusException.java // public class InvalidTestStatusException extends Throwable { // } // // Path: common/src/main/java/com/saucelabs/common/SauceApi.java // public class SauceApi { // // private WebDriver webDriver; // // public SauceApi(WebDriver webDriver) { // this.webDriver = webDriver; // } // // public SauceApi() { // } // // public void setTestStatus(String testResult) { // //TODO finish implementation // //testResult = testResult.toLowerCase(); // //isValidTestStatus(testResult); // new JavaScriptInvoker(webDriver). // executeScript(SauceJavaScriptStrings.testStatusPrefix + testResult); // } // // // private void isValidTestStatus(String testResult) throws InvalidTestStatusException { // // if(!testResult.equals("passed") || !testResult.equals("failed") || // // !testResult.equals("true") || !testResult.equals("false")) // // { // // throw new InvalidTestStatusException(); // // } // // } // // public void setTestName(String testName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.testNamePrefix + testName); // } // // public void setTestTags(String tags) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.tagsPrefix + tags); // } // // public void comment(String comment) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.sauceContextPrefix + comment); // } // // public void setBuildName(String buildName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.buildPrefix + buildName); // } // // public void setBreakpoint() { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.breakStatement); // } // }
import com.saucelabs.common.InvalidTestStatusException; import com.saucelabs.common.SauceApi; import com.saucelabs.saucerest.DataCenter; import com.saucelabs.saucerest.SauceREST; import io.restassured.path.json.JsonPath; import org.junit.*; import org.junit.rules.TestName; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; import java.net.MalformedURLException; import java.net.URL;
package com.saucelabs.common.acceptance; public class SauceApiAcceptanceTest { private String username = System.getenv("SAUCE_USERNAME"); private String accesskey = System.getenv("SAUCE_ACCESS_KEY"); private String SAUCE_REMOTE_URL = "https://ondemand.saucelabs.com/wd/hub"; private WebDriver driver; private SessionId sessionId; @Rule public TestName testName = new TestName(); @Before public void runBeforeEachTest() throws MalformedURLException { MutableCapabilities sauceOptions = getMutableCapabilities(); ChromeOptions chromeOpts = getChromeOptions(sauceOptions); driver = new RemoteWebDriver(new URL(SAUCE_REMOTE_URL), chromeOpts); sessionId = ((RemoteWebDriver) driver).getSessionId(); driver.navigate().to("https://www.saucedemo.com"); } @Test
// Path: common/src/main/java/com/saucelabs/common/InvalidTestStatusException.java // public class InvalidTestStatusException extends Throwable { // } // // Path: common/src/main/java/com/saucelabs/common/SauceApi.java // public class SauceApi { // // private WebDriver webDriver; // // public SauceApi(WebDriver webDriver) { // this.webDriver = webDriver; // } // // public SauceApi() { // } // // public void setTestStatus(String testResult) { // //TODO finish implementation // //testResult = testResult.toLowerCase(); // //isValidTestStatus(testResult); // new JavaScriptInvoker(webDriver). // executeScript(SauceJavaScriptStrings.testStatusPrefix + testResult); // } // // // private void isValidTestStatus(String testResult) throws InvalidTestStatusException { // // if(!testResult.equals("passed") || !testResult.equals("failed") || // // !testResult.equals("true") || !testResult.equals("false")) // // { // // throw new InvalidTestStatusException(); // // } // // } // // public void setTestName(String testName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.testNamePrefix + testName); // } // // public void setTestTags(String tags) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.tagsPrefix + tags); // } // // public void comment(String comment) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.sauceContextPrefix + comment); // } // // public void setBuildName(String buildName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.buildPrefix + buildName); // } // // public void setBreakpoint() { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.breakStatement); // } // } // Path: common/src/test/java/com/saucelabs/common/acceptance/SauceApiAcceptanceTest.java import com.saucelabs.common.InvalidTestStatusException; import com.saucelabs.common.SauceApi; import com.saucelabs.saucerest.DataCenter; import com.saucelabs.saucerest.SauceREST; import io.restassured.path.json.JsonPath; import org.junit.*; import org.junit.rules.TestName; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; import java.net.MalformedURLException; import java.net.URL; package com.saucelabs.common.acceptance; public class SauceApiAcceptanceTest { private String username = System.getenv("SAUCE_USERNAME"); private String accesskey = System.getenv("SAUCE_ACCESS_KEY"); private String SAUCE_REMOTE_URL = "https://ondemand.saucelabs.com/wd/hub"; private WebDriver driver; private SessionId sessionId; @Rule public TestName testName = new TestName(); @Before public void runBeforeEachTest() throws MalformedURLException { MutableCapabilities sauceOptions = getMutableCapabilities(); ChromeOptions chromeOpts = getChromeOptions(sauceOptions); driver = new RemoteWebDriver(new URL(SAUCE_REMOTE_URL), chromeOpts); sessionId = ((RemoteWebDriver) driver).getSessionId(); driver.navigate().to("https://www.saucedemo.com"); } @Test
public void shouldSetTestStatusToPassed() throws InvalidTestStatusException {
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/acceptance/SauceApiAcceptanceTest.java
// Path: common/src/main/java/com/saucelabs/common/InvalidTestStatusException.java // public class InvalidTestStatusException extends Throwable { // } // // Path: common/src/main/java/com/saucelabs/common/SauceApi.java // public class SauceApi { // // private WebDriver webDriver; // // public SauceApi(WebDriver webDriver) { // this.webDriver = webDriver; // } // // public SauceApi() { // } // // public void setTestStatus(String testResult) { // //TODO finish implementation // //testResult = testResult.toLowerCase(); // //isValidTestStatus(testResult); // new JavaScriptInvoker(webDriver). // executeScript(SauceJavaScriptStrings.testStatusPrefix + testResult); // } // // // private void isValidTestStatus(String testResult) throws InvalidTestStatusException { // // if(!testResult.equals("passed") || !testResult.equals("failed") || // // !testResult.equals("true") || !testResult.equals("false")) // // { // // throw new InvalidTestStatusException(); // // } // // } // // public void setTestName(String testName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.testNamePrefix + testName); // } // // public void setTestTags(String tags) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.tagsPrefix + tags); // } // // public void comment(String comment) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.sauceContextPrefix + comment); // } // // public void setBuildName(String buildName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.buildPrefix + buildName); // } // // public void setBreakpoint() { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.breakStatement); // } // }
import com.saucelabs.common.InvalidTestStatusException; import com.saucelabs.common.SauceApi; import com.saucelabs.saucerest.DataCenter; import com.saucelabs.saucerest.SauceREST; import io.restassured.path.json.JsonPath; import org.junit.*; import org.junit.rules.TestName; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; import java.net.MalformedURLException; import java.net.URL;
package com.saucelabs.common.acceptance; public class SauceApiAcceptanceTest { private String username = System.getenv("SAUCE_USERNAME"); private String accesskey = System.getenv("SAUCE_ACCESS_KEY"); private String SAUCE_REMOTE_URL = "https://ondemand.saucelabs.com/wd/hub"; private WebDriver driver; private SessionId sessionId; @Rule public TestName testName = new TestName(); @Before public void runBeforeEachTest() throws MalformedURLException { MutableCapabilities sauceOptions = getMutableCapabilities(); ChromeOptions chromeOpts = getChromeOptions(sauceOptions); driver = new RemoteWebDriver(new URL(SAUCE_REMOTE_URL), chromeOpts); sessionId = ((RemoteWebDriver) driver).getSessionId(); driver.navigate().to("https://www.saucedemo.com"); } @Test public void shouldSetTestStatusToPassed() throws InvalidTestStatusException {
// Path: common/src/main/java/com/saucelabs/common/InvalidTestStatusException.java // public class InvalidTestStatusException extends Throwable { // } // // Path: common/src/main/java/com/saucelabs/common/SauceApi.java // public class SauceApi { // // private WebDriver webDriver; // // public SauceApi(WebDriver webDriver) { // this.webDriver = webDriver; // } // // public SauceApi() { // } // // public void setTestStatus(String testResult) { // //TODO finish implementation // //testResult = testResult.toLowerCase(); // //isValidTestStatus(testResult); // new JavaScriptInvoker(webDriver). // executeScript(SauceJavaScriptStrings.testStatusPrefix + testResult); // } // // // private void isValidTestStatus(String testResult) throws InvalidTestStatusException { // // if(!testResult.equals("passed") || !testResult.equals("failed") || // // !testResult.equals("true") || !testResult.equals("false")) // // { // // throw new InvalidTestStatusException(); // // } // // } // // public void setTestName(String testName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.testNamePrefix + testName); // } // // public void setTestTags(String tags) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.tagsPrefix + tags); // } // // public void comment(String comment) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.sauceContextPrefix + comment); // } // // public void setBuildName(String buildName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.buildPrefix + buildName); // } // // public void setBreakpoint() { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.breakStatement); // } // } // Path: common/src/test/java/com/saucelabs/common/acceptance/SauceApiAcceptanceTest.java import com.saucelabs.common.InvalidTestStatusException; import com.saucelabs.common.SauceApi; import com.saucelabs.saucerest.DataCenter; import com.saucelabs.saucerest.SauceREST; import io.restassured.path.json.JsonPath; import org.junit.*; import org.junit.rules.TestName; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; import java.net.MalformedURLException; import java.net.URL; package com.saucelabs.common.acceptance; public class SauceApiAcceptanceTest { private String username = System.getenv("SAUCE_USERNAME"); private String accesskey = System.getenv("SAUCE_ACCESS_KEY"); private String SAUCE_REMOTE_URL = "https://ondemand.saucelabs.com/wd/hub"; private WebDriver driver; private SessionId sessionId; @Rule public TestName testName = new TestName(); @Before public void runBeforeEachTest() throws MalformedURLException { MutableCapabilities sauceOptions = getMutableCapabilities(); ChromeOptions chromeOpts = getChromeOptions(sauceOptions); driver = new RemoteWebDriver(new URL(SAUCE_REMOTE_URL), chromeOpts); sessionId = ((RemoteWebDriver) driver).getSessionId(); driver.navigate().to("https://www.saucedemo.com"); } @Test public void shouldSetTestStatusToPassed() throws InvalidTestStatusException {
SauceApi sauceApi = new SauceApi(driver);
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerFactoryTest.java
// Path: common/src/main/java/com/saucelabs/common/JavaScriptExecutor.java // public interface JavaScriptExecutor { // Object executeScript(String script); // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // }
import com.saucelabs.common.JavaScriptExecutor; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf;
package com.saucelabs.common.unit; public class JavaScriptInvokerFactoryTest extends BaseUnitTest { @Test public void shouldReturnObjectForTheManager() {
// Path: common/src/main/java/com/saucelabs/common/JavaScriptExecutor.java // public interface JavaScriptExecutor { // Object executeScript(String script); // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // } // Path: common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerFactoryTest.java import com.saucelabs.common.JavaScriptExecutor; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; package com.saucelabs.common.unit; public class JavaScriptInvokerFactoryTest extends BaseUnitTest { @Test public void shouldReturnObjectForTheManager() {
JavaScriptExecutor jsManager = JavaScriptInvokerFactory.create(mockWebDriver);
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerFactoryTest.java
// Path: common/src/main/java/com/saucelabs/common/JavaScriptExecutor.java // public interface JavaScriptExecutor { // Object executeScript(String script); // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // }
import com.saucelabs.common.JavaScriptExecutor; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf;
package com.saucelabs.common.unit; public class JavaScriptInvokerFactoryTest extends BaseUnitTest { @Test public void shouldReturnObjectForTheManager() {
// Path: common/src/main/java/com/saucelabs/common/JavaScriptExecutor.java // public interface JavaScriptExecutor { // Object executeScript(String script); // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // } // Path: common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerFactoryTest.java import com.saucelabs.common.JavaScriptExecutor; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; package com.saucelabs.common.unit; public class JavaScriptInvokerFactoryTest extends BaseUnitTest { @Test public void shouldReturnObjectForTheManager() {
JavaScriptExecutor jsManager = JavaScriptInvokerFactory.create(mockWebDriver);
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerFactoryTest.java
// Path: common/src/main/java/com/saucelabs/common/JavaScriptExecutor.java // public interface JavaScriptExecutor { // Object executeScript(String script); // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // }
import com.saucelabs.common.JavaScriptExecutor; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf;
package com.saucelabs.common.unit; public class JavaScriptInvokerFactoryTest extends BaseUnitTest { @Test public void shouldReturnObjectForTheManager() { JavaScriptExecutor jsManager = JavaScriptInvokerFactory.create(mockWebDriver);
// Path: common/src/main/java/com/saucelabs/common/JavaScriptExecutor.java // public interface JavaScriptExecutor { // Object executeScript(String script); // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // } // Path: common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerFactoryTest.java import com.saucelabs.common.JavaScriptExecutor; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; package com.saucelabs.common.unit; public class JavaScriptInvokerFactoryTest extends BaseUnitTest { @Test public void shouldReturnObjectForTheManager() { JavaScriptExecutor jsManager = JavaScriptInvokerFactory.create(mockWebDriver);
assertThat(jsManager, instanceOf(JavaScriptInvokerImpl.class));
saucelabs/sauce-java
common/src/main/java/com/saucelabs/remotedriver/SauceSession.java
// Path: common/src/main/java/com/saucelabs/common/SauceApi.java // public class SauceApi { // // private WebDriver webDriver; // // public SauceApi(WebDriver webDriver) { // this.webDriver = webDriver; // } // // public SauceApi() { // } // // public void setTestStatus(String testResult) { // //TODO finish implementation // //testResult = testResult.toLowerCase(); // //isValidTestStatus(testResult); // new JavaScriptInvoker(webDriver). // executeScript(SauceJavaScriptStrings.testStatusPrefix + testResult); // } // // // private void isValidTestStatus(String testResult) throws InvalidTestStatusException { // // if(!testResult.equals("passed") || !testResult.equals("failed") || // // !testResult.equals("true") || !testResult.equals("false")) // // { // // throw new InvalidTestStatusException(); // // } // // } // // public void setTestName(String testName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.testNamePrefix + testName); // } // // public void setTestTags(String tags) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.tagsPrefix + tags); // } // // public void comment(String comment) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.sauceContextPrefix + comment); // } // // public void setBuildName(String buildName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.buildPrefix + buildName); // } // // public void setBreakpoint() { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.breakStatement); // } // }
import com.saucelabs.common.SauceApi; import com.saucelabs.saucerest.SauceREST; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.safari.SafariOptions; import java.net.MalformedURLException;
package com.saucelabs.remotedriver; public class SauceSession { static String sauceSeleniumServer = "https://ondemand.saucelabs.com/wd/hub"; static String SAUCE_USERNAME = System.getenv("SAUCE_USERNAME"); static String SAUCE_ACCESS_KEY = System.getenv("SAUCE_ACCESS_KEY"); String BUILD_TAG = System.getenv("BUILD_TAG");
// Path: common/src/main/java/com/saucelabs/common/SauceApi.java // public class SauceApi { // // private WebDriver webDriver; // // public SauceApi(WebDriver webDriver) { // this.webDriver = webDriver; // } // // public SauceApi() { // } // // public void setTestStatus(String testResult) { // //TODO finish implementation // //testResult = testResult.toLowerCase(); // //isValidTestStatus(testResult); // new JavaScriptInvoker(webDriver). // executeScript(SauceJavaScriptStrings.testStatusPrefix + testResult); // } // // // private void isValidTestStatus(String testResult) throws InvalidTestStatusException { // // if(!testResult.equals("passed") || !testResult.equals("failed") || // // !testResult.equals("true") || !testResult.equals("false")) // // { // // throw new InvalidTestStatusException(); // // } // // } // // public void setTestName(String testName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.testNamePrefix + testName); // } // // public void setTestTags(String tags) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.tagsPrefix + tags); // } // // public void comment(String comment) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.sauceContextPrefix + comment); // } // // public void setBuildName(String buildName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.buildPrefix + buildName); // } // // public void setBreakpoint() { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.breakStatement); // } // } // Path: common/src/main/java/com/saucelabs/remotedriver/SauceSession.java import com.saucelabs.common.SauceApi; import com.saucelabs.saucerest.SauceREST; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.safari.SafariOptions; import java.net.MalformedURLException; package com.saucelabs.remotedriver; public class SauceSession { static String sauceSeleniumServer = "https://ondemand.saucelabs.com/wd/hub"; static String SAUCE_USERNAME = System.getenv("SAUCE_USERNAME"); static String SAUCE_ACCESS_KEY = System.getenv("SAUCE_ACCESS_KEY"); String BUILD_TAG = System.getenv("BUILD_TAG");
public SauceApi test;
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/unit/BaseUnitTest.java
// Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // }
import com.saucelabs.common.JavaScriptInvokerFactory; import org.junit.After; import org.junit.Before; import org.openqa.selenium.WebDriver; import static org.mockito.Mockito.mock;
package com.saucelabs.common.unit; public class BaseUnitTest { public WebDriver mockWebDriver; @Before public void runBeforeTest() { mockWebDriver = mock(WebDriver.class); resetJavaScriptInvokerState(); } @After public void afterEveryTest() { resetJavaScriptInvokerState(); } private void resetJavaScriptInvokerState() {
// Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // Path: common/src/test/java/com/saucelabs/common/unit/BaseUnitTest.java import com.saucelabs.common.JavaScriptInvokerFactory; import org.junit.After; import org.junit.Before; import org.openqa.selenium.WebDriver; import static org.mockito.Mockito.mock; package com.saucelabs.common.unit; public class BaseUnitTest { public WebDriver mockWebDriver; @Before public void runBeforeTest() { mockWebDriver = mock(WebDriver.class); resetJavaScriptInvokerState(); } @After public void afterEveryTest() { resetJavaScriptInvokerState(); } private void resetJavaScriptInvokerState() {
JavaScriptInvokerFactory.setJavaScriptExecutor(null);
saucelabs/sauce-java
common/src/test/java/com/saucelabs/remotedriver/config/SauceConfigTest.java
// Path: common/src/main/java/com/saucelabs/remotedriver/config/SauceConfig.java // public class SauceConfig // { // public String username; // public String accessKey; // // public class testConfig // { // public String name; // public String build; // public String tags; // public String customData; // } // // public class OSConfig // { // public String browserName; // } // // public ChromeOptions chromeOptions; // public String browserName; // // public static LinuxConfig withLinux() // { // return new LinuxConfig(); // } // }
import com.saucelabs.remotedriver.config.SauceConfig; import org.junit.Test;
package com.saucelabs.remotedriver.config; public class SauceConfigTest { @Test public void configuration_with_linux_should_allow_chrome_browser() {
// Path: common/src/main/java/com/saucelabs/remotedriver/config/SauceConfig.java // public class SauceConfig // { // public String username; // public String accessKey; // // public class testConfig // { // public String name; // public String build; // public String tags; // public String customData; // } // // public class OSConfig // { // public String browserName; // } // // public ChromeOptions chromeOptions; // public String browserName; // // public static LinuxConfig withLinux() // { // return new LinuxConfig(); // } // } // Path: common/src/test/java/com/saucelabs/remotedriver/config/SauceConfigTest.java import com.saucelabs.remotedriver.config.SauceConfig; import org.junit.Test; package com.saucelabs.remotedriver.config; public class SauceConfigTest { @Test public void configuration_with_linux_should_allow_chrome_browser() {
SauceConfig config = new SauceConfig();
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/unit/SauceJavaScriptStringsTest.java
// Path: common/src/main/java/com/saucelabs/common/SauceApi.java // public class SauceApi { // // private WebDriver webDriver; // // public SauceApi(WebDriver webDriver) { // this.webDriver = webDriver; // } // // public SauceApi() { // } // // public void setTestStatus(String testResult) { // //TODO finish implementation // //testResult = testResult.toLowerCase(); // //isValidTestStatus(testResult); // new JavaScriptInvoker(webDriver). // executeScript(SauceJavaScriptStrings.testStatusPrefix + testResult); // } // // // private void isValidTestStatus(String testResult) throws InvalidTestStatusException { // // if(!testResult.equals("passed") || !testResult.equals("failed") || // // !testResult.equals("true") || !testResult.equals("false")) // // { // // throw new InvalidTestStatusException(); // // } // // } // // public void setTestName(String testName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.testNamePrefix + testName); // } // // public void setTestTags(String tags) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.tagsPrefix + tags); // } // // public void comment(String comment) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.sauceContextPrefix + comment); // } // // public void setBuildName(String buildName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.buildPrefix + buildName); // } // // public void setBreakpoint() { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.breakStatement); // } // } // // Path: common/src/main/java/com/saucelabs/common/SauceJavaScriptStrings.java // public class SauceJavaScriptStrings{ // public static String tagsPrefix = "sauce:job-tags="; // public static String sauceContextPrefix = "sauce:context="; // public static String testNamePrefix = "sauce:job-name="; // public static String buildPrefix = "sauce:job-build="; // public static String breakStatement = "sauce: break"; // public static String testStatusPrefix = "sauce:job-result="; // }
import com.saucelabs.common.SauceApi; import com.saucelabs.common.SauceJavaScriptStrings; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.assertEquals;
package com.saucelabs.common.unit; public class SauceJavaScriptStringsTest { @Test public void shouldBeCorrectTestNamePrefix() {
// Path: common/src/main/java/com/saucelabs/common/SauceApi.java // public class SauceApi { // // private WebDriver webDriver; // // public SauceApi(WebDriver webDriver) { // this.webDriver = webDriver; // } // // public SauceApi() { // } // // public void setTestStatus(String testResult) { // //TODO finish implementation // //testResult = testResult.toLowerCase(); // //isValidTestStatus(testResult); // new JavaScriptInvoker(webDriver). // executeScript(SauceJavaScriptStrings.testStatusPrefix + testResult); // } // // // private void isValidTestStatus(String testResult) throws InvalidTestStatusException { // // if(!testResult.equals("passed") || !testResult.equals("failed") || // // !testResult.equals("true") || !testResult.equals("false")) // // { // // throw new InvalidTestStatusException(); // // } // // } // // public void setTestName(String testName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.testNamePrefix + testName); // } // // public void setTestTags(String tags) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.tagsPrefix + tags); // } // // public void comment(String comment) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.sauceContextPrefix + comment); // } // // public void setBuildName(String buildName) { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.buildPrefix + buildName); // } // // public void setBreakpoint() { // new JavaScriptInvoker(webDriver).executeScript(SauceJavaScriptStrings.breakStatement); // } // } // // Path: common/src/main/java/com/saucelabs/common/SauceJavaScriptStrings.java // public class SauceJavaScriptStrings{ // public static String tagsPrefix = "sauce:job-tags="; // public static String sauceContextPrefix = "sauce:context="; // public static String testNamePrefix = "sauce:job-name="; // public static String buildPrefix = "sauce:job-build="; // public static String breakStatement = "sauce: break"; // public static String testStatusPrefix = "sauce:job-result="; // } // Path: common/src/test/java/com/saucelabs/common/unit/SauceJavaScriptStringsTest.java import com.saucelabs.common.SauceApi; import com.saucelabs.common.SauceJavaScriptStrings; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.assertEquals; package com.saucelabs.common.unit; public class SauceJavaScriptStringsTest { @Test public void shouldBeCorrectTestNamePrefix() {
Assert.assertEquals("sauce:job-name=", SauceJavaScriptStrings.testNamePrefix);
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerTest.java
// Path: common/src/main/java/com/saucelabs/common/JavaScriptInvoker.java // public class JavaScriptInvoker { // private JavaScriptExecutor jsInvokerImplementation; // public JavaScriptInvoker(WebDriver driver) // { // jsInvokerImplementation = JavaScriptInvokerFactory.create(driver); // } // public Object executeScript(String script){ // return jsInvokerImplementation.executeScript(script); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // }
import com.saucelabs.common.JavaScriptInvoker; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.mockito.Mockito.*;
package com.saucelabs.common.unit; public class JavaScriptInvokerTest extends BaseUnitTest { @Test public void shouldExecuteScriptOneTimeWhenMockManagerIsSet() {
// Path: common/src/main/java/com/saucelabs/common/JavaScriptInvoker.java // public class JavaScriptInvoker { // private JavaScriptExecutor jsInvokerImplementation; // public JavaScriptInvoker(WebDriver driver) // { // jsInvokerImplementation = JavaScriptInvokerFactory.create(driver); // } // public Object executeScript(String script){ // return jsInvokerImplementation.executeScript(script); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // } // Path: common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerTest.java import com.saucelabs.common.JavaScriptInvoker; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.mockito.Mockito.*; package com.saucelabs.common.unit; public class JavaScriptInvokerTest extends BaseUnitTest { @Test public void shouldExecuteScriptOneTimeWhenMockManagerIsSet() {
JavaScriptInvokerImpl mockJsManager = mock(JavaScriptInvokerImpl.class);
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerTest.java
// Path: common/src/main/java/com/saucelabs/common/JavaScriptInvoker.java // public class JavaScriptInvoker { // private JavaScriptExecutor jsInvokerImplementation; // public JavaScriptInvoker(WebDriver driver) // { // jsInvokerImplementation = JavaScriptInvokerFactory.create(driver); // } // public Object executeScript(String script){ // return jsInvokerImplementation.executeScript(script); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // }
import com.saucelabs.common.JavaScriptInvoker; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.mockito.Mockito.*;
package com.saucelabs.common.unit; public class JavaScriptInvokerTest extends BaseUnitTest { @Test public void shouldExecuteScriptOneTimeWhenMockManagerIsSet() { JavaScriptInvokerImpl mockJsManager = mock(JavaScriptInvokerImpl.class);
// Path: common/src/main/java/com/saucelabs/common/JavaScriptInvoker.java // public class JavaScriptInvoker { // private JavaScriptExecutor jsInvokerImplementation; // public JavaScriptInvoker(WebDriver driver) // { // jsInvokerImplementation = JavaScriptInvokerFactory.create(driver); // } // public Object executeScript(String script){ // return jsInvokerImplementation.executeScript(script); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // } // Path: common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerTest.java import com.saucelabs.common.JavaScriptInvoker; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.mockito.Mockito.*; package com.saucelabs.common.unit; public class JavaScriptInvokerTest extends BaseUnitTest { @Test public void shouldExecuteScriptOneTimeWhenMockManagerIsSet() { JavaScriptInvokerImpl mockJsManager = mock(JavaScriptInvokerImpl.class);
JavaScriptInvokerFactory.setJavaScriptExecutor(mockJsManager);
saucelabs/sauce-java
common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerTest.java
// Path: common/src/main/java/com/saucelabs/common/JavaScriptInvoker.java // public class JavaScriptInvoker { // private JavaScriptExecutor jsInvokerImplementation; // public JavaScriptInvoker(WebDriver driver) // { // jsInvokerImplementation = JavaScriptInvokerFactory.create(driver); // } // public Object executeScript(String script){ // return jsInvokerImplementation.executeScript(script); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // }
import com.saucelabs.common.JavaScriptInvoker; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.mockito.Mockito.*;
package com.saucelabs.common.unit; public class JavaScriptInvokerTest extends BaseUnitTest { @Test public void shouldExecuteScriptOneTimeWhenMockManagerIsSet() { JavaScriptInvokerImpl mockJsManager = mock(JavaScriptInvokerImpl.class); JavaScriptInvokerFactory.setJavaScriptExecutor(mockJsManager);
// Path: common/src/main/java/com/saucelabs/common/JavaScriptInvoker.java // public class JavaScriptInvoker { // private JavaScriptExecutor jsInvokerImplementation; // public JavaScriptInvoker(WebDriver driver) // { // jsInvokerImplementation = JavaScriptInvokerFactory.create(driver); // } // public Object executeScript(String script){ // return jsInvokerImplementation.executeScript(script); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerFactory.java // public class JavaScriptInvokerFactory { // private static JavaScriptExecutor customManager = null; // // public static void setJavaScriptExecutor(JavaScriptExecutor js) // { // customManager = js; // } // public static JavaScriptExecutor create(WebDriver driver) // { // if (customManager != null) // { // return customManager; // } // else // return new JavaScriptInvokerImpl(driver); // } // } // // Path: common/src/main/java/com/saucelabs/common/JavaScriptInvokerImpl.java // public class JavaScriptInvokerImpl implements JavaScriptExecutor { // private final WebDriver webDriver; // // // public JavaScriptInvokerImpl(WebDriver driver) // { // webDriver = driver; // } // // @Override // public Object executeScript(String script) { // JavascriptExecutor js = (JavascriptExecutor)webDriver; // return js.executeScript(script); // } // } // Path: common/src/test/java/com/saucelabs/common/unit/JavaScriptInvokerTest.java import com.saucelabs.common.JavaScriptInvoker; import com.saucelabs.common.JavaScriptInvokerFactory; import com.saucelabs.common.JavaScriptInvokerImpl; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.mockito.Mockito.*; package com.saucelabs.common.unit; public class JavaScriptInvokerTest extends BaseUnitTest { @Test public void shouldExecuteScriptOneTimeWhenMockManagerIsSet() { JavaScriptInvokerImpl mockJsManager = mock(JavaScriptInvokerImpl.class); JavaScriptInvokerFactory.setJavaScriptExecutor(mockJsManager);
JavaScriptInvoker js = new JavaScriptInvoker(mockWebDriver);
Tanaguru/Contrast-Finder
contrast-finder-hsv/src/test/java/org/opens/color/finder/hsv/ColorFinderRgbTest.java
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorCombinaison.java // public interface ColorCombinaison { // // // /** // * // * @return // */ // Float getGap(); // // /** // * // * @return // */ // Color getColor(); // // /** // * // * @param color // */ // void setColor(Color color); // // /** // * // * @return // */ // Double getContrast(); // // /** // * // * @param distance // */ // void setDistanceFromInitialColor(Double distance); // // /** // * // * @return // */ // Double getDistance(); // // /** // * // * @param threshold // */ // void setThreshold(Double threshold); // // /** // * // * @return // */ // Double getThreshold(); // // /** // * // * @return // */ // boolean isContrastValid(); // // /** // * // * @return // */ // Color getComparisonColor(); // // /** // * // * @param color // */ // void setComparisonColor(Color color); // // /** // * // * @param color // */ // String getHexaColor(); // // /** // * // * @return // */ // String getHslColor(); // // /** // * // * @param color // */ // String getHexaColorComp(); // // /** // * // * @return // */ // String getHslColorComp(); // }
import java.awt.Color; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.opens.colorfinder.result.ColorCombinaison;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.opens.color.finder.hsv; /** * * @author alingua */ public class ColorFinderRgbTest extends TestCase { private static final Logger LOGGER = Logger.getLogger(ColorFinderRgbTest.class); public ColorFinderRgbTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testFindColorsNearColorOrange() { System.out.println("FindColorsNearColor"); Color foregroundColor = new Color(255, 255, 255); Color backgroundColor = new Color(255, 192, 7); Float coefficientLevel = 3.0f; ColorFinderRgb instance = new ColorFinderRgb();
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorCombinaison.java // public interface ColorCombinaison { // // // /** // * // * @return // */ // Float getGap(); // // /** // * // * @return // */ // Color getColor(); // // /** // * // * @param color // */ // void setColor(Color color); // // /** // * // * @return // */ // Double getContrast(); // // /** // * // * @param distance // */ // void setDistanceFromInitialColor(Double distance); // // /** // * // * @return // */ // Double getDistance(); // // /** // * // * @param threshold // */ // void setThreshold(Double threshold); // // /** // * // * @return // */ // Double getThreshold(); // // /** // * // * @return // */ // boolean isContrastValid(); // // /** // * // * @return // */ // Color getComparisonColor(); // // /** // * // * @param color // */ // void setComparisonColor(Color color); // // /** // * // * @param color // */ // String getHexaColor(); // // /** // * // * @return // */ // String getHslColor(); // // /** // * // * @param color // */ // String getHexaColorComp(); // // /** // * // * @return // */ // String getHslColorComp(); // } // Path: contrast-finder-hsv/src/test/java/org/opens/color/finder/hsv/ColorFinderRgbTest.java import java.awt.Color; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.opens.colorfinder.result.ColorCombinaison; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.opens.color.finder.hsv; /** * * @author alingua */ public class ColorFinderRgbTest extends TestCase { private static final Logger LOGGER = Logger.getLogger(ColorFinderRgbTest.class); public ColorFinderRgbTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testFindColorsNearColorOrange() { System.out.println("FindColorsNearColor"); Color foregroundColor = new Color(255, 255, 255); Color backgroundColor = new Color(255, 192, 7); Float coefficientLevel = 3.0f; ColorFinderRgb instance = new ColorFinderRgb();
List<ColorCombinaison> colorCombinaison = new ArrayList<ColorCombinaison>();
Tanaguru/Contrast-Finder
contrast-finder-hsv/src/test/java/org/opens/color/finder/hsv/ColorFinderHsvTest.java
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorCombinaison.java // public interface ColorCombinaison { // // // /** // * // * @return // */ // Float getGap(); // // /** // * // * @return // */ // Color getColor(); // // /** // * // * @param color // */ // void setColor(Color color); // // /** // * // * @return // */ // Double getContrast(); // // /** // * // * @param distance // */ // void setDistanceFromInitialColor(Double distance); // // /** // * // * @return // */ // Double getDistance(); // // /** // * // * @param threshold // */ // void setThreshold(Double threshold); // // /** // * // * @return // */ // Double getThreshold(); // // /** // * // * @return // */ // boolean isContrastValid(); // // /** // * // * @return // */ // Color getComparisonColor(); // // /** // * // * @param color // */ // void setComparisonColor(Color color); // // /** // * // * @param color // */ // String getHexaColor(); // // /** // * // * @return // */ // String getHslColor(); // // /** // * // * @param color // */ // String getHexaColorComp(); // // /** // * // * @return // */ // String getHslColorComp(); // }
import java.awt.Color; import java.util.ArrayList; import java.util.List; import static junit.framework.Assert.assertEquals; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.opens.colorfinder.result.ColorCombinaison;
/* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.color.finder.hsv; /** * * @author alingua */ public class ColorFinderHsvTest extends TestCase { private static final Logger LOGGER = Logger.getLogger(ColorFinderHsvTest.class); public ColorFinderHsvTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test of findColors method, of class ColorFinderHsv. */ public void testFindColorsWithFgAndBg() { System.out.println("FindColorsWithFgAndBg"); Color foregroundColor = new Color(127, 127, 127); Color backgroundColor = new Color(128, 128, 128); Float coefficientLevel = 4.5f; ColorFinderHsv instance = new ColorFinderHsv(); instance.findColors(foregroundColor, backgroundColor, true, coefficientLevel);
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorCombinaison.java // public interface ColorCombinaison { // // // /** // * // * @return // */ // Float getGap(); // // /** // * // * @return // */ // Color getColor(); // // /** // * // * @param color // */ // void setColor(Color color); // // /** // * // * @return // */ // Double getContrast(); // // /** // * // * @param distance // */ // void setDistanceFromInitialColor(Double distance); // // /** // * // * @return // */ // Double getDistance(); // // /** // * // * @param threshold // */ // void setThreshold(Double threshold); // // /** // * // * @return // */ // Double getThreshold(); // // /** // * // * @return // */ // boolean isContrastValid(); // // /** // * // * @return // */ // Color getComparisonColor(); // // /** // * // * @param color // */ // void setComparisonColor(Color color); // // /** // * // * @param color // */ // String getHexaColor(); // // /** // * // * @return // */ // String getHslColor(); // // /** // * // * @param color // */ // String getHexaColorComp(); // // /** // * // * @return // */ // String getHslColorComp(); // } // Path: contrast-finder-hsv/src/test/java/org/opens/color/finder/hsv/ColorFinderHsvTest.java import java.awt.Color; import java.util.ArrayList; import java.util.List; import static junit.framework.Assert.assertEquals; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.opens.colorfinder.result.ColorCombinaison; /* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.color.finder.hsv; /** * * @author alingua */ public class ColorFinderHsvTest extends TestCase { private static final Logger LOGGER = Logger.getLogger(ColorFinderHsvTest.class); public ColorFinderHsvTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test of findColors method, of class ColorFinderHsv. */ public void testFindColorsWithFgAndBg() { System.out.println("FindColorsWithFgAndBg"); Color foregroundColor = new Color(127, 127, 127); Color backgroundColor = new Color(128, 128, 128); Float coefficientLevel = 4.5f; ColorFinderHsv instance = new ColorFinderHsv(); instance.findColors(foregroundColor, backgroundColor, true, coefficientLevel);
List<ColorCombinaison> colorCombinaison = new ArrayList<ColorCombinaison>();
Tanaguru/Contrast-Finder
contrast-finder-impl/src/main/java/org/opens/colorfinder/result/ColorResultImpl.java
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/factory/ColorCombinaisonFactory.java // public interface ColorCombinaisonFactory { // // /** // * // * @param color1 // * @param color2 // * @param threashold // * @return a ColorCombinaison instance // */ // ColorCombinaison getColorCombinaison(Color color1, Color color2, Double threashold); // // } // // Path: contrast-finder-utils/src/main/java/org/opens/utils/distancecalculator/DistanceCalculator.java // public final class DistanceCalculator { // // private static final int CUBIC = 3; // private static final int ROUND_VALUE = 100; // // private DistanceCalculator() { // } // // /** // * // * @param colorToChange // * @param colorToKeep // * @return the calculated distance between 2 colors regarding the // * distance definition that can be found here // * http://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions // */ // public static double calculate(Color colorToChange, Color colorToKeep) { // return (double) Math.round(Math.abs((Math.cbrt(Math.pow(Double.valueOf(colorToChange.getRed()) - Double.valueOf(colorToKeep.getRed()), CUBIC) // + Math.pow(Double.valueOf(colorToChange.getGreen()) - Double.valueOf(colorToKeep.getGreen()), CUBIC) // + Math.pow(Double.valueOf(colorToChange.getBlue()) - Double.valueOf(colorToKeep.getBlue()), CUBIC)))) * ROUND_VALUE) / ROUND_VALUE; // } // }
import java.awt.Color; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import org.opens.colorfinder.result.factory.ColorCombinaisonFactory; import org.opens.utils.distancecalculator.DistanceCalculator;
/* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder.result; /** * * @author alingua */ public class ColorResultImpl implements ColorResult { private static final int MAX_SUGGESTED_COLOR = 20; /* the colorCombinaisonFactory instance*/
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/factory/ColorCombinaisonFactory.java // public interface ColorCombinaisonFactory { // // /** // * // * @param color1 // * @param color2 // * @param threashold // * @return a ColorCombinaison instance // */ // ColorCombinaison getColorCombinaison(Color color1, Color color2, Double threashold); // // } // // Path: contrast-finder-utils/src/main/java/org/opens/utils/distancecalculator/DistanceCalculator.java // public final class DistanceCalculator { // // private static final int CUBIC = 3; // private static final int ROUND_VALUE = 100; // // private DistanceCalculator() { // } // // /** // * // * @param colorToChange // * @param colorToKeep // * @return the calculated distance between 2 colors regarding the // * distance definition that can be found here // * http://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions // */ // public static double calculate(Color colorToChange, Color colorToKeep) { // return (double) Math.round(Math.abs((Math.cbrt(Math.pow(Double.valueOf(colorToChange.getRed()) - Double.valueOf(colorToKeep.getRed()), CUBIC) // + Math.pow(Double.valueOf(colorToChange.getGreen()) - Double.valueOf(colorToKeep.getGreen()), CUBIC) // + Math.pow(Double.valueOf(colorToChange.getBlue()) - Double.valueOf(colorToKeep.getBlue()), CUBIC)))) * ROUND_VALUE) / ROUND_VALUE; // } // } // Path: contrast-finder-impl/src/main/java/org/opens/colorfinder/result/ColorResultImpl.java import java.awt.Color; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import org.opens.colorfinder.result.factory.ColorCombinaisonFactory; import org.opens.utils.distancecalculator.DistanceCalculator; /* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder.result; /** * * @author alingua */ public class ColorResultImpl implements ColorResult { private static final int MAX_SUGGESTED_COLOR = 20; /* the colorCombinaisonFactory instance*/
private ColorCombinaisonFactory colorCombinaisonFactory;
Tanaguru/Contrast-Finder
contrast-finder-impl/src/main/java/org/opens/colorfinder/result/ColorResultImpl.java
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/factory/ColorCombinaisonFactory.java // public interface ColorCombinaisonFactory { // // /** // * // * @param color1 // * @param color2 // * @param threashold // * @return a ColorCombinaison instance // */ // ColorCombinaison getColorCombinaison(Color color1, Color color2, Double threashold); // // } // // Path: contrast-finder-utils/src/main/java/org/opens/utils/distancecalculator/DistanceCalculator.java // public final class DistanceCalculator { // // private static final int CUBIC = 3; // private static final int ROUND_VALUE = 100; // // private DistanceCalculator() { // } // // /** // * // * @param colorToChange // * @param colorToKeep // * @return the calculated distance between 2 colors regarding the // * distance definition that can be found here // * http://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions // */ // public static double calculate(Color colorToChange, Color colorToKeep) { // return (double) Math.round(Math.abs((Math.cbrt(Math.pow(Double.valueOf(colorToChange.getRed()) - Double.valueOf(colorToKeep.getRed()), CUBIC) // + Math.pow(Double.valueOf(colorToChange.getGreen()) - Double.valueOf(colorToKeep.getGreen()), CUBIC) // + Math.pow(Double.valueOf(colorToChange.getBlue()) - Double.valueOf(colorToKeep.getBlue()), CUBIC)))) * ROUND_VALUE) / ROUND_VALUE; // } // }
import java.awt.Color; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import org.opens.colorfinder.result.factory.ColorCombinaisonFactory; import org.opens.utils.distancecalculator.DistanceCalculator;
public Float getThreashold() { return Float.valueOf(submittedColors.getThreshold().floatValue()); } @Override public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) { submittedColors = colorCombinaisonFactory.getColorCombinaison( colorToChange, colorToKeep, Double.valueOf(threashold)); } @Override public ColorCombinaison getSubmittedCombinaisonColor() { return submittedColors; } @Override public boolean isCombinaisonValid() { return submittedColors.isContrastValid(); } @Override public Collection<ColorCombinaison> getSuggestedColors() { return suggestedColors; } @Override public void addSuggestedColor(ColorCombinaison colorCombinaison) {
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/factory/ColorCombinaisonFactory.java // public interface ColorCombinaisonFactory { // // /** // * // * @param color1 // * @param color2 // * @param threashold // * @return a ColorCombinaison instance // */ // ColorCombinaison getColorCombinaison(Color color1, Color color2, Double threashold); // // } // // Path: contrast-finder-utils/src/main/java/org/opens/utils/distancecalculator/DistanceCalculator.java // public final class DistanceCalculator { // // private static final int CUBIC = 3; // private static final int ROUND_VALUE = 100; // // private DistanceCalculator() { // } // // /** // * // * @param colorToChange // * @param colorToKeep // * @return the calculated distance between 2 colors regarding the // * distance definition that can be found here // * http://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions // */ // public static double calculate(Color colorToChange, Color colorToKeep) { // return (double) Math.round(Math.abs((Math.cbrt(Math.pow(Double.valueOf(colorToChange.getRed()) - Double.valueOf(colorToKeep.getRed()), CUBIC) // + Math.pow(Double.valueOf(colorToChange.getGreen()) - Double.valueOf(colorToKeep.getGreen()), CUBIC) // + Math.pow(Double.valueOf(colorToChange.getBlue()) - Double.valueOf(colorToKeep.getBlue()), CUBIC)))) * ROUND_VALUE) / ROUND_VALUE; // } // } // Path: contrast-finder-impl/src/main/java/org/opens/colorfinder/result/ColorResultImpl.java import java.awt.Color; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import org.opens.colorfinder.result.factory.ColorCombinaisonFactory; import org.opens.utils.distancecalculator.DistanceCalculator; public Float getThreashold() { return Float.valueOf(submittedColors.getThreshold().floatValue()); } @Override public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) { submittedColors = colorCombinaisonFactory.getColorCombinaison( colorToChange, colorToKeep, Double.valueOf(threashold)); } @Override public ColorCombinaison getSubmittedCombinaisonColor() { return submittedColors; } @Override public boolean isCombinaisonValid() { return submittedColors.isContrastValid(); } @Override public Collection<ColorCombinaison> getSuggestedColors() { return suggestedColors; } @Override public void addSuggestedColor(ColorCombinaison colorCombinaison) {
colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor()));
Tanaguru/Contrast-Finder
contrast-finder-impl/src/main/java/org/opens/colorfinder/factory/ColorFinderFactoryImpl.java
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/ColorFinder.java // public interface ColorFinder { // // /** // * // * @param foregroundColor // * @param backgroundColor // * @param isBackgroundTested // * @param coefficientLevel // * @return // */ // void findColors ( // Color foregroundColor, // Color backgroundColor, // boolean isBackgroundTested, // Float coefficientLevel); // // /** // * // * @return // */ // ColorResult getColorResult(); // // /** // * // * @return a key that represents the colorFinder // */ // String getColorFinderKey(); // }
import org.opens.colorfinder.ColorFinder; import java.util.HashMap; import java.util.Map;
/* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder.factory; /** * * @author alingua */ public class ColorFinderFactoryImpl implements ColorFinderFactory { private Map<String, ColorFinderFactory> colorFinderMap = new HashMap<String, ColorFinderFactory>(); public void setColorFinderMap(Map<String, ColorFinderFactory> colorFinderMap) { this.colorFinderMap = colorFinderMap; } @Override
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/ColorFinder.java // public interface ColorFinder { // // /** // * // * @param foregroundColor // * @param backgroundColor // * @param isBackgroundTested // * @param coefficientLevel // * @return // */ // void findColors ( // Color foregroundColor, // Color backgroundColor, // boolean isBackgroundTested, // Float coefficientLevel); // // /** // * // * @return // */ // ColorResult getColorResult(); // // /** // * // * @return a key that represents the colorFinder // */ // String getColorFinderKey(); // } // Path: contrast-finder-impl/src/main/java/org/opens/colorfinder/factory/ColorFinderFactoryImpl.java import org.opens.colorfinder.ColorFinder; import java.util.HashMap; import java.util.Map; /* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder.factory; /** * * @author alingua */ public class ColorFinderFactoryImpl implements ColorFinderFactory { private Map<String, ColorFinderFactory> colorFinderMap = new HashMap<String, ColorFinderFactory>(); public void setColorFinderMap(Map<String, ColorFinderFactory> colorFinderMap) { this.colorFinderMap = colorFinderMap; } @Override
public ColorFinder getColorFinder(String colorFinderKey) {
Tanaguru/Contrast-Finder
contrast-finder-impl/src/main/java/org/opens/colorfinder/result/factory/ColorResultFactoryImpl.java
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorResult.java // public interface ColorResult { // // /** // * // * @param foreground // * @param backgroud // * @param threashold // */ // void setSubmittedColors(Color foreground, Color backgroud, Float threashold); // // /** // * // * @return // */ // ColorCombinaison getSubmittedCombinaisonColor(); // // /** // * // * @return // */ // boolean isCombinaisonValid(); // // /** // * // * @return // */ // Collection<ColorCombinaison> getSuggestedColors(); // // /** // * // * @return // */ // int getNumberOfSuggestedColors(); // // /** // * // * @param combinaison // */ // void addSuggestedColor(ColorCombinaison combinaison); // // /** // * // * @return // */ // Float getThreashold(); // // /** // * // * @return the number of tested colors // */ // int getNumberOfTestedColors(); // // /** // * set the number of tested colors // */ // void setNumberOfTestedColors(int testedColors); // // } // // Path: contrast-finder-impl/src/main/java/org/opens/colorfinder/result/ColorResultImpl.java // public class ColorResultImpl implements ColorResult { // // private static final int MAX_SUGGESTED_COLOR = 20; // /* the colorCombinaisonFactory instance*/ // private ColorCombinaisonFactory colorCombinaisonFactory; // /* the submitted color combinaison*/ // private ColorCombinaison submittedColors; // /* the suggested colors */ // private Set<ColorCombinaison> suggestedColors = // new LinkedHashSet<ColorCombinaison>(); // private int numberOfTestedColors; // // /* // * Constructor // */ // public ColorResultImpl(ColorCombinaisonFactory colorCombinaisonFactory) { // this.colorCombinaisonFactory = colorCombinaisonFactory; // } // // @Override // public Float getThreashold() { // return Float.valueOf(submittedColors.getThreshold().floatValue()); // } // // @Override // public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) { // submittedColors = // colorCombinaisonFactory.getColorCombinaison( // colorToChange, // colorToKeep, // Double.valueOf(threashold)); // } // // @Override // public ColorCombinaison getSubmittedCombinaisonColor() { // return submittedColors; // } // // @Override // public boolean isCombinaisonValid() { // return submittedColors.isContrastValid(); // } // // @Override // public Collection<ColorCombinaison> getSuggestedColors() { // return suggestedColors; // } // // @Override // public void addSuggestedColor(ColorCombinaison colorCombinaison) { // colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor())); // suggestedColors.add(colorCombinaison); // } // // @Override // public int getNumberOfSuggestedColors() { // return suggestedColors.size(); // } // // /** // * // * @return whether the max number suggested colors is reached // */ // public boolean isSuggestedColorsFull() { // return getNumberOfSuggestedColors() >= MAX_SUGGESTED_COLOR; // } // // @Override // public int getNumberOfTestedColors() { // return numberOfTestedColors; // } // // @Override // public void setNumberOfTestedColors(int numberOfTestedColors) { // this.numberOfTestedColors = numberOfTestedColors; // } // }
import org.opens.colorfinder.result.ColorResult; import org.opens.colorfinder.result.ColorResultImpl;
/* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder.result.factory; /** * * @author alingua */ public class ColorResultFactoryImpl implements ColorResultFactory { @Override
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorResult.java // public interface ColorResult { // // /** // * // * @param foreground // * @param backgroud // * @param threashold // */ // void setSubmittedColors(Color foreground, Color backgroud, Float threashold); // // /** // * // * @return // */ // ColorCombinaison getSubmittedCombinaisonColor(); // // /** // * // * @return // */ // boolean isCombinaisonValid(); // // /** // * // * @return // */ // Collection<ColorCombinaison> getSuggestedColors(); // // /** // * // * @return // */ // int getNumberOfSuggestedColors(); // // /** // * // * @param combinaison // */ // void addSuggestedColor(ColorCombinaison combinaison); // // /** // * // * @return // */ // Float getThreashold(); // // /** // * // * @return the number of tested colors // */ // int getNumberOfTestedColors(); // // /** // * set the number of tested colors // */ // void setNumberOfTestedColors(int testedColors); // // } // // Path: contrast-finder-impl/src/main/java/org/opens/colorfinder/result/ColorResultImpl.java // public class ColorResultImpl implements ColorResult { // // private static final int MAX_SUGGESTED_COLOR = 20; // /* the colorCombinaisonFactory instance*/ // private ColorCombinaisonFactory colorCombinaisonFactory; // /* the submitted color combinaison*/ // private ColorCombinaison submittedColors; // /* the suggested colors */ // private Set<ColorCombinaison> suggestedColors = // new LinkedHashSet<ColorCombinaison>(); // private int numberOfTestedColors; // // /* // * Constructor // */ // public ColorResultImpl(ColorCombinaisonFactory colorCombinaisonFactory) { // this.colorCombinaisonFactory = colorCombinaisonFactory; // } // // @Override // public Float getThreashold() { // return Float.valueOf(submittedColors.getThreshold().floatValue()); // } // // @Override // public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) { // submittedColors = // colorCombinaisonFactory.getColorCombinaison( // colorToChange, // colorToKeep, // Double.valueOf(threashold)); // } // // @Override // public ColorCombinaison getSubmittedCombinaisonColor() { // return submittedColors; // } // // @Override // public boolean isCombinaisonValid() { // return submittedColors.isContrastValid(); // } // // @Override // public Collection<ColorCombinaison> getSuggestedColors() { // return suggestedColors; // } // // @Override // public void addSuggestedColor(ColorCombinaison colorCombinaison) { // colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor())); // suggestedColors.add(colorCombinaison); // } // // @Override // public int getNumberOfSuggestedColors() { // return suggestedColors.size(); // } // // /** // * // * @return whether the max number suggested colors is reached // */ // public boolean isSuggestedColorsFull() { // return getNumberOfSuggestedColors() >= MAX_SUGGESTED_COLOR; // } // // @Override // public int getNumberOfTestedColors() { // return numberOfTestedColors; // } // // @Override // public void setNumberOfTestedColors(int numberOfTestedColors) { // this.numberOfTestedColors = numberOfTestedColors; // } // } // Path: contrast-finder-impl/src/main/java/org/opens/colorfinder/result/factory/ColorResultFactoryImpl.java import org.opens.colorfinder.result.ColorResult; import org.opens.colorfinder.result.ColorResultImpl; /* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder.result.factory; /** * * @author alingua */ public class ColorResultFactoryImpl implements ColorResultFactory { @Override
public ColorResult getColorResult() {
Tanaguru/Contrast-Finder
contrast-finder-impl/src/main/java/org/opens/colorfinder/result/factory/ColorResultFactoryImpl.java
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorResult.java // public interface ColorResult { // // /** // * // * @param foreground // * @param backgroud // * @param threashold // */ // void setSubmittedColors(Color foreground, Color backgroud, Float threashold); // // /** // * // * @return // */ // ColorCombinaison getSubmittedCombinaisonColor(); // // /** // * // * @return // */ // boolean isCombinaisonValid(); // // /** // * // * @return // */ // Collection<ColorCombinaison> getSuggestedColors(); // // /** // * // * @return // */ // int getNumberOfSuggestedColors(); // // /** // * // * @param combinaison // */ // void addSuggestedColor(ColorCombinaison combinaison); // // /** // * // * @return // */ // Float getThreashold(); // // /** // * // * @return the number of tested colors // */ // int getNumberOfTestedColors(); // // /** // * set the number of tested colors // */ // void setNumberOfTestedColors(int testedColors); // // } // // Path: contrast-finder-impl/src/main/java/org/opens/colorfinder/result/ColorResultImpl.java // public class ColorResultImpl implements ColorResult { // // private static final int MAX_SUGGESTED_COLOR = 20; // /* the colorCombinaisonFactory instance*/ // private ColorCombinaisonFactory colorCombinaisonFactory; // /* the submitted color combinaison*/ // private ColorCombinaison submittedColors; // /* the suggested colors */ // private Set<ColorCombinaison> suggestedColors = // new LinkedHashSet<ColorCombinaison>(); // private int numberOfTestedColors; // // /* // * Constructor // */ // public ColorResultImpl(ColorCombinaisonFactory colorCombinaisonFactory) { // this.colorCombinaisonFactory = colorCombinaisonFactory; // } // // @Override // public Float getThreashold() { // return Float.valueOf(submittedColors.getThreshold().floatValue()); // } // // @Override // public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) { // submittedColors = // colorCombinaisonFactory.getColorCombinaison( // colorToChange, // colorToKeep, // Double.valueOf(threashold)); // } // // @Override // public ColorCombinaison getSubmittedCombinaisonColor() { // return submittedColors; // } // // @Override // public boolean isCombinaisonValid() { // return submittedColors.isContrastValid(); // } // // @Override // public Collection<ColorCombinaison> getSuggestedColors() { // return suggestedColors; // } // // @Override // public void addSuggestedColor(ColorCombinaison colorCombinaison) { // colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor())); // suggestedColors.add(colorCombinaison); // } // // @Override // public int getNumberOfSuggestedColors() { // return suggestedColors.size(); // } // // /** // * // * @return whether the max number suggested colors is reached // */ // public boolean isSuggestedColorsFull() { // return getNumberOfSuggestedColors() >= MAX_SUGGESTED_COLOR; // } // // @Override // public int getNumberOfTestedColors() { // return numberOfTestedColors; // } // // @Override // public void setNumberOfTestedColors(int numberOfTestedColors) { // this.numberOfTestedColors = numberOfTestedColors; // } // }
import org.opens.colorfinder.result.ColorResult; import org.opens.colorfinder.result.ColorResultImpl;
/* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder.result.factory; /** * * @author alingua */ public class ColorResultFactoryImpl implements ColorResultFactory { @Override public ColorResult getColorResult() {
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorResult.java // public interface ColorResult { // // /** // * // * @param foreground // * @param backgroud // * @param threashold // */ // void setSubmittedColors(Color foreground, Color backgroud, Float threashold); // // /** // * // * @return // */ // ColorCombinaison getSubmittedCombinaisonColor(); // // /** // * // * @return // */ // boolean isCombinaisonValid(); // // /** // * // * @return // */ // Collection<ColorCombinaison> getSuggestedColors(); // // /** // * // * @return // */ // int getNumberOfSuggestedColors(); // // /** // * // * @param combinaison // */ // void addSuggestedColor(ColorCombinaison combinaison); // // /** // * // * @return // */ // Float getThreashold(); // // /** // * // * @return the number of tested colors // */ // int getNumberOfTestedColors(); // // /** // * set the number of tested colors // */ // void setNumberOfTestedColors(int testedColors); // // } // // Path: contrast-finder-impl/src/main/java/org/opens/colorfinder/result/ColorResultImpl.java // public class ColorResultImpl implements ColorResult { // // private static final int MAX_SUGGESTED_COLOR = 20; // /* the colorCombinaisonFactory instance*/ // private ColorCombinaisonFactory colorCombinaisonFactory; // /* the submitted color combinaison*/ // private ColorCombinaison submittedColors; // /* the suggested colors */ // private Set<ColorCombinaison> suggestedColors = // new LinkedHashSet<ColorCombinaison>(); // private int numberOfTestedColors; // // /* // * Constructor // */ // public ColorResultImpl(ColorCombinaisonFactory colorCombinaisonFactory) { // this.colorCombinaisonFactory = colorCombinaisonFactory; // } // // @Override // public Float getThreashold() { // return Float.valueOf(submittedColors.getThreshold().floatValue()); // } // // @Override // public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) { // submittedColors = // colorCombinaisonFactory.getColorCombinaison( // colorToChange, // colorToKeep, // Double.valueOf(threashold)); // } // // @Override // public ColorCombinaison getSubmittedCombinaisonColor() { // return submittedColors; // } // // @Override // public boolean isCombinaisonValid() { // return submittedColors.isContrastValid(); // } // // @Override // public Collection<ColorCombinaison> getSuggestedColors() { // return suggestedColors; // } // // @Override // public void addSuggestedColor(ColorCombinaison colorCombinaison) { // colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor())); // suggestedColors.add(colorCombinaison); // } // // @Override // public int getNumberOfSuggestedColors() { // return suggestedColors.size(); // } // // /** // * // * @return whether the max number suggested colors is reached // */ // public boolean isSuggestedColorsFull() { // return getNumberOfSuggestedColors() >= MAX_SUGGESTED_COLOR; // } // // @Override // public int getNumberOfTestedColors() { // return numberOfTestedColors; // } // // @Override // public void setNumberOfTestedColors(int numberOfTestedColors) { // this.numberOfTestedColors = numberOfTestedColors; // } // } // Path: contrast-finder-impl/src/main/java/org/opens/colorfinder/result/factory/ColorResultFactoryImpl.java import org.opens.colorfinder.result.ColorResult; import org.opens.colorfinder.result.ColorResultImpl; /* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder.result.factory; /** * * @author alingua */ public class ColorResultFactoryImpl implements ColorResultFactory { @Override public ColorResult getColorResult() {
return (new ColorResultImpl(new ColorCombinaisonFactoryImpl()));
Tanaguru/Contrast-Finder
contrast-finder-api/src/main/java/org/opens/colorfinder/ColorFinder.java
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorResult.java // public interface ColorResult { // // /** // * // * @param foreground // * @param backgroud // * @param threashold // */ // void setSubmittedColors(Color foreground, Color backgroud, Float threashold); // // /** // * // * @return // */ // ColorCombinaison getSubmittedCombinaisonColor(); // // /** // * // * @return // */ // boolean isCombinaisonValid(); // // /** // * // * @return // */ // Collection<ColorCombinaison> getSuggestedColors(); // // /** // * // * @return // */ // int getNumberOfSuggestedColors(); // // /** // * // * @param combinaison // */ // void addSuggestedColor(ColorCombinaison combinaison); // // /** // * // * @return // */ // Float getThreashold(); // // /** // * // * @return the number of tested colors // */ // int getNumberOfTestedColors(); // // /** // * set the number of tested colors // */ // void setNumberOfTestedColors(int testedColors); // // }
import java.awt.Color; import org.opens.colorfinder.result.ColorResult;
/* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder; /** * * @author alingua */ public interface ColorFinder { /** * * @param foregroundColor * @param backgroundColor * @param isBackgroundTested * @param coefficientLevel * @return */ void findColors ( Color foregroundColor, Color backgroundColor, boolean isBackgroundTested, Float coefficientLevel); /** * * @return */
// Path: contrast-finder-api/src/main/java/org/opens/colorfinder/result/ColorResult.java // public interface ColorResult { // // /** // * // * @param foreground // * @param backgroud // * @param threashold // */ // void setSubmittedColors(Color foreground, Color backgroud, Float threashold); // // /** // * // * @return // */ // ColorCombinaison getSubmittedCombinaisonColor(); // // /** // * // * @return // */ // boolean isCombinaisonValid(); // // /** // * // * @return // */ // Collection<ColorCombinaison> getSuggestedColors(); // // /** // * // * @return // */ // int getNumberOfSuggestedColors(); // // /** // * // * @param combinaison // */ // void addSuggestedColor(ColorCombinaison combinaison); // // /** // * // * @return // */ // Float getThreashold(); // // /** // * // * @return the number of tested colors // */ // int getNumberOfTestedColors(); // // /** // * set the number of tested colors // */ // void setNumberOfTestedColors(int testedColors); // // } // Path: contrast-finder-api/src/main/java/org/opens/colorfinder/ColorFinder.java import java.awt.Color; import org.opens.colorfinder.result.ColorResult; /* * Contrast Finder * Copyright (C) 2008-2013 Open-S Company * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: open-s AT open-s DOT com */ package org.opens.colorfinder; /** * * @author alingua */ public interface ColorFinder { /** * * @param foregroundColor * @param backgroundColor * @param isBackgroundTested * @param coefficientLevel * @return */ void findColors ( Color foregroundColor, Color backgroundColor, boolean isBackgroundTested, Float coefficientLevel); /** * * @return */
ColorResult getColorResult();
Doctoror/ParticlesDrawable
library/src/main/java/com/doctoror/particlesdrawable/engine/SceneConfigurator.java
// Path: library/src/main/java/com/doctoror/particlesdrawable/Defaults.java // public final class Defaults { // // private Defaults() { // throw new UnsupportedOperationException(); // } // // public static final int DENSITY = 60; // // public static final int FRAME_DELAY = 10; // // @ColorInt // public static final int LINE_COLOR = Color.WHITE; // // public static final float LINE_LENGTH = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 86, Resources.getSystem().getDisplayMetrics()); // // public static final float LINE_THICKNESS = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1, Resources.getSystem().getDisplayMetrics()); // // @ColorInt // public static final int PARTICLE_COLOR = Color.WHITE; // // public static final float PARTICLE_RADIUS_MAX = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 3f, Resources.getSystem().getDisplayMetrics()); // // public static final float PARTICLE_RADIUS_MIN = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1f, Resources.getSystem().getDisplayMetrics()); // // public static final float SPEED_FACTOR = 1f; // } // // Path: library/src/main/java/com/doctoror/particlesdrawable/contract/SceneConfiguration.java // @Keep // public interface SceneConfiguration { // // /** // * Set number of particles to draw per scene. // * // * @param density the number of particles to draw per scene // * @throws IllegalArgumentException if density is negative // */ // void setDensity(@IntRange(from = 0) int density); // // /** // * Returns the number of particles in the scene // * // * @return the number of particles in the scene // */ // int getDensity(); // // /** // * Set a delay per frame in milliseconds. // * // * @param delay delay between frames // * @throws IllegalArgumentException if delay is a negative number // */ // void setFrameDelay(@IntRange(from = 0) int delay); // // /** // * Returns a delay per frame in milliseconds. // * // * @return delay between frames // */ // int getFrameDelay(); // // /** // * Set the line color. Note that the color alpha is ignored and will be calculated depending on // * distance between particles. // * // * @param lineColor line color to use // */ // void setLineColor(@ColorInt int lineColor); // // /** // * Returns the connection line color // * // * @return the connection line color // */ // @ColorInt // int getLineColor(); // // /** // * Set the maximum distance when the connection line is still drawn between particles. // * // * @param lineLength maximum distance for connection lines // */ // void setLineLength(@FloatRange(from = 0) float lineLength); // // /** // * Returns the maximum distance when the connection line is still drawn between particles // * // * @return maximum distance for connection lines // */ // float getLineLength(); // // /** // * Set a line thickness // * // * @param lineThickness line thickness // */ // void setLineThickness(@FloatRange(from = 1) float lineThickness); // // /** // * Returns the connection like thickness // * // * @return the connection line thickness // */ // float getLineThickness(); // // /** // * Set the particle color // * // * @param color particle color to use // */ // void setParticleColor(@ColorInt int color); // // /** // * Returns the particle color // * // * @return the particle color // */ // @ColorInt // int getParticleColor(); // // /** // * Set particle radius range // * // * @param minRadius smallest particle radius // * @param maxRadius largest particle radius // */ // void setParticleRadiusRange( // @FloatRange(from = 0.5f) float minRadius, // @FloatRange(from = 0.5f) float maxRadius); // // /** // * Largest particle radius // * // * @return largest particle radius // */ // float getParticleRadiusMax(); // // /** // * Returns smallest particle radius // * // * @return smallest particle radius // */ // float getParticleRadiusMin(); // // /** // * Sets speed factor. Use this to control speed. // * // * @param speedFactor speed factor // */ // void setSpeedFactor(@FloatRange(from = 0) final float speedFactor); // // /** // * Returns the speed factor. // * // * @return the speed factor // */ // float getSpeedFactor(); // }
import android.content.res.Resources; import android.content.res.TypedArray; import android.util.AttributeSet; import com.doctoror.particlesdrawable.Defaults; import com.doctoror.particlesdrawable.R; import com.doctoror.particlesdrawable.contract.SceneConfiguration; import androidx.annotation.Keep; import androidx.annotation.NonNull;
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.engine; @Keep public final class SceneConfigurator { public void configureSceneFromAttributes(
// Path: library/src/main/java/com/doctoror/particlesdrawable/Defaults.java // public final class Defaults { // // private Defaults() { // throw new UnsupportedOperationException(); // } // // public static final int DENSITY = 60; // // public static final int FRAME_DELAY = 10; // // @ColorInt // public static final int LINE_COLOR = Color.WHITE; // // public static final float LINE_LENGTH = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 86, Resources.getSystem().getDisplayMetrics()); // // public static final float LINE_THICKNESS = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1, Resources.getSystem().getDisplayMetrics()); // // @ColorInt // public static final int PARTICLE_COLOR = Color.WHITE; // // public static final float PARTICLE_RADIUS_MAX = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 3f, Resources.getSystem().getDisplayMetrics()); // // public static final float PARTICLE_RADIUS_MIN = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1f, Resources.getSystem().getDisplayMetrics()); // // public static final float SPEED_FACTOR = 1f; // } // // Path: library/src/main/java/com/doctoror/particlesdrawable/contract/SceneConfiguration.java // @Keep // public interface SceneConfiguration { // // /** // * Set number of particles to draw per scene. // * // * @param density the number of particles to draw per scene // * @throws IllegalArgumentException if density is negative // */ // void setDensity(@IntRange(from = 0) int density); // // /** // * Returns the number of particles in the scene // * // * @return the number of particles in the scene // */ // int getDensity(); // // /** // * Set a delay per frame in milliseconds. // * // * @param delay delay between frames // * @throws IllegalArgumentException if delay is a negative number // */ // void setFrameDelay(@IntRange(from = 0) int delay); // // /** // * Returns a delay per frame in milliseconds. // * // * @return delay between frames // */ // int getFrameDelay(); // // /** // * Set the line color. Note that the color alpha is ignored and will be calculated depending on // * distance between particles. // * // * @param lineColor line color to use // */ // void setLineColor(@ColorInt int lineColor); // // /** // * Returns the connection line color // * // * @return the connection line color // */ // @ColorInt // int getLineColor(); // // /** // * Set the maximum distance when the connection line is still drawn between particles. // * // * @param lineLength maximum distance for connection lines // */ // void setLineLength(@FloatRange(from = 0) float lineLength); // // /** // * Returns the maximum distance when the connection line is still drawn between particles // * // * @return maximum distance for connection lines // */ // float getLineLength(); // // /** // * Set a line thickness // * // * @param lineThickness line thickness // */ // void setLineThickness(@FloatRange(from = 1) float lineThickness); // // /** // * Returns the connection like thickness // * // * @return the connection line thickness // */ // float getLineThickness(); // // /** // * Set the particle color // * // * @param color particle color to use // */ // void setParticleColor(@ColorInt int color); // // /** // * Returns the particle color // * // * @return the particle color // */ // @ColorInt // int getParticleColor(); // // /** // * Set particle radius range // * // * @param minRadius smallest particle radius // * @param maxRadius largest particle radius // */ // void setParticleRadiusRange( // @FloatRange(from = 0.5f) float minRadius, // @FloatRange(from = 0.5f) float maxRadius); // // /** // * Largest particle radius // * // * @return largest particle radius // */ // float getParticleRadiusMax(); // // /** // * Returns smallest particle radius // * // * @return smallest particle radius // */ // float getParticleRadiusMin(); // // /** // * Sets speed factor. Use this to control speed. // * // * @param speedFactor speed factor // */ // void setSpeedFactor(@FloatRange(from = 0) final float speedFactor); // // /** // * Returns the speed factor. // * // * @return the speed factor // */ // float getSpeedFactor(); // } // Path: library/src/main/java/com/doctoror/particlesdrawable/engine/SceneConfigurator.java import android.content.res.Resources; import android.content.res.TypedArray; import android.util.AttributeSet; import com.doctoror.particlesdrawable.Defaults; import com.doctoror.particlesdrawable.R; import com.doctoror.particlesdrawable.contract.SceneConfiguration; import androidx.annotation.Keep; import androidx.annotation.NonNull; /* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.engine; @Keep public final class SceneConfigurator { public void configureSceneFromAttributes(
@NonNull final SceneConfiguration scene,
Doctoror/ParticlesDrawable
library/src/main/java/com/doctoror/particlesdrawable/engine/SceneConfigurator.java
// Path: library/src/main/java/com/doctoror/particlesdrawable/Defaults.java // public final class Defaults { // // private Defaults() { // throw new UnsupportedOperationException(); // } // // public static final int DENSITY = 60; // // public static final int FRAME_DELAY = 10; // // @ColorInt // public static final int LINE_COLOR = Color.WHITE; // // public static final float LINE_LENGTH = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 86, Resources.getSystem().getDisplayMetrics()); // // public static final float LINE_THICKNESS = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1, Resources.getSystem().getDisplayMetrics()); // // @ColorInt // public static final int PARTICLE_COLOR = Color.WHITE; // // public static final float PARTICLE_RADIUS_MAX = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 3f, Resources.getSystem().getDisplayMetrics()); // // public static final float PARTICLE_RADIUS_MIN = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1f, Resources.getSystem().getDisplayMetrics()); // // public static final float SPEED_FACTOR = 1f; // } // // Path: library/src/main/java/com/doctoror/particlesdrawable/contract/SceneConfiguration.java // @Keep // public interface SceneConfiguration { // // /** // * Set number of particles to draw per scene. // * // * @param density the number of particles to draw per scene // * @throws IllegalArgumentException if density is negative // */ // void setDensity(@IntRange(from = 0) int density); // // /** // * Returns the number of particles in the scene // * // * @return the number of particles in the scene // */ // int getDensity(); // // /** // * Set a delay per frame in milliseconds. // * // * @param delay delay between frames // * @throws IllegalArgumentException if delay is a negative number // */ // void setFrameDelay(@IntRange(from = 0) int delay); // // /** // * Returns a delay per frame in milliseconds. // * // * @return delay between frames // */ // int getFrameDelay(); // // /** // * Set the line color. Note that the color alpha is ignored and will be calculated depending on // * distance between particles. // * // * @param lineColor line color to use // */ // void setLineColor(@ColorInt int lineColor); // // /** // * Returns the connection line color // * // * @return the connection line color // */ // @ColorInt // int getLineColor(); // // /** // * Set the maximum distance when the connection line is still drawn between particles. // * // * @param lineLength maximum distance for connection lines // */ // void setLineLength(@FloatRange(from = 0) float lineLength); // // /** // * Returns the maximum distance when the connection line is still drawn between particles // * // * @return maximum distance for connection lines // */ // float getLineLength(); // // /** // * Set a line thickness // * // * @param lineThickness line thickness // */ // void setLineThickness(@FloatRange(from = 1) float lineThickness); // // /** // * Returns the connection like thickness // * // * @return the connection line thickness // */ // float getLineThickness(); // // /** // * Set the particle color // * // * @param color particle color to use // */ // void setParticleColor(@ColorInt int color); // // /** // * Returns the particle color // * // * @return the particle color // */ // @ColorInt // int getParticleColor(); // // /** // * Set particle radius range // * // * @param minRadius smallest particle radius // * @param maxRadius largest particle radius // */ // void setParticleRadiusRange( // @FloatRange(from = 0.5f) float minRadius, // @FloatRange(from = 0.5f) float maxRadius); // // /** // * Largest particle radius // * // * @return largest particle radius // */ // float getParticleRadiusMax(); // // /** // * Returns smallest particle radius // * // * @return smallest particle radius // */ // float getParticleRadiusMin(); // // /** // * Sets speed factor. Use this to control speed. // * // * @param speedFactor speed factor // */ // void setSpeedFactor(@FloatRange(from = 0) final float speedFactor); // // /** // * Returns the speed factor. // * // * @return the speed factor // */ // float getSpeedFactor(); // }
import android.content.res.Resources; import android.content.res.TypedArray; import android.util.AttributeSet; import com.doctoror.particlesdrawable.Defaults; import com.doctoror.particlesdrawable.R; import com.doctoror.particlesdrawable.contract.SceneConfiguration; import androidx.annotation.Keep; import androidx.annotation.NonNull;
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.engine; @Keep public final class SceneConfigurator { public void configureSceneFromAttributes( @NonNull final SceneConfiguration scene, @NonNull final Resources r, @NonNull final AttributeSet attrs) { final TypedArray a = r.obtainAttributes(attrs, R.styleable.ParticlesView); try { final int count = a.getIndexCount();
// Path: library/src/main/java/com/doctoror/particlesdrawable/Defaults.java // public final class Defaults { // // private Defaults() { // throw new UnsupportedOperationException(); // } // // public static final int DENSITY = 60; // // public static final int FRAME_DELAY = 10; // // @ColorInt // public static final int LINE_COLOR = Color.WHITE; // // public static final float LINE_LENGTH = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 86, Resources.getSystem().getDisplayMetrics()); // // public static final float LINE_THICKNESS = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1, Resources.getSystem().getDisplayMetrics()); // // @ColorInt // public static final int PARTICLE_COLOR = Color.WHITE; // // public static final float PARTICLE_RADIUS_MAX = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 3f, Resources.getSystem().getDisplayMetrics()); // // public static final float PARTICLE_RADIUS_MIN = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1f, Resources.getSystem().getDisplayMetrics()); // // public static final float SPEED_FACTOR = 1f; // } // // Path: library/src/main/java/com/doctoror/particlesdrawable/contract/SceneConfiguration.java // @Keep // public interface SceneConfiguration { // // /** // * Set number of particles to draw per scene. // * // * @param density the number of particles to draw per scene // * @throws IllegalArgumentException if density is negative // */ // void setDensity(@IntRange(from = 0) int density); // // /** // * Returns the number of particles in the scene // * // * @return the number of particles in the scene // */ // int getDensity(); // // /** // * Set a delay per frame in milliseconds. // * // * @param delay delay between frames // * @throws IllegalArgumentException if delay is a negative number // */ // void setFrameDelay(@IntRange(from = 0) int delay); // // /** // * Returns a delay per frame in milliseconds. // * // * @return delay between frames // */ // int getFrameDelay(); // // /** // * Set the line color. Note that the color alpha is ignored and will be calculated depending on // * distance between particles. // * // * @param lineColor line color to use // */ // void setLineColor(@ColorInt int lineColor); // // /** // * Returns the connection line color // * // * @return the connection line color // */ // @ColorInt // int getLineColor(); // // /** // * Set the maximum distance when the connection line is still drawn between particles. // * // * @param lineLength maximum distance for connection lines // */ // void setLineLength(@FloatRange(from = 0) float lineLength); // // /** // * Returns the maximum distance when the connection line is still drawn between particles // * // * @return maximum distance for connection lines // */ // float getLineLength(); // // /** // * Set a line thickness // * // * @param lineThickness line thickness // */ // void setLineThickness(@FloatRange(from = 1) float lineThickness); // // /** // * Returns the connection like thickness // * // * @return the connection line thickness // */ // float getLineThickness(); // // /** // * Set the particle color // * // * @param color particle color to use // */ // void setParticleColor(@ColorInt int color); // // /** // * Returns the particle color // * // * @return the particle color // */ // @ColorInt // int getParticleColor(); // // /** // * Set particle radius range // * // * @param minRadius smallest particle radius // * @param maxRadius largest particle radius // */ // void setParticleRadiusRange( // @FloatRange(from = 0.5f) float minRadius, // @FloatRange(from = 0.5f) float maxRadius); // // /** // * Largest particle radius // * // * @return largest particle radius // */ // float getParticleRadiusMax(); // // /** // * Returns smallest particle radius // * // * @return smallest particle radius // */ // float getParticleRadiusMin(); // // /** // * Sets speed factor. Use this to control speed. // * // * @param speedFactor speed factor // */ // void setSpeedFactor(@FloatRange(from = 0) final float speedFactor); // // /** // * Returns the speed factor. // * // * @return the speed factor // */ // float getSpeedFactor(); // } // Path: library/src/main/java/com/doctoror/particlesdrawable/engine/SceneConfigurator.java import android.content.res.Resources; import android.content.res.TypedArray; import android.util.AttributeSet; import com.doctoror.particlesdrawable.Defaults; import com.doctoror.particlesdrawable.R; import com.doctoror.particlesdrawable.contract.SceneConfiguration; import androidx.annotation.Keep; import androidx.annotation.NonNull; /* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.engine; @Keep public final class SceneConfigurator { public void configureSceneFromAttributes( @NonNull final SceneConfiguration scene, @NonNull final Resources r, @NonNull final AttributeSet attrs) { final TypedArray a = r.obtainAttributes(attrs, R.styleable.ParticlesView); try { final int count = a.getIndexCount();
float particleRadiusMax = Defaults.PARTICLE_RADIUS_MAX;
Doctoror/ParticlesDrawable
opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/GLErrorChecker.java
// Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/GlException.java // @KeepAsApi // public final class GlException extends RuntimeException { // // private final int glError; // // /** // * @param glError the error read from glGetError. // * @param tag custom tag to include in exception message. // */ // public GlException(final int glError, @NonNull final String tag) { // super("GLError: " + glError + ", tag: " + tag); // this.glError = glError; // } // // /** // * @return the error read from glGetError. // */ // @SuppressWarnings("unused") // public int getGlError() { // return glError; // } // }
import android.opengl.GLES20; import android.util.Log; import com.doctoror.particlesdrawable.KeepAsApi; import com.doctoror.particlesdrawable.opengl.GlException; import androidx.annotation.NonNull;
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.opengl.util; @KeepAsApi public final class GLErrorChecker { private static boolean shouldThrowOnGlError = true; private static boolean shouldCheckGlError = true; public static void setShouldCheckGlError(final boolean shouldCheckGlError) { GLErrorChecker.shouldCheckGlError = shouldCheckGlError; } public static void setShouldThrowOnGlError(final boolean shouldThrowOnGlError) { GLErrorChecker.shouldThrowOnGlError = shouldThrowOnGlError; } public static void checkGlError(@NonNull final String tag) { if (shouldCheckGlError) { final int error = GLES20.glGetError(); if (error != GLES20.GL_NO_ERROR) { if (shouldThrowOnGlError) {
// Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/GlException.java // @KeepAsApi // public final class GlException extends RuntimeException { // // private final int glError; // // /** // * @param glError the error read from glGetError. // * @param tag custom tag to include in exception message. // */ // public GlException(final int glError, @NonNull final String tag) { // super("GLError: " + glError + ", tag: " + tag); // this.glError = glError; // } // // /** // * @return the error read from glGetError. // */ // @SuppressWarnings("unused") // public int getGlError() { // return glError; // } // } // Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/GLErrorChecker.java import android.opengl.GLES20; import android.util.Log; import com.doctoror.particlesdrawable.KeepAsApi; import com.doctoror.particlesdrawable.opengl.GlException; import androidx.annotation.NonNull; /* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.opengl.util; @KeepAsApi public final class GLErrorChecker { private static boolean shouldThrowOnGlError = true; private static boolean shouldCheckGlError = true; public static void setShouldCheckGlError(final boolean shouldCheckGlError) { GLErrorChecker.shouldCheckGlError = shouldCheckGlError; } public static void setShouldThrowOnGlError(final boolean shouldThrowOnGlError) { GLErrorChecker.shouldThrowOnGlError = shouldThrowOnGlError; } public static void checkGlError(@NonNull final String tag) { if (shouldCheckGlError) { final int error = GLES20.glGetError(); if (error != GLES20.GL_NO_ERROR) { if (shouldThrowOnGlError) {
throw new GlException(error, tag);
Doctoror/ParticlesDrawable
library/src/main/java/com/doctoror/particlesdrawable/model/Scene.java
// Path: library/src/main/java/com/doctoror/particlesdrawable/Defaults.java // public final class Defaults { // // private Defaults() { // throw new UnsupportedOperationException(); // } // // public static final int DENSITY = 60; // // public static final int FRAME_DELAY = 10; // // @ColorInt // public static final int LINE_COLOR = Color.WHITE; // // public static final float LINE_LENGTH = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 86, Resources.getSystem().getDisplayMetrics()); // // public static final float LINE_THICKNESS = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1, Resources.getSystem().getDisplayMetrics()); // // @ColorInt // public static final int PARTICLE_COLOR = Color.WHITE; // // public static final float PARTICLE_RADIUS_MAX = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 3f, Resources.getSystem().getDisplayMetrics()); // // public static final float PARTICLE_RADIUS_MIN = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1f, Resources.getSystem().getDisplayMetrics()); // // public static final float SPEED_FACTOR = 1f; // } // // Path: library/src/main/java/com/doctoror/particlesdrawable/contract/SceneConfiguration.java // @Keep // public interface SceneConfiguration { // // /** // * Set number of particles to draw per scene. // * // * @param density the number of particles to draw per scene // * @throws IllegalArgumentException if density is negative // */ // void setDensity(@IntRange(from = 0) int density); // // /** // * Returns the number of particles in the scene // * // * @return the number of particles in the scene // */ // int getDensity(); // // /** // * Set a delay per frame in milliseconds. // * // * @param delay delay between frames // * @throws IllegalArgumentException if delay is a negative number // */ // void setFrameDelay(@IntRange(from = 0) int delay); // // /** // * Returns a delay per frame in milliseconds. // * // * @return delay between frames // */ // int getFrameDelay(); // // /** // * Set the line color. Note that the color alpha is ignored and will be calculated depending on // * distance between particles. // * // * @param lineColor line color to use // */ // void setLineColor(@ColorInt int lineColor); // // /** // * Returns the connection line color // * // * @return the connection line color // */ // @ColorInt // int getLineColor(); // // /** // * Set the maximum distance when the connection line is still drawn between particles. // * // * @param lineLength maximum distance for connection lines // */ // void setLineLength(@FloatRange(from = 0) float lineLength); // // /** // * Returns the maximum distance when the connection line is still drawn between particles // * // * @return maximum distance for connection lines // */ // float getLineLength(); // // /** // * Set a line thickness // * // * @param lineThickness line thickness // */ // void setLineThickness(@FloatRange(from = 1) float lineThickness); // // /** // * Returns the connection like thickness // * // * @return the connection line thickness // */ // float getLineThickness(); // // /** // * Set the particle color // * // * @param color particle color to use // */ // void setParticleColor(@ColorInt int color); // // /** // * Returns the particle color // * // * @return the particle color // */ // @ColorInt // int getParticleColor(); // // /** // * Set particle radius range // * // * @param minRadius smallest particle radius // * @param maxRadius largest particle radius // */ // void setParticleRadiusRange( // @FloatRange(from = 0.5f) float minRadius, // @FloatRange(from = 0.5f) float maxRadius); // // /** // * Largest particle radius // * // * @return largest particle radius // */ // float getParticleRadiusMax(); // // /** // * Returns smallest particle radius // * // * @return smallest particle radius // */ // float getParticleRadiusMin(); // // /** // * Sets speed factor. Use this to control speed. // * // * @param speedFactor speed factor // */ // void setSpeedFactor(@FloatRange(from = 0) final float speedFactor); // // /** // * Returns the speed factor. // * // * @return the speed factor // */ // float getSpeedFactor(); // }
import com.doctoror.particlesdrawable.Defaults; import com.doctoror.particlesdrawable.KeepAsApi; import com.doctoror.particlesdrawable.contract.SceneConfiguration; import java.nio.FloatBuffer; import java.util.Locale; import androidx.annotation.ColorInt; import androidx.annotation.FloatRange; import androidx.annotation.IntRange; import androidx.annotation.NonNull;
/* * Copyright (C) 2017 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.model; @KeepAsApi public final class Scene implements SceneConfiguration { private static final int COORDINATES_PER_VERTEX = 2; // The alpha value of the scene private int alpha = 255;
// Path: library/src/main/java/com/doctoror/particlesdrawable/Defaults.java // public final class Defaults { // // private Defaults() { // throw new UnsupportedOperationException(); // } // // public static final int DENSITY = 60; // // public static final int FRAME_DELAY = 10; // // @ColorInt // public static final int LINE_COLOR = Color.WHITE; // // public static final float LINE_LENGTH = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 86, Resources.getSystem().getDisplayMetrics()); // // public static final float LINE_THICKNESS = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1, Resources.getSystem().getDisplayMetrics()); // // @ColorInt // public static final int PARTICLE_COLOR = Color.WHITE; // // public static final float PARTICLE_RADIUS_MAX = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 3f, Resources.getSystem().getDisplayMetrics()); // // public static final float PARTICLE_RADIUS_MIN = TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 1f, Resources.getSystem().getDisplayMetrics()); // // public static final float SPEED_FACTOR = 1f; // } // // Path: library/src/main/java/com/doctoror/particlesdrawable/contract/SceneConfiguration.java // @Keep // public interface SceneConfiguration { // // /** // * Set number of particles to draw per scene. // * // * @param density the number of particles to draw per scene // * @throws IllegalArgumentException if density is negative // */ // void setDensity(@IntRange(from = 0) int density); // // /** // * Returns the number of particles in the scene // * // * @return the number of particles in the scene // */ // int getDensity(); // // /** // * Set a delay per frame in milliseconds. // * // * @param delay delay between frames // * @throws IllegalArgumentException if delay is a negative number // */ // void setFrameDelay(@IntRange(from = 0) int delay); // // /** // * Returns a delay per frame in milliseconds. // * // * @return delay between frames // */ // int getFrameDelay(); // // /** // * Set the line color. Note that the color alpha is ignored and will be calculated depending on // * distance between particles. // * // * @param lineColor line color to use // */ // void setLineColor(@ColorInt int lineColor); // // /** // * Returns the connection line color // * // * @return the connection line color // */ // @ColorInt // int getLineColor(); // // /** // * Set the maximum distance when the connection line is still drawn between particles. // * // * @param lineLength maximum distance for connection lines // */ // void setLineLength(@FloatRange(from = 0) float lineLength); // // /** // * Returns the maximum distance when the connection line is still drawn between particles // * // * @return maximum distance for connection lines // */ // float getLineLength(); // // /** // * Set a line thickness // * // * @param lineThickness line thickness // */ // void setLineThickness(@FloatRange(from = 1) float lineThickness); // // /** // * Returns the connection like thickness // * // * @return the connection line thickness // */ // float getLineThickness(); // // /** // * Set the particle color // * // * @param color particle color to use // */ // void setParticleColor(@ColorInt int color); // // /** // * Returns the particle color // * // * @return the particle color // */ // @ColorInt // int getParticleColor(); // // /** // * Set particle radius range // * // * @param minRadius smallest particle radius // * @param maxRadius largest particle radius // */ // void setParticleRadiusRange( // @FloatRange(from = 0.5f) float minRadius, // @FloatRange(from = 0.5f) float maxRadius); // // /** // * Largest particle radius // * // * @return largest particle radius // */ // float getParticleRadiusMax(); // // /** // * Returns smallest particle radius // * // * @return smallest particle radius // */ // float getParticleRadiusMin(); // // /** // * Sets speed factor. Use this to control speed. // * // * @param speedFactor speed factor // */ // void setSpeedFactor(@FloatRange(from = 0) final float speedFactor); // // /** // * Returns the speed factor. // * // * @return the speed factor // */ // float getSpeedFactor(); // } // Path: library/src/main/java/com/doctoror/particlesdrawable/model/Scene.java import com.doctoror.particlesdrawable.Defaults; import com.doctoror.particlesdrawable.KeepAsApi; import com.doctoror.particlesdrawable.contract.SceneConfiguration; import java.nio.FloatBuffer; import java.util.Locale; import androidx.annotation.ColorInt; import androidx.annotation.FloatRange; import androidx.annotation.IntRange; import androidx.annotation.NonNull; /* * Copyright (C) 2017 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.model; @KeepAsApi public final class Scene implements SceneConfiguration { private static final int COORDINATES_PER_VERTEX = 2; // The alpha value of the scene private int alpha = 255;
private int density = Defaults.DENSITY;